蟒蛇 |添加模式 1 22 333 4444 55555 ....?

Python | addition of pattern 1 22 333 4444 55555​ ....?

提问人:pkk 提问时间:4/12/2022 更新时间:4/12/2022 访问量:3192

问:

如何加法 1 22 333 4444 55555 ....?

i) 情况 1:n = 1,v = 1

ii) 情况 2:n= 2,v = 23(注:23 派生为 1 + 22)

def create_sequence():

   n = int(input('Enter the number till which you want the sequence:'))

   for i in range(1,n+1):

       print(str(i) * i)

   

create_sequence()
python-3.x 序列 添加

评论

2赞 Barmar 4/12/2022
将字符串转换为整数并将其添加到结果变量中。

答:

4赞 jthulhu 4/12/2022 #1

生成 形式的元素序列,将其转换为整数,然后生成该序列。str(i)*isum

def create_sequence(n):
    return sum(int(str(i)*i) for i in range(1, n+1))

create_sequence(int(input('Enter the number till which you want the sequence: ')))
1赞 acornTime 4/12/2022 #2

利用循环,他们是你的朋友

def create_sequence():

   n = int(input('Enter the number till which you want the sequence:'))
   sum = 0
   for x in range(1, n+1):
       string = ""
       for i in range(1, x+1):
           string += str(x)
       sum += int(string)
   return sum
print(create_sequence())