How to make pyramid with sum of the string with python

Question:

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?

Asked By: ilya jung

||

Answers:

You could use itertools.groupby, it transforms [1, 2, 2, 3, 3, 3] into {1:[1], 2:[2,2], 3:[3,3,3]}, then use to slice the input for sum

from itertools import groupby

s = '31415926535897'
rules = [1, 2, 2, 3, 3, 3]

for value, count in groupby(rules):
    for j in range(len(list(count))):
        group = sum(map(int, s[:value]))
        print(group, end=" ")
        s = s[value:]
    print()
Answered By: azro

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.

Answered By: FelipeCruzV10

Since row tells you the number of digits to sum and the number of times you’d do that (e.g. in row 2 we take the sum of 2 digits and we do that twice) you could do the ff:

  1. Identify the appropriate substring; increment pos by row. Also the size of substring can be also determined by the row number.

    stri[pos: pos+row]

  2. Take the sum by first converting each char to int

    [int(ch) for ch in stri[pos: pos+row]]

So, we get this

stri = '31415926535897'
pos = 0
row = 1
while pos < len(stri):
  for i in range(row):
    print(sum([int(ch) for ch in stri[pos: pos+row]]), end=' ')
    pos += row
  row += 1
  print()
Answered By: rendoraaprille
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.