How can we change this recursive function to "for iteration"?.....
Note: Greed algorithms should not be used. Greedy algorithms are less accurate.
Reason to change : To increase the efficiency of a function by changing to a dynamic algorithm
What I've tried:
# this code is trash
for i in range(1,m+1):
n1=m-coins[i]
for i in range(1,m+1):
n2=m-coins[i]
return min(n1,n2)
while n1==0:
i=i+1
n1=m-coins[i]
return n1
Besides this, I tried using dictionary and combination, but I forgot because I thought it wouldn't work.
How the function behaves : It is a function that takes a list of coins and a value of m and makes m==0.
n1 means moving on without using coins[0].
n2 means using coins[0] as a necessity and moving on to the next level.
If I had a list of [5,4,2,1] and a value of 10 m, I would recurs the first n1=[4,2,1],10 and the first n2=[5,4,2,1],10.
coins =[50,40,20,10,5,4,2,1]
m = 80
def coin_count(coins, m):
if m > 0:
while len(coins) > 0 and m < coins[0]:
coins = coins[1:]
#Below is the part I want to change.
if coins[0] > 1:
n1=coin_count(coins[1:],m)
n2=coin_count(coins,m-coins[0])+1
return min(n1,n2)
else: # coins[0] == 1
return m
#Above is the part I want to change
else: # m == 0
return 0