我正在用Python做关于机票价格的课程作业。我的布尔函数返回现在购买机票还是等待更长时间购买机票,其中True表示现在购买,False表示等待更长时间:
def should_I_buy(data, input_price, input_day):
"""Returns whether one should buy flight ticket now or wait longer to buy"""
for day, price in data:
if day < input_day:
if price < input_price:
return False
return True
我还想找到一种方法来计算当我放入一个随机的input_price和input_day时,循环中有多少真和假。
发布于 2019-04-09 10:50:31
那么,你应该使用一个在每次迭代中递增的变量:
def should_I_buy(data, input_price, input_day):
"""Returns whether one should buy flight ticket now or wait longer to buy"""
number_of_false = 0
for day, price in data:
if day < input_day:
if price < input_price:
number_of_false+=1
return number_of_false,len(data)-number_of_false
NB
请注意,我不知道你在做什么,所以我的答案是基于快速浏览你的代码。
如果这不是预期的行为,请评论,我们可以通过您希望获得的。
发布于 2019-04-09 10:52:23
您可以使用sum
来计算for循环中的所有True,(True=1
,False=0
):
def should_I_buy(data, input_price, input_day):
"""Returns whether one should buy flight ticket now or wait longer to buy"""
return sum(day >= input_day or price >= input_price for day, price in data)
测试和输出:
data = [(14, 77.51), (13, 14.99), (12, 56.09), (11, 14.99), (10, 14.99), (9, 14.99), (8, 39.00), (7, 114.23),
(6, 37.73), (5, 56.09), (4, 14.99), (3, 22.43), (2, 22.43), (1, 31.61), (0, 168.29)]
print(should_I_buy(data, 50.00, 8)) # output 10
print(should_I_buy(data, 18.00, 3)) # output 15
希望这对你有帮助,如果你有更多的问题可以发表意见。:)
https://stackoverflow.com/questions/55591019
复制