Nested Loop Python

后端 未结 13 2252
一个人的身影
一个人的身影 2020-12-09 23:40
count = 1
for i in range(10):
    for j in range(0, i):
        print(count, end=\'\')
        count = count +1
    print()
input()

I am writing a

13条回答
  •  离开以前
    2020-12-10 00:25

    Others have suggested some interesting solutions but this can also be done mathematically using a simple observation. Notice that:

    1 - 1*1

    22 - 2*11

    333 - 3*111

    4444 - 4*1111

    and so on ....

    We can have a general formula for producing 1,11,111,1111,... at every iteration. Observe that:

    1 = 9/9 = (10 - 1)/9 = (10^1 - 1)/9

    11 = 99/9 = (100 - 1)/9 = (10^2 - 1)/9

    111 = 999/9 = (1000 - 1)/9 = (10^3 - 1)/9

    ......

    that is we have (10^i - 1)/9 for the ith iteration.

    Now it is simple enough to implement. We will multiply i with the above formula in each iteration. Hence the overall formula is:

    i*(10^i - 1)/9 (for every ith iteration). Here's the python code:

    for i in xrange(1,10):
        print i*(10**i-1)/9
    

    Hope this helps.

提交回复
热议问题