I want to make a function to print triangle like the following picture. User can insert the row number of the triangle. The total lenght of first row is must an odd.
I try to use below code :
def triangle(n):
k = 2*n - 2
for i in range(0, n):
for j in range(0, k):
print(end=" ")
k = k - 1
for j in range(0, i+1):
print("* ", end="")
print("\r")
n = 5
triangle(n)
Here is the expected output image :
and here is my actual output image :
but I can't remove the star middle star. And it's not Upside - Down Triangle
You could try a different way.
def triangle(n) :
for i in range(1,n+1) :
for j in range(1,i) :
print (" ",end="")
for j in range(1,(n * 2 - (2 * i - 1))
+1) :
if (i == 1 or j == 1 or
j == (n * 2 - (2 * i - 1))) :
print ("*", end="")
else :
print(" ", end="")
print ("")
n = 5
triangle(n)
Not sure how cool implementation is this but it gives results:
def triangle(n):
print(' '.join(['*']*(n+2)))
s = int((n/2)+1)
for i in range(s):
star_list = [' ']*(n+2)
star_list[-i-2] = ' *'
star_list[i+1] = '*'
print(''.join(star_list))
n = 5
triangle(n)
Output:
* * * * * * *
* *
* *
*
for n = 7:
* * * * * * * * *
* *
* *
* *
*
I would try a recursive solution where you call the printTriangle() function. This way, it will print the point first and move it's way down the call stack.
Related
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)) + "*")
def x_pattern(n):
for i in range(n):
for j in range(n):
if (j == i) or (j == n-1-i):
print('*', end='')
i=i+1
j=j-1
else:
print('', end='')
print()
When I run this function it is not showing what I am trying to achieve.
x_pattern(5)
x_pattern(6)
x_pattern(7)
x_pattern(8)
Could anybody please point out what I am doing wrong?
Edit: Removed i = i+1 and j = j+1 as patrick suggested
If you get an even number, you probably only want to print one of the two middle rows:
def x_pattern(n):
skip_middle = n%2 == 0
for i in range(n):
if i == n/2 and skip_middle: # skip one of the two middle lines of '...**...'
continue
for j in range(n):
if (j == i) or (j == n-1-i):
print('*', end='')
else:
print(' ', end='') # print a space here
print()
for l in range(5,9):
x_pattern(l)
print()
Output:
* *
* *
*
* *
* *
* *
* *
**
* *
* *
* *
* *
* *
*
* *
* *
* *
* *
* *
* *
**
* *
* *
* *
Problem here is that you get one row less then you specified - thats why I suggested adding the wanted output to your question.
This is my code which i wrote in python
n = 5
row = 2 * n - 2
for i in range(n,-1,-1):
for j in range(row):
print(end="")
row -=2
for k in range(i+1):
print('*',end=" ")
print()
The output what is get is this
* * * * *
* * * *
* * *
* *
*
i want to print this start from left to right order for example
The expected output is :-
* * * * *
* * * *
* * *
* *
*
if it's any possible way to print the elements from left to right because in most of my program i need that logic i'm searching for it please help me and even i used reversed function for loop it will reverse the loop but i'm not getting what i expect
n = 5
print(*[' '.join(' '*i + '*'*(n-i)) for i in range(n)], sep='\n')
Output:
* * * * *
* * * *
* * *
* *
*
Explanation:
for i in range(n):
chars = ' '*i + '*'*(n-i) # creating list of (i) spaces followed
# by (n-i) stars to finish a line of n elements
print(' '.join(chars)) # join prepared values with spaces
Here is a simple solution not using list comprehension:
n = 5
for i in range(n+1):
for j in range(i):
print(" ", end="")
for j in range(i+1, n+1):
print("* ", end="")
print()
Output:
* * * * *
* * * *
* * *
* *
*
My solution - I'm new to python as well:
n = 5
c = 0
for i in range(n, 0, -1):
print(" " * c + "*" * i)
c += 1
or
n = 5
c = 0
while n >= 0:
print(" " * c + "*" * n)
n -= 1
c += 1
The problem is that print itself cannot print right-justified text. But you can print a right-justified string instead of using multiple calls to print.
Here's your original code, using join instead of an inner loop:
n = 5
row = 2 * n - 2
for i in range(n,-1,-1):
for j in range(row):
print(end="")
row -=2
row_str = " ".join(["*"] * i)
print(row_str)
And here's the modified code to make the output right-justified:
n = 5
row = 2 * n - 2
whole = row + 1
for i in range(n,-1,-1):
for j in range(row):
print(end="")
row -=2
row_str = " ".join(["*"] * i).rjust(whole)
print(row_str)
This question already has answers here:
How to recreate pyramid triangle?
(3 answers)
Closed 5 years ago.
I am trying to print a triangle made of asterisk (*) separated by spaces.
If n = 4, it should look like:
*
* *
* * *
* * * *
This is the code I have:
n = 4
for i in range(1, n + 1):
for j in range(i):
print("*")
This is the result I get:
*
*
*
*
*
*
*
*
*
*
I would very appreciate what is wrong with my code...
print() adds a newline to your string each time.
It is easier to multiply the * with the number of times you would like to see it:
n = 4
for i in range(1, n + 1):
print("* " * i)
Output:
*
* *
* * *
* * * *
You could use the built-in "end" parameter:
n = 4
for i in range(1, n + 1):
for j in range(i):
print("*", end=" ")
print()
n = 4
for i in range(1, n + 1):
lvl = ""
for j in range(i):
lvl += "* "
print(lvl)
You need to aggregate the level of the triangle to print.
edit :
if you don't want spaces at the end of the line :-/
n = 4
for i in range(1, n+1):
print( " ".join([c for c in '*' * i]))
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) )