Babai
Babai

Reputation: 23

How can I create a rectangle using numbers and asterisks symbol?

Output should be like this :

1*****
12****
123***

The code I tired has given below. But I didn't get my the desired output.

n = int(input("enter rows: "))
x = int(input("enter column: "))

def show_rectangle(row, column):
    for i in range(0,n):
        for j in range(i+1,x):
            print(j,end="")
        for k in range(1, j-i):
            print("*",end="")
        print()

show_rectangle(n,x)

Upvotes: 1

Views: 404

Answers (3)

wuerfelfreak
wuerfelfreak

Reputation: 2439

This for rows <= 9:

n = int(input("enter rows: "))
x = int(input("enter column: "))

for i in range(n):
    print(''.join(map(str,range(1,i+2)))+'*'*(x-i))

Otherwise use this:

n = int(input("enter rows: "))
x = int(input("enter column: "))

for i in range(n):
    s = ''.join(map(str, range(1, i + 2)))
    print(s+'*'*(x-len(s)))

Upvotes: 1

Federico Ba&#249;
Federico Ba&#249;

Reputation: 7656

Solution 1

rows = 6
columns = 3

def show_rectangle(row,column):
    for i in range(column):  # Column
        for j in range(i+1):
            print(j+1,end="")
        
        for k in range(j, row):
          print("*",end="")
        print()

show_rectangle(rows, columns)

# 1*****
# 12****
# 123***

Solution 2

Returning the actual result so that you can store it in a variable

rows = 6
columns = 3
  
def make_rectangle(row,column):
  result = []      
  while True: 
    temp = []
    if not column:
      break
    column -= 1
    for col in range(1, column+2):
      temp.append(str(col))      
    for r in range(row-column):
      temp.append("*")
      
    result.append(''.join(temp))

  result.reverse()
  return result
  
def show_rectancle(result):
  for i in result:
    print(''.join(str(i)))

result = make_rectangle(rows, columns)
show_rectancle(result)

Solution 3

rows = 6
columns = 3


def make_rectangle(row, column):
    result = []
    accumulator = []
    for col in range(1, column+1):
      temp = []
      accumulator.append(col)
      for r in range(1, row):
        if r in accumulator:
          print(r, end='')
          temp.append(str(r))
        else:
          temp.append('*')  
          print('*', end='')
      result.append(temp)
      print()
    result_ = []
    for i in result:
      result_.append(''.join(i))
    return result_
  

def show_rectancle(result):
    for i in result:
        print(i)


result = make_rectangle(rows, columns)
print('==='*15)
show_rectancle(result)

Upvotes: 0

Jyotirmay
Jyotirmay

Reputation: 554

r = int(input("Enter no. of rows : "))
z=r
for i in range(1,r+1):
    for j in range(1,i+1):
        print(j,end='')
    for x in range(z,0,-1):
        print('*',end='')
    z-=1
    print()

Upvotes: 1

Related Questions