How to print a pyramid in Python? - python

How to make a pyramid?
I need to make a function, that prints a full pyramid.
For example
(13 is the base width of the pyramid and 1 is the width of the top row.)
pyramid(13, 1)
Result:
.
.....
.........
.............
The step should be 4, so each row differs from the last row by 4 dots.
Edit:
This is what I have so far, but I only got the half of the pyramid and the base isn't what it's supposed to be.
def pyramid(a, b):
x = range(b, a+1, 4)
for i in x:
print(" "*(a-i) + "."*(i))
pyramid(17,1)

Try this :
def pyramid(a, b):
for i in range(b,a+1,4) :
print(str( " " *int((a-i)/2) )+ "."*(i)+ str( " " *int((a-i)/2) ))
Output:
pyramid(17,1)
.
.....
.........
.............
.................

Here is my contribution, using - character instead of blank space, for a better visualization:
def pyramide(base, top, step=4):
dot = "."
for i in range(top, base+1, step):
print((dot*i).center(base, "-"))
pyramide(13,1)
Output
------.------
----.....----
--.........--
.............

# Function to demonstrate printing pattern triangle
def triangle(n):
# number of spaces
k = 2*n - 2
# outer loop to handle number of rows
for i in range(0, n):
# inner loop to handle number spaces
# values changing acc. to requirement
for j in range(0, k):
print(end=" ")
# decrementing k after each loop
k = k - 1
# inner loop to handle number of columns
# values changing acc. to outer loop
for j in range(0, i+1):
# printing stars
print("* ", end="")
# ending line after each row
print("\r")
# Driver Code
n = 5
triangle(n)

Related

Python program to give me numbers on the left with their sum on the right while having interchanged symbols in each line up to n (n=6)

Here's the picture of the program/ how it should work, it should display 1*1 then 12$3 < 3 is the sum of 1+2.. we only got to for loop.
I have tried a lot of solutions and this is what i got to at the end, for some reason i can't copy and paste it here without the code deleting whatever i had here..
also the output currently is:
please help and thanks a lot
I would implement this idea this way:
def func(n: int):
for i in range(1, n + 1):
nsum = 0 # Sum of numbers in nested loop.
last = 0 # Last number added to 'nsum'.
string = '' # Final string which is then printed.
for j in range(1, i + 1):
nsum += j # Add to total sum.
string += str(j) # Add to final string.
last = j # Set last number to current.
# Decide if either asterisk (*) or dollar ($) should be included
# in final message, after it append total sum.
string += ('*' if last % 2 else '$') + str(nsum)
print(string)
func(6)

Draw a centered triforce surrounded by hyphens using Python

I want to draw a triangle of asterisks from a given n which is an odd number and at least equal to 3. So far I did the following:
def main():
num = 5
for i in range(num):
if i == 0:
print('-' * num + '*' * (i + 1) + '-' * num)
elif i % 2 == 0:
print('-' * (num-i+1) + '*' * (i + 1) + '-' * (num-i+1))
else:
continue
if __name__ == "__main__":
main()
And got this as the result:
-----*-----
----***----
--*****--
But how do I edit the code so the number of hyphens corresponds to the desirable result:
-----*-----
----***----
---*****---
--*-----*--
-***---***-
*****-*****
There's probably a better way but this seems to work:
def triangle(n):
assert n % 2 != 0 # make sure n is an odd number
hyphens = n
output = []
for stars in range(1, n+1, 2):
h = '-'*hyphens
s = '*'*stars
output.append(h + s + h)
hyphens -= 1
pad = n // 2
mid = n
for stars in range(1, n+1, 2):
fix = '-'*pad
mh = '-'*mid
s = '*'*stars
output.append(fix + s + mh + s + fix)
pad -= 1
mid -= 2
print(*output, sep='\n')
triangle(5)
Output:
-----*-----
----***----
---*****---
--*-----*--
-***---***-
*****-*****
Think about what it is you're iterating over and what you're doing with your loop. Currently you're iterating up to the maximum number of hyphens you want, and you seem to be treating this as the number of asterisks to print, but if you look at the edge of your triforce, the number of hyphens is decreasing by 1 each line, from 5 to 0. To me, this would imply you need to print num-i hyphens each iteration, iterating over line number rather than the max number of hyphens/asterisks (these are close in value, but the distinction is important).
I'd recommend trying to make one large solid triangle first, i.e.
-----*-----
----***----
---*****---
--*******--
-*********-
***********
since this is a simpler problem to solve and is just one modification away from what you're trying to do (this is where the distinction between number of asterisks and line number will be important, as your pattern changes dependent on what line you're on).
I'll help get you started; for any odd n, the number of lines you need to print is going to be (n+1). If you modify your range to be over this value, you should be able to figure out how many hyphens and asterisks to print on each line to make a large triangle, and then you can just modify it to cut out the centre.

How can I use for loops to figure out how to solve this?

enter image description here5
I have to use a for loop to code this. I have tried many times but it never works.
enter code here
num_of_times = 5
for x in range(1, num_of_times, 5):
for y in range(5, i+5):
print(y, end= '')
print('')
You can try this:
lst = []
for i in range(1, 5):
lst.append(i * 5)
print(*lst)
You basically want to print multiple of 5. That could be achieved with two nested for loops:
max = 5
for i in range(max):
line = ''
for j in range(i+1):
line += str(5 * (j+1)) + ' '
print(line)
The first loop goes from 0 to max-1 and stores the index in i ; the second loop goes from 0 to i+1 and stores the index in j.
Then, the result of 5 * (j+1) is added to a variable called line printed at the end of the j-loop.
Feel free to follow the loops and the value of each variable at every step with a paper and a pen, that should help you.
Here you go
for i in range(1,6):
for j in range (1, i+1):
print(j*5, end = ' ')
print('')

Empty pyramid in python 3

I want to print an empty pyramid in python 3 and my teacher suggested me this code but i am confused about the list(array) and i want an alternative of this code. Is there any alternative method to print an empty pyramid. This code is also available on available on stackoverflow but i want to solve it by using simple if else.
#Function Definition
def Empty_triangle(n): # Here value of n is 5
for i in list(range(n-1))+[0]:
line = ""
leadingSpaces = n-2-i
line += " "*leadingSpaces
line += "*"
if i != 0:
middleSpaces = 2*i-1
line += " "*middleSpaces
line += "*"
print(line)
# Function Call
n = 5
Empty_triangle(n)
Example of code which i want
if (row==0 and row==5 and col!=0):
output should like this using ifelse
Can it be done with simple if else
In the code your teacher suggested, the "list" seems redundant. When n=5, the "range(n-1)" command already gives you the numeric list [0, 1, 2, 3, 4]. Since it's already a list, you don't need to put "list()" around it. Then the "+[0]" just adds 0 to the end to give you [0, 1, 2, 3, 4, 0]. Also, I'm not sure if you want that extra star at the bottom center.
There are lots of alternative ways to do it, but here's an alternative version I made:
def triangle2(n):
for row in range(n):
line = [ ' ' for i in range(n+row+1)]
line[n-row] = '*'
line[n+row] = '*'
print ''.join(line)
triangle2(5)
For each row, it creates a list of spaces that's just big enough for that row, then it replaces the spaces with the locations of where the stars should be. Finally it joins all of the spaces and stars into a string, and prints it.
An even shorter way is to essentially take half of each row, then mirror it to make the second half:
def triangle3(n):
for row in range(n):
line = [ ' ' for i in range(n-row) ] + ['*'] + [ ' ' for i in range(row)]
print(''.join(line[:-1] + line[::-1]))
Or skipping lists and joins and just using concatenated strings:
def triangle4(n):
for row in range(n):
first_half = ' '*(n-row) + '*' + ' '*row
second_half = first_half[::-1][1:]
print(first_half + second_half)
The "[::-1]" part is a little trick to reverse a string or list.
# Python 3.x code to demonstrate star pattern
# Function to demonstrate printing pattern triangle
def triangle(n):
# number of spaces
k = 2*n - 2
# outer loop to handle number of rows
for i in range(0, n):
# inner loop to handle number spaces
# values changing acc. to requirement
for j in range(0, k):
print(end=" ")
# decrementing k after each loop
k = k - 1
# inner loop to handle number of columns
# values changing acc. to outer loop
for j in range(0, i+1):
# printing stars
print("* ", end="")
# ending line after each row
print("\r")
# Driver Code
n = 5
triangle(n)
careful with indent.
previously whole code wasn't displayed.

Python 3 - convert the staircase from right-aligned to LEFT ALIGNED, composed of # symbols and spaces

sc = []
n = 6
for i in range(n):
sc.append("#")
scstr = ''.join(map(str, sc))
print(scstr)
I tried to use the code below to reverse the output by adding padding white spaces but it prints out a distorted staircase.
# print(scstr.rjust(n-i, ' ')) -- trying to print reversed staircase
Please help convert the staircase from right-aligned to LEFT ALIGNED, composed of # symbols and spaces.
Attached is a visual description of expected output
You can use str.rjust()
for i in range(1,n+1):
print( ('#'*i).rjust(n))
I like the new string formatting.
Code:
for i in range(10, -1, -1):
print("{0:#<10}".format(i*" "))
Produces:
#
##
###
####
#####
######
#######
########
#########
##########
You can "right align" a row by padding it with spaces. Here, the Ith rows should have N-I spaces and I hashes:
for i in range(1, n + 1):
print(' ' * (n - i) + '#' * i)
replace n with n+1
n = 6
for i in range(n+1):
print(' '*(n-i) + '#' * i)

Categories

Resources