Search code examples
pythonarrayslistsublistcoin-change

Sublist into String Python


I have a little problem , I have this code and I need to convert the final print to a string, to be able to printthe final results in different lines and change the separator "," to a "+". If someone could help me to fix this I will be grateful :D.

Thks in advance ^^.

Ex.:

Input: 7

Output:

5 + 2

5 + 1 + 1

2 + 2 + 2 + 1

2 + 2 + 1 + 1 + 1

2 + 1 + 1 + 1 + 1 + 1

1 + 1 + 1 + 1 + 1 + 1 + 1

Code:

def change(coins, amount)
      res = []
      def getchange(end, remain, cur_result):
        if end < 0: return
        if remain == 0:
            res.append(cur_result)
            return
        if remain >= coins[end]:
            getchange(end, remain - coins[end], cur_result + [coins[end]])
        getchange(end - 1, remain, cur_result)
    
     getchange(len(coins) - 1, amount, [])
     return res

q = int(input("Write your change: "))
st = change([1, 2, 5, 10], q)
print(st)

Solution

  • change your last line code from print(st) to

    for s in st:
        print('+'.join((map(str,s))))