Rui Yu Rui Yu - 15 days ago 5
Python Question

How do I do this "If n is 3, return `1+..1+2+..1+2+3+..`"

Define a function named

nested_increasing_additions(n)
which receives one positive integer
(n)
and returns a string as illustrated in the following examples:

If
n
is
3
, the function should return the string:
1+..1+2+..1+2+3+..


If
n
is
5
, the function should return the string:
1+..1+2+..1+2+3+..1+2+3+4+..1+2+3+4+5+


What I think is, I can make
n
to a list
[1,2,3]
and use while loop or for loop to repeat
n
times. For the first loop it returns
1+..
, for the second loop it returns
1+2..
somehow (which i don't know) it stops at
2
which is the same as the repeating time.

I don't know if I'm thinking it right. Need some help and explanations! Thank you!

Answer

You can build the complete string step by step, and remember at each step what you have added last:

def nested_increasing_additions(n):
    complete_string = ""
    add_string = ""
    for i in range(1,n+1):
        add_string += str(i) + "+"
        complete_string += add_string + ".."
    return complete_string

print(nested_increasing_additions(1))
print(nested_increasing_additions(3))
print(nested_increasing_additions(5))

The output with python3 is:

1+..
1+..1+2+..1+2+3+..
1+..1+2+..1+2+3+..1+2+3+4+..1+2+3+4+5+..
Comments