Colin Warn
Colin Warn

Reputation: 411

Print a half pyramid of numbers in Python

Suppose, you are given a positive integer. Now, print a numerical triangle of height like the below one. More than 2 lines will result in a 0 score.

1

22

333

4444

55555

My code:

for i in range(1,int(input())): #More than 2 lines will result in 0 score. Do not leave a blank line also
    for j in range(i):
        print((j+1), end="")
    print("\n")

I'm able to do it in two print statements, but not in one. How would I condense it to one?

Upvotes: 0

Views: 1359

Answers (4)

Saran Kumar RS
Saran Kumar RS

Reputation: 3

for i in range(1,int(input())):
    print((10**i)//9*i)

By using this code you can print the pattern by without using string function and the code comes within two lines.

Upvotes: 0

Ajax1234
Ajax1234

Reputation: 71471

You can use a list comprehension with a single print call:

print('\n'.join(str(i)*i for i in range(1, 6)))

Output:

1
22
333
4444
55555

Upvotes: 4

Dani Mesejo
Dani Mesejo

Reputation: 61930

You could do something like this:

for i in range(1, int(input()) + 1):
    print(''.join(str(i) for j in range(i)))

Output

1
22
333
4444
55555

Note: The above output was for input = 5

Upvotes: 0

Sven Harris
Sven Harris

Reputation: 2939

There's lots of ways you could do this, for example, using a list comprehension:

for i in range(1,int(input())):
    print([i for j in range(i)])

And then maybe you want to change the output into strings instead of lists, in which case you can do:

for i in range(1,int(input())):
    print("".join([str(i) for j in range(i)]))

Upvotes: 0

Related Questions