【问题标题】:Is there a way to count how many true/false outputs in a Boolean function with a for loop?有没有办法用 for 循环计算布尔函数中有多少真/假输出?
【发布时间】:2019-08-30 15:23:25
【问题描述】:

我正在使用 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 时,我还想找到一种方法来计算循环中有多少 True 和 False。

【问题讨论】:

  • 请用一些示例数据和示例输出更新您的问题。
  • 我的意思是您的新要求的示例输出。
  • 每次调用该函数时,它都会返回一个布尔值,因此您需要将这些结果保存在某个地方,也许是您以后可以从中检索的列表?

标签: python function for-loop if-statement boolean


【解决方案1】:

嗯,你应该使用一个在每次迭代时递增的变量:

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

注意

请注意,我不知道你在做什么,所以我的回答是基于快速浏览你的代码。

如果这不符合预期,请发表评论,我们可以完成您希望获得的内容。

【讨论】:

    【解决方案2】:

    你可以使用sum来计算for循环中的所有True,(True=1False=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
    

    希望对您有所帮助,如果您有其他问题,请发表评论。 :)

    【讨论】:

      猜你喜欢
      • 2015-04-01
      • 2013-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多