Making a hollow box in Python to these specifications? - python

I'm to "Write a python program that prompts the user to input a positive integer n. The program then prints a hollow rectangle with n rows and 2*n columns. For a example an input of 3 would output:"
******
* *
******
And my code is:
n=int(input('Please enter a positive integer between 1 and 15: '))
for col in range(n):
for row in range(n):
print('*' if col in(0,(2*n)+1) or row in(0,n+1) else ' ', end=' ')
print()
But my output doesn't look at all like what I need; it's like the upper and left half of a hollow box. In addition, I'm not getting double columns like I need. What am I doing wrong?
EDIT: Thank you everyone for your help! Gave me a lot of insight and was very helpful. I modified my code to the following, and it works very well:
>n=int(input('Please enter a positive integer between 1 and 15: '))
>for row in range(n):
> for col in range(2*n):
> print('*' if row in(0,n-1) or col in(0,(2*n)-1) else ' ', end=' ')
> print()
Special shout out to user2357112; you made me realize exactly what I had tripped up.

My solution:
# Response to StackOverflow post:
# Making a hollow box in Python
# The multiplication operator (*) is the same as repeated
# concatenation when applied to strings in Python.
# I solved the problem by creating an array with N elements
# and gluing them together (str.join(array)) with newline
# characters.
# I trust you're already familiar with string formatting and
# concatenation, but in case you're not, please feel free to
# ask for clarification.
def main():
n = int (input("Enter an integer between 1 and 15"))
box = "\n".join(["*"*(2*n)] + ["*%s*" % (" "*(2*n-2))]*(n-2) + ["*"*(int(n>1)*2*n)])
print (box)
if __name__ == '__main__':
main()
input() # Prevents the console from closing immediately
As for your solution. it seems to me like the loop conditions are messed up; the column and row loops are in reverse order and the argument to range() in the column loop should be 2*n (since that's the number of columns intersecting each row). You should also take a second look at the conditions in the first print statement.

The code should be like:
line = "*"*(2*n)
print line
s = "*" + " "*(n-2) + "*"
for i in range(n-2):
print s
print line
The line:
"*"*(2*n)
specifies a string of "*", repeated 2*n times. You wanted 2*n column right.. This prints 2*n "*"

def make_box():
size = int(input('Please enter a positive integer between 1 and 15: '))
for i in range(size):
if i == 0 or i == size - 1:
print("*"*(size+2))
else:
print("*" + " "*size + "*")
make_box()
Output: (n=15)
*****************
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
*****************

Code:
def printStars(length):
l = ['*'*length]
l+= ['*' + ' '*(length-2) + '*'] * (length-2)
l+= ['*'*length]
return l
if __name__=='__main__':
print('\n'.join(printStars(15)))
Output:
***************
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
***************
Hope this helps :)
EDIT:Fixed Some Formatting

My solution is more elementary. Please consider it :
row = abs(eval(input('Enter row: ')))
col = abs(eval(input('Enter column: ')))
print ('*'*col)
for i in range (row-2):
print ('*'+' '*(col-2)+'*')
print ('*'*col)

Related

How to draw a certain pyramid pattern

I'm trying to get these shapes:
if num=9
*
* *
* *
* *
* *
if num=5
*
* *
* *
if num=3
*
* *
(Only odd inputs)
num = int(input())
for row in range(num):
for col in range((num*2)-1):
if row==0 and col==((num*2)-1)//2 or row==1 and (col==2 or col==6) or row==2 and (col==0 or col==8):
print('*', end='')
else:
print(end=" ")
print()
This is what I managed to write but the code is hardcoded to draw a pyramid of 5 stars, so giving it any other input would mess the shape
I got column and row from a quick sketch
based on this image
I would like to automate the code so any input I feed it, it would draw this specific pyramid shape. I need help, thank you.
Start thinking about how different properties relate to the input number, and make a variable for each one. Start with how many rows, and how many columns. Then think of an equation that can give you the star location based on the current column and row. This should be easy to determine from the diagram you posted.
num = int(input())
num_rows = (num // 2) + 1
num_cols = (num * 2) - 1
middle_col = num - 1
for row_index in range(num_rows):
left_star_col = middle_col - (2 * row_index)
right_star_col = middle_col + (2 * row_index)
for col_index in range(num_cols):
if col_index == left_star_col or col_index == right_star_col:
print("*", end="")
else:
print(" ", end="")
print() # newline
Here's a way with a helper list. For each row, place a star i steps left of the middle and i steps right of the middle:
half = num // 2
for i in range(half + 1):
row = [' '] * num
row[half-i] = row[half+i] = '*'
print(*row)
Output for num = 9 (Try it online!):
*
* *
* *
* *
* *
It prints a few spaces at the end of the upper lines. If that's troublesome, make the row just as long as needed:
half = num // 2
for i in range(half + 1):
row = [' '] * (half + i + 1)
row[half-i] = row[half+i] = '*'
print(*row)
If you replace the ' ' with '-', you can see more what's happening:
- - - - *
- - - * - *
- - * - - - *
- * - - - - - *
* - - - - - - - *
This should give you the output very close what you desire. When you run you may see the first '*' little bit off to the left, but you can adjust for that.
def pyramid(n):
ll = []
ct = 0
for row in range(n//2, -1, -1):
l = [''] * n
l[row] = '*'
l[row + ct] = '*'
ct += 2
ll.append(l)
print('\n'.join(' '.join(row) for row in ll))
With minor adjustment, below should give you exactly what you need.
def pyramid(n):
ll = []
ct = 0
for row in range(n//2, -1, -1):
l = [''] * n
l[row] = '*'
l[row + ct] = '*'
ct += 2
ll.append(l)
l.insert(n//2, '')
print('\n'.join(' '.join(row) for row in ll))
One option is to define the pyramid shape as a graph: of the form y = abs(x - offset) (interactive demo here)
This can be done in python like so:
num = int(input())
for row in range(num // 2 + 1):
for col in range(num * 2 - 1):
if 2 * row == abs(num - 1 - col):
print('*', end='')
else:
print(end=" ")
print()
Your row counter is too high, since num is the number of columns.
It's simpler if you treat row 0 specially, since it only has one * rather than 2.
Rather than looping over columns, calculate the number of spaces you need and print that many spaces using " " * count
for row in range(num//2 + 1):
if row == 0:
print((" " * (num//2)) + "*")
else:
print((" " * (num//2 - row)) + "*" + (" " * (row*4 - 1)) + "*")

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)

Python - creating a square with asterixes [duplicate]

I'm to "Write a python program that prompts the user to input a positive integer n. The program then prints a hollow rectangle with n rows and 2*n columns. For a example an input of 3 would output:"
******
* *
******
And my code is:
n=int(input('Please enter a positive integer between 1 and 15: '))
for col in range(n):
for row in range(n):
print('*' if col in(0,(2*n)+1) or row in(0,n+1) else ' ', end=' ')
print()
But my output doesn't look at all like what I need; it's like the upper and left half of a hollow box. In addition, I'm not getting double columns like I need. What am I doing wrong?
EDIT: Thank you everyone for your help! Gave me a lot of insight and was very helpful. I modified my code to the following, and it works very well:
>n=int(input('Please enter a positive integer between 1 and 15: '))
>for row in range(n):
> for col in range(2*n):
> print('*' if row in(0,n-1) or col in(0,(2*n)-1) else ' ', end=' ')
> print()
Special shout out to user2357112; you made me realize exactly what I had tripped up.
My solution:
# Response to StackOverflow post:
# Making a hollow box in Python
# The multiplication operator (*) is the same as repeated
# concatenation when applied to strings in Python.
# I solved the problem by creating an array with N elements
# and gluing them together (str.join(array)) with newline
# characters.
# I trust you're already familiar with string formatting and
# concatenation, but in case you're not, please feel free to
# ask for clarification.
def main():
n = int (input("Enter an integer between 1 and 15"))
box = "\n".join(["*"*(2*n)] + ["*%s*" % (" "*(2*n-2))]*(n-2) + ["*"*(int(n>1)*2*n)])
print (box)
if __name__ == '__main__':
main()
input() # Prevents the console from closing immediately
As for your solution. it seems to me like the loop conditions are messed up; the column and row loops are in reverse order and the argument to range() in the column loop should be 2*n (since that's the number of columns intersecting each row). You should also take a second look at the conditions in the first print statement.
The code should be like:
line = "*"*(2*n)
print line
s = "*" + " "*(n-2) + "*"
for i in range(n-2):
print s
print line
The line:
"*"*(2*n)
specifies a string of "*", repeated 2*n times. You wanted 2*n column right.. This prints 2*n "*"
def make_box():
size = int(input('Please enter a positive integer between 1 and 15: '))
for i in range(size):
if i == 0 or i == size - 1:
print("*"*(size+2))
else:
print("*" + " "*size + "*")
make_box()
Output: (n=15)
*****************
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
*****************
Code:
def printStars(length):
l = ['*'*length]
l+= ['*' + ' '*(length-2) + '*'] * (length-2)
l+= ['*'*length]
return l
if __name__=='__main__':
print('\n'.join(printStars(15)))
Output:
***************
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
***************
Hope this helps :)
EDIT:Fixed Some Formatting
My solution is more elementary. Please consider it :
row = abs(eval(input('Enter row: ')))
col = abs(eval(input('Enter column: ')))
print ('*'*col)
for i in range (row-2):
print ('*'+' '*(col-2)+'*')
print ('*'*col)

Using Python to create a right triangle

I'm confused and frustrated as to why my program is not executing the way it should. I am trying to create a right triangle using asterisks on python ver 3. I am using the exact code from the text book and it comes out as a straight line. Please enlighten me.
example
size = 7
for row in range (size):
for col in range (row + 1):
print('*', end='')
print()
results in
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
all in one column
In Python, indentation counts. The final print should be aligned with the second for.
size = 7
for row in range (size):
for col in range (row + 1):
print('*', end='')
print()
Result:
*
**
***
****
*****
******
*******
An empty print function effectively means "move to a new line". if both print statements occur at the same indentation level, then every time you print an asterisk, you'll move to the next line. If the second print goes outside the inner for loop, you'll only get 7 newlines.
as an alternative you can use one for loop !
>>> s=''
>>> for i in range(7):
... s+='*'
... print (s)
...
*
**
***
****
*****
******
*******
It may not be the most readable solution but if you fancy oneliners this is one way of doing it:
print "\n".join(["".join(["*" for col in range(row+1)]) for row in range(7)])
EDIT
Just to make it even shorter:
print "\n".join(["*" * (row+1) for row in range(7)])
str1 = 'x '
str2 = ' ' #give space within the inverted comma
for i in range (1,6):
print((str2 * (5 - i)) + (str1 * i))
#print((str1 * i)+(str2 * (5 - i)))
other program:
str1 = 'x '
str2 = '' #give empty string(remove sace from the single inverted comma)
for i in range (1,6):
print((str2 * (5 - i)) + (str1 * i))
#print((str1 * i)+(str2 * (5 - i)))

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