Program to create one triangle stair by using stars in Python


Suppose we have a number n, we have to find a string of stairs with n steps. Here each line in the string is separated by a newline separator.

So, if the input is like n = 5, then the output will be

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

To solve this, we will follow these steps −

  • s := blank string
  • for i in range 0 to n-1, do
    • s := s concatenate (n-i-1) number of blank space concatenate (i+1) number of stars
    • if i < n-1, then
      • s := add one new line after s
  • return s

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, n):
      s ="" for i in range(n):
      s+= " "*(n-i-1)+"*"*(i+1)
      if(i<n-1):
         s+="\n"
      return s
ob = Solution()
print(ob.solve(5))

Input

5

Output

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

Updated on: 05-Oct-2020

457 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements