我是python的新手,今天我写了一个程序从一些数据集中获取最大值对,但是我写的程序没有给我正确的答案,代码是
#!/usr/bin/python
import sys
maxsale = 0
oldKey = None
# Loop around the data
# It will be in the format key\tval
# Where key is the store name, val is the sale amount
#
# All the sales for a particular store will be presented,
# then the key will change and we'll be dealing with the next store
for line in sys.stdin:
data_mapped = line.strip().split("\t")
if len(data_mapped) != 2:
# Something has gone wrong. Skip this line.
continue
thisKey, thisSale = data_mapped
if oldKey and oldKey != thisKey:
print oldKey, "\t", maxsale
oldKey = thisKey;
oldsale = 0
oldKey = thisKey
if maxsale < thisSale:
maxsale = thisSale
if oldKey != None:
print oldKey, "\t", maxsale
数据集是:
Anchorage 298.86
Anchorage 6.38
Aurora 34.1
Aurora 10.6
Aurora 55.7
Austin 327.75
Austin 379.6
Austin 469.63
Austin 11.6
结果是:
Anchorage 6.38
Aurora 34.1
Austin 469.63
有人能帮我处理这个问题吗?提前谢谢!你知道吗
首先,您没有将输入转换为数字。这意味着任何以
'6'
开头的“数”都大于任何以'2'
开头的“数”,即使是像'6.38'
和'198.86'
这样的值。你知道吗接下来,将
oldSale
设置为0
,但从不引用它。我想你是想在那里做maxSale = 0
,重置一个新商店的值。你知道吗最后,您不需要在
if
块中使用oldKey = thisKey;
,因为您会在之后立即这样做。你知道吗请注意,当您将值转换为该货币的最小面额并使用整数时,货币计算效果最佳,因为浮点计算并不总是完全准确的,而且可能会出现舍入错误。看起来您的数据不能保证有尾随的零,因此您必须检查字符串中是否有小数点,如果存在小数点,则在小数点上拆分,等等。你知道吗
对表示美分数的整数执行财务计算,然后根据显示需要将值格式化为美元和美分:
相关问题 更多 >
编程相关推荐