Python task - Grid of Asterisks - python

Write a program to prompt the user to enter 2 numbers: one for number of columns and one for number of rows and outputs a grid of asterisks with the specified number of rows and columns
Hint: You will need to use one loop nested inside another.
For example, given width = 3 and height = 4, the program should output the following grid:
* * *
* * *
* * *
* * *
This is what I have so far:
width = int(input("Please enter a width for your grid:"))
rows = int(input("Please enter the amount of rows in your grid:"))
for width in range (5,0,-1):
print(width * ' ' + (5 - width) * '*')

Just a snippet:
w = 5
h = 4
for i in range(h):
print ' *' * w + ' '
output:
* * * * *
* * * * *
* * * * *
* * * * *

Since you're being asked to use nested loops, you'll want to print asterisks separated by spaces in the inner loop, and move to the next line at the end of that loop:
for x in range(rows):
for y in range(width):
print('*',end = ' ')
print()

Related

Print an empty square using an argument in Python

I want to draw the outer lines of a square. I am able to create a filled in square, using the shown code, however I am not sure how to make it empty on the inside.
This is what I have:
def square(size):
for x in range(0, size):
print("* " * size)
square(5)
What should I change?
If numpy is an option, here is an approach with it:
import numpy as np
def square(size):
square = np.ones((size, size), dtype='object')
square[1:-1, 1:-1] = ' '
square[square==1] = '*'
print('\n'.join([' '.join([str(elem) for elem in row]) for row in square]))
square(15)
Output:
* * * * * * * * * * * * * * *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* * * * * * * * * * * * * * *
Without numpy, you could use str.ljust to achieve your goal
def square(size):
for i in range(0, size):
if i not in [0, size-1]:
print('*'.ljust(size*2-2) + '*')
else:
print('* ' * size)
Your approach of printing the rows one by one is intuitive and correct, but to leave the inner of the square empty you need to treat rows differently, depending on where they occur.
To be precise, you only need to print "*" size times at the first and last row, and rows in the middle you need to keep in mind that they only have "*" at the edges.
Your code becomes:
def square(size):
# first row (all need to be filled)
print("* " * size)
# inner rows, we only print "*" at the start and at the end, the middle is empty
for x in range(0, size-2):
print("* " + " "*(size-2) + "*")
# last row (all need to be filled)
print("* " * size)
square(5)
I would recommend only printing once and add separators (e.g. the whitespace between "*") programmatically.
def square(size):
sep = " "
letter = "*"
# keep track of what we want to print
rows = []
# first row
rows.append([letter] * size)
# middle rows
for x in range(0, size-2):
rows.append([letter] + [" "] * (size-2) + [letter])
# last row
rows.append([letter] * size)
# join() lists with symbol and line separator
print("\n".join([sep.join(row) for row in rows]))
square(5)

Pattern printing with odd count of stars

How to print this pattern? I have done regular patterns but I am unable to get odd stars.
You could use a simple list comprehension:
n = 5
print("\n".join((a := [("* "*i).center(n*2 + 1) for i in range(1, n + 1) if i&1]) + a[::-1][1:]))
*
* * *
* * * * *
* * *
*
You can change n to anything you want

to print a triangle of hash '#' and stars '*' in python

I m trying to print the following triangle in python, but not able to
*#####
**####
***###
****##
*****#
I am only able to print '*', but not hashes.
here's my code to print '*'
max = 6
for x in range(1,max+1):
for y in range(1,x+1):
print '*',
print
length = 6
for x in range(1, length+1):
print(x * '*' + (length - x) * '#') # integer * (string), concatenate the string integer times
How to Print * in a triangle shape in python?
*
* *
* * *
* * * *
* * * * *
This is one of the coding interview questions.
def print_triangle(n):
for i, j in zip(range(1,n+1), range(n,0,-1)):
print(" "*j, '* '*i, " "*j)
print_triangle(5)

diamond structure using asterix in python [duplicate]

This question already has answers here:
Printing an ASCII diamond with set width in python
(7 answers)
Closed 8 years ago.
i need to print a basic diamond structure using asterix in python. the program should read the number of rows and print an output. eg-if the number of rows is 5 then there should be 3 of the big triangle and 2 of the reversed to give us 5 rows. also this code is cor python 2.7.
sample output should be like if width=5
*
* *
* * *
* *
*
this is what i attempted
width=input("enter the number of rows")
for num in range(1, width-1 , 1):
print(('*' * num).center(width))
for num in reversed(range(1, width-2, 1)):
print(('*' * num).center(width))
I wasn't supposed to code that, but I like this stuff. This works for both even and odd numbers:
rows = input("enter the number of rows")
for num in range(1, rows // 2 + 1) + range((rows + 1) // 2, 0, -1):
print(' '.join('*' * num).center(rows))
Output rows = 5:
*
* *
* * *
* *
*
Output rows = 6:
*
* *
* * *
* * *
* *
*
EDIT
This is also nice:
for num in xrange(rows):
print(' '.join('*' * min(num + 1, rows - num)).center(rows))

Hollow Diamond in python

My goal is to create a hollow diamond using python.
Sample input:
Input an odd Integer:
9
Sample output:
*
* *
* *
* *
* *
* *
* *
* *
*
But so far, I have the following code that is not working right. Please help me to modify the code to achieve the goal above:
a=int(input("Input an odd integer: "))
k=1
c=1
r=a
while k<=r:
while c<=r:
print "*"
c+=1
r-=1
c=1
while c<=2*k-1:
print "*"
c+=1
print "\n"
k+=1
r=1
k=1
c=1
while k<=a-1:
while c<=r:
print " "
c+=1
r+=1
c=1
while c<= 2*(a-k)-1:
print ("*")
c+=1
print "\n"
k+=1
The code above return a result that is very far from my goal.
Input an odd integer: 7
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
I am actually converting the code from this post: http://www.programmingsimplified.com/c/source-code/c-program-print-diamond-pattern written in C language and will modify later for the hollow one but I can't get it... There is something wrong with my conversion..
A Hollow diamond is the solution to the equation
|x|+|y| = N
on an integer grid. So Hollow diamond as a 1-liner:
In [22]: N = 9//2; print('\n'.join([''.join([('*' if abs(x)+abs(y) == N else ' ') for x in range(-N, N+1)]) for y in range(-N, N+1)]))
*
* *
* *
* *
* *
* *
* *
* *
*
Your problem is that you keep using print. The print statement (and the function in Python 3) will add a line-break after what you printed, unless you explicitely tell it not to. You can do that in Python 2 like this:
print '*', # note the trailing comma
Or in Python 3 (with the print function) like this:
print('*', end='')
My solution
I took my own take at the problem and came up with this solution:
# The diamond size
l = 9
# Initialize first row; this will create a list with a
# single element, the first row containing a single star
rows = ['*']
# Add half of the rows; we loop over the odd numbers from
# 1 to l, and then append a star followed by `i` spaces and
# again a star. Note that range will not include `l` itself.
for i in range(1, l, 2):
rows.append('*' + ' ' * i + '*')
# Mirror the rows and append; we get all but the last row
# (the middle row) from the list, and inverse it (using
# `[::-1]`) and add that to the original list. Now we have
# all the rows we need. Print it to see what's inside.
rows += rows[:-1][::-1]
# center-align each row, and join them
# We first define a function that does nothing else than
# centering whatever it gets to `l` characters. This will
# add the spaces we need around the stars
align = lambda x: ('{:^%s}' % l).format(x)
# And then we apply that function to all rows using `map`
# and then join the rows by a line break.
diamond = '\n'.join(map(align, rows))
# and print
print(diamond)
def diamond(n, c='*'):
for i in range(n):
spc = i * 2 - 1
if spc >= n - 1:
spc = n - spc % n - 4
if spc < 1:
print(c.center(n))
else:
print((c + spc * ' ' + c).center(n))
if __name__ == '__main__':
diamond(int(input("Input an odd integer: ")))
this is not pretty, but its a function that does what you want:
def make_diamond(size):
if not size%2:
raise ValueError('odd number required')
r = [' ' * space + '*' + ' ' * (size-2-(space*2)) + '*' + ' ' * space for space in xrange((size-1)/2)]
r.append(' ' * ((size-1)/2) + '*' + ' ' * ((size-1)/2))
return '\n'.join(r[-1:0:-1] + r)
first i check to make sure its an odd number,
then i create a list of the lines from the center downwards.
then i create the last point.
then i return them as as a string, with a mirror of the bottom on top without the center line.
output:
>>> print make_diamond(5)
*
* *
* *
* *
*
>>> print make_diamond(9)
*
* *
* *
* *
* *
* *
* *
* *
*
Made it in one single loop ;)
x = input("enter no of odd lines : ") #e.g. x=5
i = int(math.fabs(x/2)) # i=2 (loop for spaces before first star)
j = int(x-2) #j=3 # y & j carry loops for spaces in between
y = int(x-3) #y=2
print ( " " * i + "*" )
i = i-1 #i=1
while math.fabs(i) <= math.fabs((x/2)-1): # i <= 1
b = int(j- math.fabs(y)) # b = (1, 3, 1) no of spaces in between stars
a = int(math.fabs(i)) # a = (1, 0, 1) no of spaces before first star
print (" "* a + "*" + " "*b + "*")
y = y-2 # 2,0,-2
i = i-1 # 1,0,-1, -2 (loop wont run for -2)
i = int(math.fabs(i)) # i = -2
print ( " " * i + "*")
The previous answer has got two corrections, which've been done here :
import math
x = int(input("enter no of odd lines : ")) #e.g. x=5
i = int(math.fabs(x/2)) # i=2 (loop for spaces before first star)
j = int(x-2) #j=3 # y & j carry loops for spaces in between
y = int(x-3) #y=2
print ( " " * i + "*" )
i = i-1 #i=1
while math.fabs(i) <= math.fabs((x/2)-1): # i <= 1
b = int(j- math.fabs(y)) # b = (1, 3, 1) no of spaces in between stars
a = int(math.fabs(i)) # a = (1, 0, 1) no of spaces before first star
print (" "* a + "*" + " "*b + "*")
y = y-2 # 2,0,-2
i = i-1 # 1,0,-1, -2 (loop wont run for -2)
i = int(math.fabs(i)) # i = -2
print ( " " * i + "*")
Note : Now this works for both python 2.5x and python 3.x
If you wish to know the difference in the two answers, then google it!
sizeChoice = 13
N = sizeChoice//2
for column in range (-N, N + 1):
for row in range (-N, N + 1):
if abs(column) + abs(row) == N:
print ("*", end = " ")
else:
print(" ", end = " ")
print ( )
this code works perfectly to print a hollow diamond where you can set diagonal length upto user requirement
n=int(input('Enter Odd Diagonal length :'))-1
j=n-1
print(' '*(n)+'*')
for i in range(1, 2*n):
if i>n:
print(' '*(i-n)+'*'+' '*(2*j-1)+'*')
j-=1
else:
print(' '*(n-i)+'*'+' '*(2*i-1)+'*')
if n>1:
print(' '*n+'*')
Hallow Diamond in Python using only print function
for i in range(1,6):
print(' '*(5-i) + '*'*1 + ' '*(i-1) + ' '*max((i-2),0) + '*'*(1%i) )
for j in range(4,0,-1):
print(' '*(5-j) + '*'*1 + ' '*(j-1) + ' '*max((j-2),0) + '*'*(1%j) )

Categories