简体   繁体   中英

Recursive counting on buy back function

I'm trying to create a function that is essentially a buy back program with bottles, the rules are as follows

money -> the amount of money the customer has

bottlesOwned -> the number of bottles the customer has to exchange

price -> the price of a bottle of soda pop

exchangeRate -> the exchange rate, expressed as a tuple. the first element is the minimum size of the group of bottles that can be exchanged. The second argument is the refund received for one group of bottles.

A customer may refund as many groups of bottles as they like on a single visit to the store, but the total number of bottles refunded must be a multiple of the first element of exchangeRate.

The function must output the total number of bottles which the customer is able to purchase over all trips, until the customer runs out of money.

def lightningBottle(money, bottlesOwned, price, exchangeRate):

    if bottlesOwned >= exchangeRate[0]:
        bottlesOwned -= exchangeRate[0]
        money += exchangeRate[1]

    if money >= price:
        bottlesOwned += 1
        bottlesbought += 1
        money -= price
        return lightningBottle(money, bottlesOwned, price, exchangeRate)

    else:
        print ("we bought",bottlesbought,"bottles")
        return bottlesbought

this is as far as I've gotten but I cannot figure out how to get the bottlesbought counter to tick up without using a global variable (I can't use a global because it does not reset on concurrent tests and provides the wrong answer)

You're close. You just need bottlesbought to be an argument of your function:

def lightningBottle(money, bottlesOwned, price, exchangeRate, bottlesbought=0):

    if bottlesOwned >= exchangeRate[0]:
        bottlesOwned -= exchangeRate[0]
        money += exchangeRate[1]

    if money >= price:
        bottlesOwned += 1
        bottlesbought += 1
        money -= price
        return lightningBottle(money, bottlesOwned, price, exchangeRate, bottlesbought)

    else:
        print ("we bought",bottlesbought,"bottles")
        return bottlesbought

You can give it a default value so you don't need to specify that it's equal to zero at the start (which it always is).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM