Search code examples
pythonsum

How to make pyramid with sum of the string with python


for example of '31415926535897', should be applying the rule of 1 2 2 3 3 3 which can be shown like (3) (1 + 4) (1 + 5) (9 + 2 + 6) (5 + 3 + 5) (8 + 9 + 7) which results,

3
5 6
17 13 24

in which i made my code for pyramid is,

for i in range(rows):
   for j in range(i + 1):
       print(i, end=" ")
   print("\r")

but i can't get it how to apply the sum of the 1 2 2 3 3 3 structure. Should i use sum(x for x in range()) or what should i do for it?


Solution

  • I think that this solution may work well as far as the string provided accomplishes with the requirements to apply the pyramid sum completely.

    string = "31415926535234"
    
    structure = 1
    pos = 0
    result = ""
    
    while not pos==len(string):
        for i in range(structure):
            ans = 0
            for j in range(structure):
                ans += int(string[pos+j])
            result += str(ans)+" "
            pos = pos+structure
        structure += 1
        result += "\n"
    
    print(result)
    

    If you input 31415926535234 it works well, but if you delete the last digit, it will not work because you wouldn't be able to complete the sum of 3 numbers.