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

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

如何做1 22 333 4444 55555 ....?

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

ii) case 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()

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

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: ')))

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

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())