简体   繁体   中英

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)

change your last line code from print(st) to

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

If st is a list of integers, you can change it to

print(" + ".join(str(s) for s in st))

Generators and comprehensions are generally preferred to the map operation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM