0

I need to build a generator - all_sums(num, bound).

The generator will return a string which describes a connection between small or equal numbers to bound, whose sum is num.

Each string will be returned only once.

For example -

res = all_sums(4, 3)
list(res)
 output - ['1 + 1 + 1 + 1' ,'1 + 1 + 2' ,'2 + 2' ,'1 + 3']

This is what I did until now -

def all_sums(num,bound):
    lst = []
    new = []
    for i in range(1,num):
        lst.append(i)
    return all_sums_helper(num,bound,lst,new)

def all_sums_helper(num,bound,lst,new):
    if num == 1:
        return new.append('1')
    if lst[0] + bound == num:
        yield str(lst[0])+ '+'+ str(bound)
    yield from (all_sums_helper(num,bound,lst[1:],new) 

I dont know what I need to do next.

I would be happy for any help.

  • Why does it specifically need to be a generator? – John Gordon Jun 23 '22 at 19:31
  • 1
    Your problem is actually related to integer partitioning - you may find this question and its answers useful in modifying your generator: https://stackoverflow.com/questions/10035752/elegant-python-code-for-integer-partitioning – jrd1 Jun 23 '22 at 19:31
  • I am learning for a test and this is the question , it has to be generator. –  Jun 23 '22 at 19:36
  • `new` is serving no purpose here. Not sure what you expected it to do. And you probably want `range(1,num+1)`. You can replace that first loop by `lst = list(range(1,num+1))`. – Tim Roberts Jun 23 '22 at 19:41

0 Answers0