2017-12-06 4 views
-2

バーショップは10日間のプロモーションを行っています。この期間中、ビールの価格は毎日10%下がります。たとえば、1日目に10ドルのビールを購入すると、2日目に9ドル、3日目に8.1ドルの費用がかかります。計算するPython "yield"キーワード

私は毎日ビール価格を計算するためにyieldキーワードを使用するPython関数を記述したいと思います。例えば

我々は、入力10を与えた場合、 私の予想される出力は次のとおりです。

Price is discounted to : 9 

Price is discounted to : 8.1 

..etc

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() 
+2

あなたの質問は何ですか?側面として、このクラスはかなり...不要です。内部状態はありません。 –

+0

私の割引クラスに "yield(current_price - (current_price * 10)// 100")を追加すると、最初のonlayである "Price is discount:9"他の日の結果も。 – Alice

+0

使用しているコードで質問がうまくいかない場合は、[編集](https://stackoverflow.com/posts/47681818/edit)してください。私は、「私の割引クラスにyield(current_price - (current_price * 10)// 100)」を追加すると、*正確に*あなたが意味することを知ることができません。 *どこに*を追加しますか? –

答えて

2

それが原因のサイクルに、これはそれを修正する必要があります:

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)