如何用 python 的字符串总和制作金字塔
How to make pyramid with sum of the string with python
例如“31415926535897
”,应该应用 1 2 2 3 3 3
的规则,可以显示为 (3) (1 + 4) (1 + 5) (9 + 2 + 6) (5 + 3 + 5) (8 + 9 + 7)
结果,
3
5 6
17 13 24
我制作金字塔代码的地方是,
for i in range(rows):
for j in range(i + 1):
print(i, end=" ")
print("\r")
但我不知道如何应用 1 2 2 3 3 3
结构的总和。我应该使用 sum(x for x in range())
还是应该为此做什么?
你可以使用 itertools.groupby
,它将 [1, 2, 2, 3, 3, 3]
转换为 {1:[1], 2:[2,2], 3:[3,3,3]}
,然后使用切片输入求和
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()
我认为只要提供的 string
满足完全应用金字塔总和的要求,此解决方案可能会很有效。
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)
如果你输入31415926535234
就可以了,但是如果你删除了最后一个数字,它就不行了,因为你无法完成3个数字的总和。
例如“31415926535897
”,应该应用 1 2 2 3 3 3
的规则,可以显示为 (3) (1 + 4) (1 + 5) (9 + 2 + 6) (5 + 3 + 5) (8 + 9 + 7)
结果,
3
5 6
17 13 24
我制作金字塔代码的地方是,
for i in range(rows):
for j in range(i + 1):
print(i, end=" ")
print("\r")
但我不知道如何应用 1 2 2 3 3 3
结构的总和。我应该使用 sum(x for x in range())
还是应该为此做什么?
你可以使用 itertools.groupby
,它将 [1, 2, 2, 3, 3, 3]
转换为 {1:[1], 2:[2,2], 3:[3,3,3]}
,然后使用切片输入求和
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()
我认为只要提供的 string
满足完全应用金字塔总和的要求,此解决方案可能会很有效。
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)
如果你输入31415926535234
就可以了,但是如果你删除了最后一个数字,它就不行了,因为你无法完成3个数字的总和。