Python Forum
Appending to list not working and causing a infinite loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Appending to list not working and causing a infinite loop
#1
New to Python and Algorithims. Trying to solve this one before looking for solutions. Im having the problem towards the bottom where the coin is suppose to be appended to the list, if this doesn't happen then the condition never becomes false.

def rec_coins(target,coins):
    
    coins = sorted(coins)
    mincoinsneeded = []
    sum_of_coins = sum(mincoinsneeded)
    current_accum = target - sum_of_coins

    while sum_of_coins != target:

        for coin in reversed(coins):
            
            if coin == target:
                return coin

            elif current_accum % coin != 0:
                coins.pop()

            else:

                while current_accum % coin > 1:
                    mincoinsneeded.append(coin)

    print (mincoinsneeded)

rec_coins(20,[1,5,10])
Reply
#2
What this function should do/return?

EDIT: if one wants to find coins needed for certain amount one can use built-in function divmod() combined with dictionary. (for quite obvious reasons one should start from largest):

def coins(amount, coins=(50, 20, 10, 5, 2, 1)):
    quantities = dict() 
    for coin in coins: 
        quantities[coin], amount = divmod(amount, coin) 
    return {k:v for k, v in quantities.items() if v !=0} # or 'return quantities', zero quantity coins are kept


One can adjust available coins for it's own currency and usage is simple:

>>> coins(121)
{50: 2, 20: 1, 1: 1}
EDIT: if total amount of coins is needed then function should return sum(quantities.values())
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#3
@perfringo, its suppose to return the minimum amount of coins needed to reach the target amount.

Thank you perfringo, I was trying to solve it with my solution. Its seems that the numbers append to the list but the

current_accum = target - sum_of_coins
is not working, so it gets stuck in the while loop

Apologies, its actually this part that doesnt seem to be working:

sum_of_coins = sum(mincoinsneeded)
Reply
#4
This is because sum will always be 0:

>>> min_coins_needed = []
>>> sum_of_coins = sum(min_coins_needed)     # sum returns immutable numeric
>>> sum_of_coins
0
>>> min_coins_needed.append(5)
>>> min_coins_needed
[5]
>>> sum_of_coins
0
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#5
Starting to recognize that now as I editing the code, how would I go about fixing this?
Reply
#6
One way could be:

while sum(min_coins_needed) != target:
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#7
Figured it out. Thank you!

def rec_coins(target,coins):
    
    
    mincoinsneeded = []

    while sum(mincoinsneeded) != target:

        for coin in reversed(coins):
            
            if coin == target:
                return coin

            else:

                while (target - sum(mincoinsneeded)) / coin >= 1:
                    mincoinsneeded.append(coin)

    print (mincoinsneeded)

rec_coins(37,[1,5,10])
Reply
#8
I observe that you reverse coins list but not sort. This works well if coins list is initially sorted in ascending order but in all other cases there will be unexpected results:

>>> rec_coins(37, [1, 5, 10])                                                              
[10, 10, 10, 5, 1, 1]
>>> rec_coins(37, [5,1, 10])                                                               
[10, 10, 10, 1, 1, 1, 1, 1, 1, 1]
If there is possibility that list is not sorted ascending then sorted(coins, reverse=True) could be used

I personally not big fan of printing and returning None from function. No flow control and and probably somebody tries to print or give it a name. This code especially unpredictable as in some cases it returns integer and in some cases prints list and returns None.

>>> print(rec_coins(37, [1, 5, 10]))                                                       
[10, 10, 10, 5, 1, 1]
None
>>> coins = rec_coins(37, [1, 2, 10])                                                      
[10, 10, 10, 2, 2, 2, 1]
>>> coins        # Nothing happens as coins is None                                                                                  
>>> type(coins)                                                                            
NoneType
>>> rec_coins(10, [5,1, 10])                                                               
10
>>> print(rec_coins(10, [5,1,10]))                                                         
10
>>> coins = rec_coins(10, [5,1,10])                                                        
>>> coins                                                                                  
10
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#9
Thank you for the feedback! I added the sort before I read this, but thank you for that as well. Is there any improvements to this that can be done, or is a recursive approach better?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  while loop not working-I am using sublime text editor mma_python 4 1,147 Feb-05-2023, 06:26 PM
Last Post: deanhystad
Shocked Why this code does not go into an infinite loop? 2367409125 2 884 Dec-02-2022, 08:22 PM
Last Post: deanhystad
  Need help with infinite loop & making hotkeys/shortcuts Graxum 1 1,175 Aug-22-2022, 02:57 AM
Last Post: deanhystad
  WHILE Loop - constant variables NOT working with user input boundaries C0D3R 4 1,494 Apr-05-2022, 06:18 AM
Last Post: C0D3R
  string.format() suddenly causing errors with google drive API zwitrader 0 1,771 Jun-28-2021, 11:38 PM
Last Post: zwitrader
  Time.sleep: stop appending item to the list if time is early quest 0 1,881 Apr-13-2021, 11:44 AM
Last Post: quest
  Reading and appending list MrSwiss 1 1,733 Mar-01-2021, 09:01 AM
Last Post: Serafim
  Infinite loop problem Zirconyl 5 2,995 Nov-16-2020, 09:06 AM
Last Post: DeaD_EyE
  using 'while loop' output going into infinite loop... amitkb 2 1,971 Oct-05-2020, 09:18 PM
Last Post: micseydel
  Appending list Trouble Big Time Milfredo 7 3,127 Oct-01-2020, 02:59 AM
Last Post: Milfredo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020