Recursive generator for change money - python

2024/10/7 18:28:03

First, thanks for any help.

I have this recursive code for counting ways of change from a list of coins and a given amount.

I need to write a recursive generator code that presents the ways in every iteration. Example at the end:

This is the code:

def countChange(amount, coins):if (amount == 0):return 1elif (amount < 0 or coins == []):return 0else:return (countChange(amount, coins[:-1]) + countChange(amount - coins[-1], coins))

Now, I need to present the ways with a recursive generator. I have a part of the code that I need to write:

def change_gen(amount, coins):if amount == 0:yield ?????elif not (amount < 0 or coins == []):g = change_gen(amount, coins[:-1])????? 

This should be the output for example:

 for e in change_gen(5,[1,2,3]):print(e)[1, 1, 1, 1, 1][1, 1, 1, 2][1, 2, 2][1, 1, 3][2, 3]
Answer

Btw this reminds me of Problem 31.

If you are using Python 3.3+ we can write change_gen with yield from:

def change_gen(amount, coins):if amount == 0:yield 1elif amount < 0 or not coins:yield 0else:yield from change_gen(amount, coins[:-1])yield from change_gen(amount - coins[-1], coins)

or without yield from

def change_gen(amount, coins):if amount == 0:yield 1elif amount < 0 or not coins:yield 0else:for element in change_gen(amount, coins[:-1]):yield elementfor element in change_gen(amount - coins[-1], coins):yield element

Tests

import randomfor _ in range(10):amount = random.randint(0, 900)coins = list({random.randint(1, 100)for _ in range(random.randint(1, 10))})assert countChange(amount, coins) == sum(change_gen(amount, coins))

worked fine, so it seems to give similar output

Note

You should remember that for large values of amount and small coins we may reach recursion limit (max depth is near 1000 on my machines).


EDIT

if you want to get which coins were used we can add extra parameter for them

def change_gen(amount, left_coins, used_coins):if amount == 0:yield used_coinselif amount < 0 or not left_coins:yieldelse:yield from change_gen(amount, left_coins[:-1],used_coins=used_coins[:])yield from change_gen(amount - left_coins[-1],left_coins,used_coins[:] + [left_coins[-1]])

possible problem here is that in situations when amount is negative or no coins left None object will be yielded, but it's ok, we can filter them from results using filter:

for e in filter(None, change_gen(5, [1, 2, 3], used_coins=[])):print(e)

gives us

[1, 1, 1, 1, 1]
[2, 1, 1, 1]
[2, 2, 1]
[3, 1, 1]
[3, 2]
https://en.xdnf.cn/q/118790.html

Related Q&A

Like button not recording the data [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar q…

Python, Pygame, Image manipulation: Restretch a loaded png, to be the texture for an isometric Tile

Im a 17 year old programmer, trying to program an isometric game in python, with pygame. After finishing a tile engine, working with not good looking, gimp-drawn PNGs, I wondered, if it would be possib…

TypeError: list object is not callable [duplicate]

This question already has answers here:TypeError: list object is not callable while trying to access a list(9 answers)Closed 10 years ago.I cant find the problem im facing... this is exactly what the …

Tokenise text and create more rows for each row in dataframe

I want to do this with python and pandas.Lets suppose that I have the following:file_id text 1 I am the first document. I am a nice document. 2 I am the second document. I am an even …

Is the example of the descriptor protocol in the Python 3.6 documentation incorrect?

I am new to Python and looking through its documentation I encountered the following example of the descriptor protocol that in my opinion is incorrect. .It looks like class IntField:def __get__(self, …

How to clean a string to get value_counts for words of interest by date?

I have the following data generated from a groupby(Datetime) and value_counts()Datetime 0 01/01/2020 Paul 803 2 01/02/2020 Paul 210982360967 1 …

Folium - Map doesnt appear

I try to get map through Folium but only thing I can see is marker on blank page. Id like to know where is problem lies, in explorer or coding. map.py import foliummap = folium.Map(location = [46.20, 6…

python tkinter exe built with cx_Freeze for windows wont show GUI

PROBLEM SOLVED. the issue was with jaraco module, that i used for clipboard manipulation, i used pyperclip instead.I made a python app with tkinter that works fine, but I wanted to make an exe from it …

lxml tree connection and properties

I have a .dtsx file so, I have multiple components with connections, so I need to extract component that have especific connection, but I can not handle that, example: <components><component r…

Python recursive function call with if statement

I have a question regarding function-calls using if-statements and recursion. I am a bit confused because python seems to jump into the if statements block even if my function returns "False"…