0

I have the following code that prints out the least amount of bills needed to form a given amount of dollars:

dollars = 568

billSelection = [100,50,20,10,5,1]
def thingy(bill):
    global dollars
    numOfBills = dollars // bill
    dollars -= numOfBills * bill
    return numOfBills

result = list(map(thingy,billSelection))

print(result)
print(sum(result))

I would like to pass 'dollars' into the function in order to avoid the ugly global variable. It works if I set dollars as a list with 1 element and write dollars[0] everywhere else but this is also not optimal. Any suggestions for how to do this cleanly? Thanks!

2 Answers 2

3

While you can set up a map call to pass in more than one variable to each call of the function, it won't really help you here. That's because you want the dollars value to be both read and modified by the function. The only way you could make that work is to have it both be an argument, and a return value, and most of the ways to give it to map won't let you use the return value as the new dollars value for the next call.

If you don't mind dropping map for an explicit loop, you could make it work:

def thingy(dollars, bill):
    numOfBills = dollars // bill
    dollars -= numOfBills * bill
    return dollars, numOfBills  # return a two-tuple

dollars = 568
billSelection = [100,50,20,10,5,1]
result = []

for bill in billSelection:                        # use an explicit loop instead of map
    dollars, bill_count = thingy(dollars, bill)   # so we can update dollars
    result.append(bill_count)
Sign up to request clarification or add additional context in comments.

1 Comment

This is awesome. Thanks :D
0

map can take multiple arguments as long as they're all iterable. One quick and dirty way to pass a constant value is to put it inside a list of the same size as the other iterable, like this:

dollars = 568
billSelection = [100,50,20,10,5,1]

def thingy(bill, dollars):
    # function logic goes here

result = map(thingy, billSelection, [dollars]*len(billSelection))

2 Comments

While this answers the question posed in the title, it won't actually calculate the desired result. The thingy function is modifying dollars currently, so if you want map to work with multiple arguments, you need some way to get the latest value into the list you're using for the second argument.
Correct, I didn't see that OP was changing the value of dollars inside the function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.