Python Beginner: Number Pyramid Problem

Asked 2 years ago, Updated 2 years ago, 15 views

n = int(input())
a=list(range(0,10))

for i in range(1,n+1):
    for j in range(i):
        print(a[j]+i, end='')
    print()

It works well when you put in 2, but if you put in 3, 345 comes out instead of 456.

python

2022-09-20 18:07

3 Answers

What seems to work well with 2 is accidental. It means that it didn't necessarily work normally.

When n = 3, the code operates in the following order:

The real problem is that at some point, the output of the double for statement can be the same.
a[2] + 2 = a[1] + 3 which means there will be a problem.

If it were me, I'd just do this. If you look at the requirements of the problem, you don't have to define the list.

n = 4

last_print = 0 # What was the last number I printed?

For i in range(n): #n is 4, so we need to build a total of 4 floors
    For jin range (i+1) : # I should print only one on the first floor and two on the second floor
        last_print = last_print + 1 # Oops, but the number to be printed this time must be 1 greater than the last number to be printed
        print(last_print, end = '') # Shall we print it out?
    print() # Since we're done with this floor, should we move on to the next floor?

# It's almost done


2022-09-20 18:07

num = 20

asdf = 1

for i in range(num):
    qrweqr = ''

    for j in range(i + 1):
        qrweqr += str(j + asdf) + '.'

    print(qrweqr)

    asdf += i + 1

"""
1.
2.3.
4.5.6.
7.8.9.10.
11.12.13.14.15.
16.17.18.19.20.21.
22.23.24.25.26.27.28.
29.30.31.32.33.34.35.36.
37.38.39.40.41.42.43.44.45.
46.47.48.49.50.51.52.53.54.55.
56.57.58.59.60.61.62.63.64.65.66.
67.68.69.70.71.72.73.74.75.76.77.78.
79.80.81.82.83.84.85.86.87.88.89.90.91.
92.93.94.95.96.97.98.99.100.101.102.103.104.105.
106.107.108.109.110.111.112.113.114.115.116.117.118.119.120.
121.122.123.124.125.126.127.128.129.130.131.132.133.134.135.136.
137.138.139.140.141.142.143.144.145.146.147.148.149.150.151.152.153.
154.155.156.157.158.159.160.161.162.163.164.165.166.167.168.169.170.171.
172.173.174.175.176.177.178.179.180.181.182.183.184.185.186.187.188.189.190.
191.192.193.194.195.196.197.198.199.200.201.202.203.204.205.206.207.208.209.210.
"""


2022-09-20 18:07

 


2022-09-20 18:07

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.