1

This is my code which i wrote in python

n = 5
row = 2 * n - 2
for i in range(n,-1,-1):
    for j in range(row):
        print(end="")

    row -=2

    for k in range(i+1):
        print('*',end=" ")

    print()

The output what is get is this

* * * * *  
* * * * 
* * * 
* * 
*

i want to print this start from left to right order for example

The expected output is :-

* * * * *
  * * * *
    * * *
      * *
        *

if it's any possible way to print the elements from left to right because in most of my program i need that logic i'm searching for it please help me and even i used reversed function for loop it will reverse the loop but i'm not getting what i expect

4 Answers 4

4
n = 5
print(*[' '.join(' '*i + '*'*(n-i)) for i in range(n)], sep='\n')

Output:

* * * * *
  * * * *
    * * *
      * *
        *

Explanation:

for i in range(n):
    chars = ' '*i + '*'*(n-i)  #  creating list of (i) spaces followed
                                   #  by (n-i) stars to finish a line of n elements
    print(' '.join(chars))  # join prepared values with spaces
Sign up to request clarification or add additional context in comments.

4 Comments

An explanation would have been fine ;-)
thanks bro You use list comprehension can you give me as i wrote normal code
I feel like that code is self explanatory but I'll give it a try.
The code is unnecessarily complicated by writing it as a single call to print.
0

Here is a simple solution not using list comprehension:

n = 5
for i in range(n+1):
    for j in range(i):
        print("  ", end="")
    for j in range(i+1, n+1):
        print("* ", end="")
    print()

Output:

* * * * * 
  * * * * 
    * * * 
      * * 
        *

Comments

0

My solution - I'm new to python as well:

n = 5
c = 0
for i in range(n, 0, -1):
    print(" " * c + "*" * i)
    c += 1

or

n = 5
c = 0
while n >= 0:
    print(" " * c + "*" * n)
    n -= 1
    c += 1

Comments

-1

The problem is that print itself cannot print right-justified text. But you can print a right-justified string instead of using multiple calls to print.

Here's your original code, using join instead of an inner loop:

n = 5
row = 2 * n - 2
for i in range(n,-1,-1):
    for j in range(row):
        print(end="")

    row -=2

    row_str = " ".join(["*"] * i)
    print(row_str)

And here's the modified code to make the output right-justified:

n = 5
row = 2 * n - 2
whole = row + 1
for i in range(n,-1,-1):
    for j in range(row):
        print(end="")

    row -=2

    row_str = " ".join(["*"] * i).rjust(whole)
    print(row_str)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.