Creating a diamond pattern using loops - python

I am trying to write a program that reads an integer and displays, using asterisks, a filled diamond of the given side length. For Example, if the side length is 4, the program should display
*
***
*****
*******
*****
***
*
Here is what I am trying to do. It is executing, but I can't seem to get the spaces right for the program to show the diamond shape properly....
userInput = int(input("Please input side length of diamond: "))
if userInput > 0:
for i in range(userInput):
for s in range(userInput -3, -2, -1):
print(" ", end="")
for j in range(i * 2 -1):
print("*", end="")
print()
for i in range(userInput, -1, -1):
for j in range(i * 2 -1):
print("*", end="")
print()
Thank you!

How about the following:
side = int(input("Please input side length of diamond: "))
for x in list(range(side)) + list(reversed(range(side-1))):
print('{: <{w1}}{:*<{w2}}'.format('', '', w1=side-x-1, w2=x*2+1))
Giving:
*
***
*****
*******
*********
***********
*********
*******
*****
***
*
So how does it work?
First we need a counter that counts up to side and then back down again. There is nothing stopping you from appending two range lists together so:
list(range(3)) + list(reversed(range(3-1))
This gives you a list [0, 1, 2, 1, 0]
From here we need to work out the correct number of spaces and asterisks needed for each line:
* needs 2 spaces 1 asterix
*** needs 1 space 3 asterisks
***** needs 0 spaces 5 asterisks
So two formulas are needed, e.g. for side=3:
x 3-x-1 x*2+1
0 2 1
1 1 3
2 0 5
Using Python's string formatting, it is possible to specify both a fill character and padding width. This avoids having to use string concatenation.
If you are using Python 3.6 or later, you can make use of f string notation:
for x in list(range(side)) + list(reversed(range(side-1))):
print(f"{'': <{side - x - 1}} {'':*<{x * 2 + 1}}")

This might work better for you:
n = userInput
for idx in range(n-1):
print((n-idx) * ' ' + (2*idx+1) * '*')
for idx in range(n-1, -1, -1):
print((n-idx) * ' ' + (2*idx+1) * '*')
Output for userInput = 6:
*
***
*****
*******
*********
***********
*********
*******
*****
***
*

Thanks Guys, I was able to formulate/correct my code based on the help I received. Thanks for all your input and helping the SO community!
if userInput > 0: # Prevents the computation of negative numbers
for i in range(userInput):
for s in range (userInput - i) : # s is equivalent to to spaces
print(" ", end="")
for j in range((i * 2) - 1):
print("*", end="")
print()
for i in range(userInput, 0, -1):
for s in range (userInput - i) :
print(" ", end="")
for j in range((i * 2) - 1):
print("*", end="")
print()

def build(width):
if width%2==0:
x=[(' *'*i).center(width*2,' ') for i in range(1,(width*2/2))]
else:
x=[(' *'*i).center(width*2+1,' ') for i in range(1,((width*2+1)/2))]
for i in x[:-1]+x[::-1]: print i
This worked for me for any positive width, But there are spaces padding the *s

How about this:
n = 5
stars = [('*' + '**'*i).center(2*n + 1) for i in range(n)]
print('\n'.join(stars + stars[::-1][1:]))
The output:
*
***
*****
*******
*********
*******
*****
***
*
This is similar to some of the answers above, but I find the syntax to be more simple and readable.

Related

Hello To print the second part of the code in reverse, for example, for the number 6, the output should be equal to the attached photo of this code

n=int(input("type a number:"))
for i in range(n+1):
a ='*'*i
print(a)
This is the output for the number 6:
You could do something like, using a little custom generator for the pyramid pattern:
def updown(n):
yield from range(1, n)
yield from range(n, 0, -1)
for i in updown(6):
print(i * '*')
*
**
***
****
*****
******
*****
****
***
**
*
There might be better ways to do it (and this doesn't feel too useful anyway), but this should work.
n=int(input("type a number:"))
i = 0
while i <= n:
i+=1
print("*"*i)
while i > 0:
i-=1
print("*"*i)
You can also use something like this
def pattern(n):
return list(range(1, n+1)) + list(range(n-1, 0, -1))
>>> for i in pattern(6):
... print(i * '*')
*
**
***
****
*****
******
*****
****
***
**
*

Print triangle pattern using nested loops

I need to make a "Pyramid" that would look so if the height someone would input was say 2:
*
***
or if someone would input a height of about 6 it would look like this:
*
***
*****
*******
*********
***********
I got down the code for the previous triangle:
n = int(input("Enter a value for n: "))
for x in range(1, n+1):
for y in range(n, 0, -1):
if y > x:
print(" ", end = "")
else:
print("*", end = "")
print("")
for x in range(1, n):
for y in range(n):
if y < x:
print(" ", end = "")
else:
print("*", end = "")
print("")
That prints the triangle
*
**
***
****
*****
******
*****
****
***
**
*
You can do this easily with format and 3 lines
>>> n = int(input("Enter a value for n: "))
Enter a value for n: 6
>>> for i in range(1,n*2,2):
... print("{}{}".format(' '*(n-i/2-1),'*'*i))
...
*
***
*****
*******
*********
***********
I think this is easier
n = int(input("Please enter an integer: "))
for x in range(1, n+1):
print("*" * x)
for y in range(n-1, 0, -1):
print("*" * y)

Python 3.4: creating an asterisk diamond

so I've been trying to create a program where you prompt the user for the number of rows, and then the program prints out a diamond with input number of rows.
This is what the program is supposed to do:(image)
This is what my code looks like
def main():
ROWS = get_input()
draw_pattern(ROWS)
def get_input():
return int(input("Enter the number of rows (or -1 or -99 to quit): "))
def draw_pattern(ROWS):
if ROWS == -1 or ROWS == -99:
quit
else:
for x in range(0,(int)((ROWS/2)+1),1):
print ((int)((ROWS/2)-(2*x+1)/2)*" " + (2*x+1) * '*')
for t in range((int)(x),0,-1):
print((int)((ROWS/2)-(2*t-1)/2)*" " + (2*t-1) * '*')
main()
This is what it ends up doing:
Enter the number of rows (or -1 or -99 to quit): 7
*
***
*
*****
***
*
*******
*****
***
*
So what am I doing wrong? I assume it's something in my for loop that makes the rows not line up correctly. Can anyone give me a little help? Thanks.
I got it to work like this. (< 3 mins) (DO NOT use even numbers its going to look odd)
def main():
ROWS = get_input()
draw_pattern(ROWS)
def get_input():
return int(input("Enter the number of rows (or -1 or -99 to quit): "))
def draw_pattern(ROWS):
if ROWS == -1 or ROWS == -99:
return
else:
for x in range(1, ROWS, 2):
print(' ' * int(ROWS / 2.0 - x / 2.0) + ("*" * x))
for x in range(ROWS, 1, -2):
print(' ' * int(ROWS / 2.0 - x / 2.0) + ("*" * x))
if x != 1:
print(' ' * int(ROWS / 2.0 - 1 / 2.0) + ("*" * 1))
main()
There are many ways to do this, you can generate all the strings then print them out using formatting to center the diamond, e.g.:
>>> row = 5
>>> d = ('*' * (n if n <= row else 2*row-n) for n in range(1, 2*row, 2))
>>> for i in d:
... print('{:^{w}}'.format(i, w=row))
*
***
*****
***
*
For row = 4:
*
***
***
*
Points for obfuscation?
star = lambda rows:'\n'.join(('*'*(2*(i if i<rows//2 else rows-i-1)+1)).center(rows) for i in range(rows))
Odd
print(star(5))
*
***
*****
***
*
Even
print(star(4))
*
***
***
*

python nested loop output art and reverseal

I am trying to write a program that looks something like this if, say, the input number was 6, or something like that the output should look like this:
*
**
***
****
*****
******
*****
****
***
**
*
but when I do it like I was told, this way specifically because this is what a classmate told me to do. :
n = int(input("Enter a value for n: "))
for i in range(1, n + 1):
for j in range(n):
if n - j > i:
print(" ", end = " ")
else:
print("*", end = " ")
print("")
for i in range(1, n):
for j in range(n):
if n - j < i:
print(" ", end = " ")
else:
print("*", end = " ")
print("")
I get:
*
**
***
****
*****
******
*****
****
***
**
*
What am I doing wrong? Please tell me how to get it to correctly line up, I'd really appreciate it if someone could help me with this so I can learn to do this on my own, please assist me...
If your assignment requires you to write the code exactly as you posted, Austin Kootz answer is the way to go.
However, a more simplifed way of doing this is using ljust
n = 6
for x in range(n - 1, 0, -1):
print ''.ljust(x, ' ') + '*'.ljust(n - x, '*')
for x in range(n):
print ''.ljust(x, ' ') + '*'.ljust(n - x, '*')
Your loops are a bit overcomplicated, so I've simplified somewhat:
n = int(input("Enter a value for n: "))
for x in range(n):
out = ''
for y in range(n-x):
out = out +' '
for y in range(x):
out = out +'*'
print(out)
for x in range(n):
out = ''
for y in range(x):
out = out +' '
for y in range(n-x):
out = out +'*'
print(out)
Enjoy!
What you want in the second set of loops is to take the row number (counting from 1) and print that many spaces (" "), and then print asterisks ("*") for the rest of the row. So if i is the row number and j the column number (and indexing starts from 0), you should print " " while j < i + 1 and "*" otherwise. This gives:
# The top part of the pyramid
for i in range(1, n + 1):
for j in range(n):
if n - j > i:
print(" ", end = " ")
else:
print("*", end = " ")
print("")
# The bottom half of the pyramid
for i in range(n):
for j in range(n):
# Print spaces in the beginning of the row
# (while the column number is less than the row number)
if j < i + 1:
print(" ", end = " ")
# Print asterisks for the rest of the row
else:
print("*", end = " ")
print("")

Asterisk Triangle

I'm coming from a background in Google's App Inventor. I'm taking an online class.
Task: Make a triangle out of asterisks with a nested while loop. The triangle has a base of 19 asterisks and a height of 10 asterisks.
Here's where I am.
Num = 1
while Num <= 19:
print '*'
Num = Num * '*' + 2
print Num
what you are doing with
Num = Num * '*' + 2
is the following:
you create a string (Num-times '*') this is what you want
then you try to add two, you'll probably see an error like cannot concatenate 'str' and 'int' objects, because there is no way to add a string to an int (at least in python). Instead you probably want to add two only to Num.
Here's a cool trick - in Python, you can multiply a string by a number with *, and it will become that many copies of the string concatenated together.
>>> "X "*10
'X X X X X X X X X X '
And you can concatenate two strings together with +:
>>> " "*3 + "X "*10
' X X X X X X X X X X '
So your Python code can be a simple for loop:
for i in range(10):
s = ""
# concatenate to s how many spaces to align the left side of the pyramid?
# concatenate to s how many asterisks separated by spaces?
print s
n = 0
w = 19
h = 10
rows = []
while n < h:
rows.append(' '*n+'*'*(w-2*n)+' '*n)
n += 1
print('\n'.join(reversed(rows)))
Produces
*
***
*****
*******
*********
***********
************* #etc...
*************** #2 space on both sides withd-4 *
***************** #1 space on both sides, width-2 *
******************* #0 spaces
>>> len(rows[-1])
19
>>> len(rows)
10
you can use the 'center'-method from string-objects:
width = 19
for num in range(1, width + 1, 2):
print(('*' * num).center(width))
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
Usually you wouldn't use a nested while loop for this problem, but here's one way
rows = 10
while rows:
rows -=1
cols = 20
line = ""
while cols:
cols -=1
if rows < cols < 20-rows:
line += '*'
else:
line += ' '
print line
(count - 1) * 2 + 1 calculates the number of asterisks in each row.
count = 1
while count <= 10:
print('*' * ((count - 1) * 2 + 1))
count += 1
You can go the easy way of course.
count = 1
while count <= 20:
print('*' * count)
count += 2

Categories

Resources