1

I'm wondering how to create a pyramid using only element (1,2,3) regardless of how many rows.

For eg. Rows = 7 ,

1
22
333
1111
22222
333333
1111111

I've have tried creating a normal pyramid with numbers according to rows.

eg.

1
22
333
4444
55555
666666

Code that I tried to make a Normal Pyramid

    n = int(input("Enter the number of rows:"))

    for rows in range (1, n+1):  
        for times in range (rows): 
            print(rows, end=" ")

        print("\n")
Sammy
  • 13
  • 3

3 Answers3

1

You need to adjust your ranges and use the modulo operator % - it gives you the remainer of any number diveded by some other number.Modulo 3 returns 0,1 or 2. Add 1 to get your desired range of values:

1 % 3 = 1  
2 % 3 = 2 # 2 "remain" as 2 // 3 = 0 - so remainder is:  2 - (2//3)*3 = 2 - 0 = 2 
3 % 3 = 0 # no remainder, as 3 // 3 = 1 - so remainder is:  3 - (3//3)*3 = 3 - 1*3 = 0

Full code:

n = int(input("Enter the number of rows: "))
print()
for rows in range (0, n):                 # start at 0
    for times in range (rows+1):          # start at 0
        print( rows % 3 + 1, end=" ")   # print 0 % 3 +1 , 1 % 3 +1, ...,  etc.

    print("")

Output:

Enter the number of rows: 6
1 
2 2 
3 3 3 
1 1 1 1 
2 2 2 2 2 
3 3 3 3 3 3 

See:

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

Using cycle from itertools, i.e. a generator.

from itertools import cycle

n = int(input("Enter the number of rows:"))

a = cycle((1,2,3))
for x,y in zip(range(1,n),a):
   print(str(x)*y)

(update) Rewritten as two-liner

from itertools import cycle
n = int(input("Enter the number of rows:"))
print(*[str(y)*x for x,y in zip(range(1,n),cycle((1,2,3)))],sep="\n")
fluxens
  • 565
  • 3
  • 15
0

A one-liner (just for the record):

>>> n = 7
>>> s = "\n".join(["".join([str(1+i%3)]*(1+i)) for i in range(n)])
>>> s
'1\n22\n333\n1111\n22222\n333333\n1111111'
>>> print(s)
1
22
333
1111
22222
333333
1111111

Nothing special: you have to use the modulo operator to cycle the values.

"".join([str(1+i%3)]*(1+i)) builds the (i+1)-th line: i+1 times 1+i%3 (thats is 1 if i=0, 2 if i=1, 3 if i=2, 1 if i=4, ...).

Repeat for i=0..n-1 and join with a end of line char.

jferard
  • 7,835
  • 2
  • 22
  • 35