【问题标题】:Python "yield" keyword to calculatePython“yield”关键字计算
【发布时间】:2017-12-06 19:12:17
【问题描述】:

一家酒吧店有为期十天的促销活动。在此期间,啤酒的价格每天下降 10%。例如,第一天 10 美元的啤酒第二天要 9 美元,第三天要 8.1 美元。

我想写一个python函数,使用yield关键字计算每天的啤酒价格。

例如,如果我们输入 10, 我的预期输出是:

Price is discounted to : 9

Price is discounted to : 8.1 

..等

class DiscountCalc:
    def get_item_price(self):
        return input('Input a starting price (0 to quit): ')


    def discount(self, current_price, days):
        yield (current_price - (current_price*10)//100)



    def run(self):
        initial = self.get_item_price()
        for price in self.discount(initial, 10):
            print "Price is discounted to : " + str(price)

DiscountCalc().run()

【问题讨论】:

  • 那么,您的问题究竟是什么?作为一个方面,这门课似乎很……没必要。没有任何内部状态。
  • 如果我将“yield (current_price - (current_price*10)//100)”添加到我的折扣类中,我会得到输入,因为只有“Price is discounted to : 9”,它首先是 onlay天,但我也想得到其他天的结果。
  • edit 提出您使用的代码无效的问题。我不知道您所说的“如果我将“收益率 (current_price - (current_price*10)//100)”添加到我的折扣类”中是什么意思。 添加到哪里?
  • @Alice 请将您的尝试与yield 声明放在问题中,并说明它正在做什么以及您期望它做什么。
  • 我做了,如你所见,我将产量声明添加到我的折扣类中,它只给出一天的输出,我也想获得其他天的输出,可能我会使用循环但是,怎么做?

标签: python generator yield


【解决方案1】:

这是由于循环,这应该可以解决它:

def discount(self, current_price, days):
    for day in range(days):
        yield current_price
        current_price = current_price * 0.9


def run(self):
    initial = self.get_item_price()
    for price in self.discount(initial, 10):
        print(price)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-21
    • 1970-01-01
    • 1970-01-01
    • 2011-05-26
    • 2023-03-05
    • 2011-06-08
    • 1970-01-01
    相关资源
    最近更新 更多