Python Forum
Sublist/ Subarray into string Python - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Sublist/ Subarray into string Python (/thread-33414.html)



Sublist/ Subarray into string Python - SantiagoPB - Apr-23-2021

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.

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
Thks in advance ^^.

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)



RE: Sublist/ Subarray into string Python - perfringo - Apr-23-2021

Something like this?:

>>> list_ = [5, 1, 1]
>>> print(' + '.join([str(i) for i in list_]))
5 + 1 + 1



RE: Sublist/ Subarray into string Python - SantiagoPB - Apr-23-2021

Wow it function perfectly, thank you a lot!

(Apr-23-2021, 06:44 PM)perfringo Wrote: Something like this?:

>>> list_ = [5, 1, 1]
>>> print(' + '.join([str(i) for i in list_]))
5 + 1 + 1