Python Loop Reverse Diamond - python

I have a code that loops to create a diamond, but I would want it to be reversed.
width = int(input("Please enter a width: "))
i = 1
while i < width*2:
if i < width:
print("-" * (width-i) + " *" * i + "-" * (width-i))
else:
print("-" * (i-width) + " *" * (2*width-i) + "-" * (i-width))
i += 1 [EDIT: formatting mistake]
My output is as follows:
---- *----
--- * *---
-- * * *--
- * * * *-
* * * * *
- * * * *-
-- * * *--
--- * *---
---- *----
but I want it to be like this:
* * * * *
- * * * *-
-- * * *--
--- * *---
---- *----
---- *----
--- * *---
-- * * *--
- * * * *-
* * * * *
Help would be appreciated!

width = int(input("Please enter a width: "))
i = 0
while i < width*2:
if i < width:
print("-" * i+ " *" * (width-i) + "-" * i)
else:
print("-" * ((2*width-i) -1) + " *" * (i - width + 1) + "-" * ((2*width-i) -1))
i += 1

Related

printing 2 stars using strings side by side

Without using the function call, how can I modify my string to have the stars come out as side by side?
This is what I did:
print(" *\n * *\n * *\n * *\n * * * * * *\n"
" * *\n * *\n **********" , end = "\n *\n * *\n * *\n * *\n * * * * * *\n"
" * *\n * *\n **********" )
but this results in the stars coming out as top and bottom. I want it to print side by side.
You could use a triple quoted multi-line string to create an "arrow template" then utilize .splitlines() and zip() to print them side by side(with optional spacing between).
UP_ARROW = """
*
* *
* *
* *
* * * * * *
* *
* *
**********
""".strip("\n").splitlines()
for arrows in zip(UP_ARROW, [" "] * len(UP_ARROW), UP_ARROW):
print(*arrows)
Output:
* *
* * * *
* * * *
* * * *
* * * * * * * * * * * *
* * * *
* * * *
********** **********
#pass one arrow in a variable y
y = ''' *\n * *\n * *\n * *\n * * * * * *\n * *\n * *\n **********'''
#split on the linebreak
spl = y.split('\n')
#get width of the arrow
max_len = max([len(x) for x in spl])
#compute space for new arrow points as max width - position of last element
#of first arrow and repeat after space
new = [x + (max_len - len(x))*' ' +x for x in spl]
#join back on linebreaks
new = '\n'.join(new)
print(new)
* *
* * * *
* * * *
* * * *
* * * * * * * * * * * *
* * * *
* * * *
********** **********

How to print following empty up side down pattern

I am trying to print this following pattern , But not able to frame logic
My code :
for i in range(1,row+1):
if i == 1:
print(row * '* ')
elif i<row:
print( '* ' + ((row - 3) * 2) * ' ' + '*')
row = row - 1
else:
print('*')
Expected output :
* * * * * * * *
* *
* *
* *
* *
* *
* *
*
But my code gives me abnormal output :
* * * * * * * *
* *
* *
* *
*
*
*
*
#stacker's answer is nifty but mathematically a little overkill. This should do the trick just as well:
row = 8
print(row * '* ')
for i in range(1,row - 1):
rowlength = (row - i) * 2 - 3
print('*', end='')
print(rowlength * ' ', end='')
print('*')
print('*')
import math
row = 8;
for i in range(1,row+1):
if i == 1:
print(row * '* ')
elif i<(row * row) / (math.pi / math.sqrt(7)):
print( '* ' + ((row - 3) * 2) * ' ' + '*')
row = row - 1
else:
print('*')
Output:
* * * * * * * *
* *
* *
* *
* *
* *
* *
*
row=10
for i in range(1,row):
if i == 1:
print(row * '* ')
elif i < row:
print('* ' + (row-2)*2 * ' ' + '*')
row = row-1
elif i > row-2:
print('* ' + (row - 2) * 2 * ' ' + '*')
row = row - 1
Output:
* * * * * * * * * *
* *
* *
* *
* *
* *
* *
* *
* *
Process finished with exit code 0
Hope this helps

printing shapes in one line in python

I am trying to print 2 circles pattern in one row and two in the next row like this
Here is my Code:
cell = {}
row = 5
col = 5
for i in range(0,row):
for j in range(0,col):
if((j == 0 or j == col-1) and (i!=0 and i!=row-1)) :
cell[(i,j)] = '*'
#end='' so that print statement should not change the line.
elif( ((i==0 or i==row-1) and (j>0 and j<col-1))):
cell[(i,j)] = '*'
else:
cell[(i,j)] = " "
print(cell[(i, j)], end=" ")
print(end='\n')
And with this code I'm getting the output as follows:
what should I change in this code to make it correct?
You essentially need a template for top/bottom of a circle and the middle part of a circle.
Then you need to print enough of them per line:
nums = 7 # only squares supported
amount = 3 # shapes per line & shape rows in total
spacer = 2 # space horizontally, vertically it is 1 line
# prepare shapes
top_botton = f" {'*'*(nums-2)} "
middle = f"*{' '*(nums-2)}*"
space_h = " " * spacer
for row in range(amount * nums):
# detect which row we are in
mod_row = row % nums
# bottom or top of row
if mod_row in (0, nums-1):
print(*([top_botton]*amount), sep=space_h )
if mod_row == nums-1:
print()
# middle of row
else:
print(*([middle]*amount), sep=space_h)
Output:
# nums = 5, count = 2
*** ***
* * * *
* * * *
* * * *
*** ***
*** ***
* * * *
* * * *
* * * *
*** ***
# nums = 7, count = 3
***** ***** *****
* * * * * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *
***** ***** *****
***** ***** *****
* * * * * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *
***** ***** *****
***** ***** *****
* * * * * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *
***** ***** *****
The distance between the circles is handled by the sep=... of the print statement. It prints the decomposed list of (amount) shapes.
You could as well handle a "single char" printer like you did for your single cirle, but all those loops in loops and values modular checking are getting confusing fast.
for i in range(0,row):
for j in range(0,col):
if((j == 1 or j == col-1) and (i!=0 and i!=row+1)) :
cell[(i,j)] = ''
elif( ((i==0 or i==row-1) and (j>0 and j<col+1))):
cell[(i,j)] = ''
else:
cell[(i,j)] = " "
print(cell[(i,j)], end=" ")
print(end='\n')

How to transform this code that prints a hollow diamond to solid diamond?

Hello I'm fairly new to python and have a question I'm stuck on:
This is the original code to print a hollow diamond:
def print_diamond(height):
"""prints hollow diamond"""
print("{:^{}}".format("*", height))
for i in range(1, height // 2):
print("{:^{}}".format("*" + " " * (2*i - 1) + "*", height))
for i in range(height // 2, 0, -1):
print("{:^{}}".format("*" + " " * (2*i - 1) + "*", height))
print("{:^{}}".format("*", height))
#test code
print_diamond(5)
print_diamond(3)
print_diamond(7)
This outputs:
*
* *
* *
* *
*
*
* *
*
*
* *
* *
* *
* *
* *
*
How would you transform this code to print a solid diamond?
*
*
***
*
*
***
*****
***
*
*
***
*****
*******
*****
***
*
Using these tests:
print_diamond(1)
print_diamond(2)
print_diamond(3)
print_diamond(4)
I tried changing the formatting by adding " * " but that pushes the other " * " on the side. Thank you.
Adding " * " to the spaces " " does not fix the problem as the formating does not work with solid diamond test code.
It shouldn't output this currently:
*
*
*
***
*
*
***
*
Just replace " " with "*" in the following lines :
print("{:^{}}".format("*" + "*" * (2*i - 1) + "*", height))

How can i display a nested box inside the terminal using python with minimum codes?

The user will be asked to enter any positive number and the output will be the following:
If he enters '1':
***
* *
***
If he enters '2':
*******
* *
* *** *
* * * *
* *** *
* *
*******
If he enters '3':
***********
* *
* ******* *
* * * *
* * *** * *
* * * * * *
* * *** * *
* * * *
* ******* *
* *
***********
And so on. That means if the input is 'n', the output will be 'n' number of nested box in the following pattern.
PS:
Here I've tried some codes. But not getting the desired pattern.
try:
n = int(raw_input("Please Enter A Positive Number: "))
list = range(1, 4*n)
if n > 0:
for n in list:
if n % 2 == 0:
print "*" + " " * (list[-1]-2) + "*"
else:
if n:
print "*" * list[-1]
else:
pass
else:
print "You must choose any positive number."
except:
print "You must enter a number."
You could create a function to add a nesting layer to an existing box and then call this the required number of times as follows:
def add_nested(box):
new_box = []
lines = box.splitlines()
width = len(lines[0])
l1 = '*' * (width + 4)
l2 = '*{}*'.format(' ' * (width + 2))
new_box.extend([l1, l2])
for row in lines:
new_box.append('* {} *'.format(row))
new_box.extend([l2, l1])
return '\n'.join(new_box)
n = int(raw_input("Please Enter A Positive Number: "))
box = "***\n* *\n***"
for _ in range(n-1):
box = add_nested(box)
print box
So if 5 was entered, it would display:
Please Enter A Positive Number: 5
*******************
* *
* *************** *
* * * *
* * *********** * *
* * * * * *
* * * ******* * * *
* * * * * * * *
* * * * *** * * * *
* * * * * * * * * *
* * * * *** * * * *
* * * * * * * *
* * * ******* * * *
* * * * * *
* * *********** * *
* * * *
* *************** *
* *
*******************
How does it work?
The function first splits the existing box into lines and determines the width of the first line. It then creates two lines to go above and below the box (called l1 and l2). These have the correct number of * and for the new outer box. It then adds these to a list of lines. Then for each line in the existing box, it added * to the start of each line and * to the end. It then adds l2 and l1 to the end to complete the new nested box. It then returns this list of lines as a single string joined with newlines to create the new box. This function can then be called again and again to add further layers.
The code below progressively builds the top left corner of a nested set of boxes. It builds the right side by reflecting the left side, and it builds the bottom by reflecting the top.
We start with an empty base string and alternately add a star (on even lines) or a space (on odd lines) to this base; the current half-row is constructed from the base string by padding it with a star or space as appropriate.
The nested_box function does no printing, it returns a list of strings, so it's up to the calling code to do the actual printing.
def nested_box(n):
w = 2 * n
rows = []
base = ''
for i in range(w):
c = '* '[i % 2]
base += c
row = base.ljust(w, c)
rows.append(row + row[-2::-1])
return rows + rows[-2::-1]
# Test
for i in range(1, 5):
print('\n', i)
for row in nested_box(i):
print(row)
output
1
***
* *
***
2
*******
* *
* *** *
* * * *
* *** *
* *
*******
3
***********
* *
* ******* *
* * * *
* * *** * *
* * * * * *
* * *** * *
* * * *
* ******* *
* *
***********
4
***************
* *
* *********** *
* * * *
* * ******* * *
* * * * * *
* * * *** * * *
* * * * * * * *
* * * *** * * *
* * * * * *
* * ******* * *
* * * *
* *********** *
* *
***************
To run this code correctly on Python 2, put from __future__ import print_function at the top of the script. That's really only necessary for the print('\n', i) call, the box printing doesn't need it.
Just for fun, here's a "code golf" version:
def b(n):
r,a=[],''
for i in range(2*n):c='* '[i%2];a+=c;l=a.ljust(2*n,c);r+=[l+l[-2::-1]]
return'\n'.join(r+r[-2::-1])
for i in range(1, 5):print(i,b(i),sep='\n')

Categories

Resources