我是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
有人能帮我处理这个问题吗?提前谢谢!
2条答案
按热度按时间vyu0f0g11#
首先,您没有将输入转换为数字。这意味着任何以
'6'
大于以'2'
,即使是像'6.38'
以及'198.86'
.接下来,您将设置
oldSale
至0
,但从未提及。我想你是故意的maxSale = 0
在那里,为新商店重置值。最后,你不需要
oldKey = thisKey;
在if
阻止,因为你马上就要这么做了。请注意,当您将值转换为该货币的最小面额并使用整数时,货币计算效果最佳,因为浮点计算并不总是完全准确的,而且可能会出现舍入错误。看起来您的数据不能保证有尾随的零,因此您必须检查字符串中是否有小数点,如果存在小数点,则在小数点上拆分,等等。
对表示美分数的整数执行财务计算,然后根据显示需要将值格式化为美元和美分:
aoyhnmkz2#