Asterisks Triangle in Python - python

I am trying to create a program that allows me to make a "pyramid" or "triangle" using asterisks, in the Python program. I've already started the code, but can't seem to figure it out.
Here's the code I've managed to figure out:
def triangle():
totalRows = int(eval(input("How big? ")))
for currentRows in range(1,totalRows+1):
for currentCol in range (1, currentRows+1):
print("*", end = " ")
triangle()
The end result is supposed to mirror this!
How big? 1
*
------------------------------------------------------
How big? 2
*
* *
------------------------------------------------------
How big? 3
*
* *
* * *
------------------------------------------------------

Slight modification to RParadox's solution to match requirement:
for i in range(totalRows + 1):
numWhite = totalRows - i
print ' ' * numWhite + '* ' * i

n = 10
for i in range(n-1):
numwhite = n-i
print ' '*numwhite + '*'*i + '*'*i
**
****
******
********
**********
************
**************
****************

def build_pyr(depth):
rows = [ (depth-i)*' ' + i*2*'*' + '*' for i in range(depth-1) ]
for i in rows:
print i
This works, however, it adds 2n + 1 asterisks at each depth. Just remove the + 1 asterisks from the list comprehension and add an initial asterisk to the row list before hand.

kiko="*"
empty=" "
def star(n):
for i in range(n):
print((n-i-1)*empty+(i+i+1)*kiko)
star(5)

def xmastree(maxwidth):
for i in xrange(1,maxwidth,2):
print '{0}'.format('*'*i).center(maxwidth)
or:
def xmastree2(maxrows):
for i in xrange(1,maxrows*2,2):
print '{0}'.format('*'*i).center(maxrows*2)
hmm, still no response, maybe not generic enough ? ok try this ;-) :
def triangle(pattern, n):
maxwidth = n*len(pattern)*2
for i in xrange(1,n*2+1,2):
print '{0}'.format(pattern*i).center(maxwidth)
>>> triangle(' ^', 5)
^
^ ^ ^
^ ^ ^ ^ ^
^ ^ ^ ^ ^ ^ ^
^ ^ ^ ^ ^ ^ ^ ^ ^

Woah, guys, you are going at it from a really complicated point of view! why don'y you just use this program? :
asterisknum = int(raw_input('How many asterisks? Input here: '))
base = 0
if asterisknum % 2 == 0:
print ('Added 1 to even number')
asterisknum = asterisknum + 1
while asterisknum != -1 :
print (' ' * base + '*' * asterisknum)
base = base + 1
asterisknum = asterisknum - 2
raw_input('Press <Enter> to exit')
I just made this program to work once, but I used the extremely simple parts of python that everybody should know. It could be tweaked to work again in the same program, or whatever...

def triangle(height):
maxstars = 1+ 2*(height -1)
spaces = int(maxstars/2)
for i in range(0,height):
print(" " * spaces +"*" * (1+ 2*i))
spaces = spaces -1
number = int(input("Please enter height of triangle: "))
triangle(number)

Imagine you have "blocks" of stars and space. Now add them on a canvas.
This is Python.
It glues objects together in this particular case
This code prints a diamond, the first loop is the upper half, the second loop is the lower half.
Note that i had to make new variables(objects) for the second loop.
Hope this helps guys :)
star = "*"
space = "." # dots are for presentation purposes
rows = 10
star_counter = 1
space_counter = rows
for i in range(rows):
print((space * (space_counter - 1 )) + (star * star_counter) +
(star * (star_counter - 1)) + (space * (space_counter - 1)) )
star_counter += 1
space_counter -= 1
star_counter_new = (rows - 1) # one row less for the lower triangle
# the upper triangle takes the base row
# that's why rows - 1
space_counter_new = 1
for j in range(rows - 1): # same goes here
print((space * (space_counter_new)) + (star * (star_counter_new)) +
(star * (star_counter_new - 1)) + (space * (space_counter_new )))
space_counter_new += 1
star_counter_new -= 1

it can be done in just few steps:
def main():
rows = input(" enter the number of rows : ")
for i in range (rows):
print ' '*(rows-i-1) + '*'*(2*i+1)
main()

def pypart2(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
pypart2(n)

Related

Python Shape Printing

Hi everyone, I have an assignment to acquire this shape in Python. I am a beginner, I tried to use nested loops to create this shape but I couldn't. Could someone help? Thanks a lot. (I couldn't copy the output exactly I'm sorry)
I used nested for loops, if and else statements in various ways (for example, I've tried to write stars at the end of a row) but I couldn't get the shape. I am editing the post in order to show you my effort. I am really sorry that my output is really different from the wanted one.
len = int(input("enter an odd number: "))
if len % 2 == 0:
print("enter an odd number")
else:
row = int((len+1) / 2)
for i in range (0,len):
print("#",end="")
print()
for i in range(0,row):
print("*")
print("*", end=" ")
for j in range(1,len):
print("*",end="")
for i in range(0,len):
print("#",end="")
for n = 5
#####
* *
* *
* *
* *
* *
* *
#####
This could be one way of solving it:
if we define n as the sample input, the shape can be divided into 3 steps of length (n//2) each.
Initialization: print('#'*n)
Step 1: for i in range(n//2): print('*'+' '*(n-2)+'*')
Step 2a: create a print_list: print_list = [k*' ' + '*'+ (n-2-2*k)*' ' + '*' + k*' ' for k in range(n//2)]
Step 2b: Now print each line in print_list
Step 3: Then print each line in print_list[::-1]
End: print('#'*n)
Implemented Code:
n = int(input("enter an odd number: "))
if n % 2 == 0:
print("enter an odd number")
else:
print("#"*n)
for i in range(n//2):
print('*'+' '*(n-2)+'*')
print_list = [k * ' ' + '*' + (n - 2 - 2*k) * ' ' + '*' + k * ' 'for k in range(n//2)]
for p in print_list: print(p)
for p in print_list[::-1]: print(p)
print("#"*n)

how to print string inside pyramid python

I've been given a homework assignment that asks to print an equilateral triangle with '*' as the frame and inside the triangle a string of fixed number of '$' and spaces is supposed to run.
example:
Enter height: 9
Enter number of $: 5
Enter number of spaces: 2
I am lost here, help?
Let's see over what logic it works. You will find code at last.
1st.
How to create left-side star pattern like this :
*
*
*
*
First thing is how many spaces on the left of each star is equal to TOTAL_HEIGHT_OF_PATTERN - CURRENT_HEIGHT_STATUS. for given example let's take 2nd-line so:
TOTAL_HEIGHT_OF_PATTERN = 4
CURRENT_HEIGHT_STATUS = 2
NUMBER_OF_SPACE_ON_LEFT = TOTAL_HEIGHT_OF_PATTERN - CURRENT_HEIGHT_STATUS = 2
2nd.
How to create `$` and `space` pattern like this in between: (BOTTOM PATTERN IS ONLY FOR VISUALIZATION)
*
*$*
*$$$*
* $$$*
*$$$$$ *
*$$$$$ $$*
*$$$$$ $ $*
*$$$ $$$$$$*
How many spaces at given height, for above system it is found.
spaces:0 for height # 1, 2, 3
spaces:1 for height # 4, 5, 6
spaces:2 for height # 7, 8
Instead of completely using loop let's divide them in procedural code. For making particular enclose-string we can use make_str function who logic revolves around the remaining number of $
CODE :
height = int(input('Height : '))
doller = int(input('Dollor : '))
spaces = int(input('Spaces : '))
def make_str(rem, len_str):
x = 0
s = ''
for _ in range(len_str):
if rem >0:
s += '$'
rem -= 1
else:
s += ' '
x += 1
if x == spaces:
x = 0
rem = 5
return (rem, s)
rem_dollor = doller
for i in range(1,height+1):
num = 2*(i)-3
rem_dollor, str_ = make_str(rem_dollor, num)
if i == 1:
print(' '*(height-i) + '*')
elif i != height and i != 1:
print(' '*(height-i) + '*' + str_ + '*')
else:
print('*'*(2*height-1))
OUTPUT :
Height : 9
Dollor : 5
Spaces : 2
*
*$*
*$$$*
*$ $$*
*$$$ $$*
*$$$ $$$$*
*$ $$$$$ $*
*$$$$ $$$$$ *
*****************

for and while loop using break,pass,continue.I don't know where I should go next [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am new to Python and Stackoverflow in general, so sorry if my formatting sucks and I'm not good at English. But I am stuck with this code.
test = True
a = True
total = 0
t = 0
while test:
n = int(input('Width (7-10): '))
if n<7 or n>10:
print('Invalid Number!')
total += 1
if n>=7 and n<=10:
break
while a:
c = int(input('Border (1-3): '))
if c<1 or c>3:
print('Invalid Number!')
t += 1
if c>=1 and c<=3:
break
This is the result.
Width (7-10): 5
Invalid Number!
Width (7-10): 10
Border (1-3): 0
Invalid Number!
Border (1-3): 2
And this is the result that I want.
Width (7-10): 5
Invalid Number!
Width (7-10): 10
Border (1-3): 0
Invalid Number!
Border (1-3): 2
**********
**********
** **
** **
** **
** **
** **
** **
**********
**********
I don't know how to make the square.
Firstly, you can simply write
while True:
Instead of
a = True
while a:
Secondly, you don't use total or t anywhere. You can delete them.
Thirdly, if x has to belong to [a, b], you can write
if a <= x <= b:
Fourthly, you can use else statement instead of negation of if. Also, when you have break in if statement, the code below won't be executed if statement is true (it will break), so you even don't have to use any else here.
The last part you can make by simple iteration in for loop and multiplying or adding strings (e.g. 5*'a' = 'aaaaa')
while True:
width = int(input('Width (7-10): '))
if 7 <= width <= 10:
break
print('Invalid Number!')
while True:
border = int(input('Border (1-3): '))
if 1 <= border <= 3:
break
print('Invalid Number!')
for _ in range(border):
print(width*'*')
for _ in range (width - 2*border):
print(border*'*' + (width-2*border)*' ' + border*'*')
for _ in range(border):
print(width*'*')
This can be achieved by the following code:
for i in range(n):
if i < c or i >= n-c:
print("*"*n)
else:
print("*"*c + " "*(n-(c*c)) + "*"*c)
This iterates through a for loop with the range being the width entered earlier (n in this case). By testing if you are at the first/last few iterations (as determined by the border, or c in this case), you can print the border. If not, you can print the necessary stars with the required spacing.
You print the required amount of stars by multiplying the string as necessary.
ok, i am totally lost, i don't know how u expect
**********
**********
** **
** **
** **
** **
** **
** **
**********
**********
that when u haven't written any code that will output that result, but what u could do is that before u break in the last while loop paste this
dummy = ''
for line in range(1, n + 1):
if line <= c or line > n - c:
dummy = ''.join(['*'] * n)
print(dummy)
dummy = ''
else:
dummy = ''.join(['*'] * c)
dummy = dummy + ''.join([' '] * (n - 2*c))
dummy = dummy + ''.join(['*'] * c)
print(dummy)
please respond if it helped i spent some time on this, and here is ur final code
a = True
total = 0
t = 0
while test:
n = int(input('Width (7-10): '))
if n<7 or n>10:
print('Invalid Number!')
total += 1
if n>=7 and n<=10:
break
while a:
c = int(input('Border (1-3): '))
if c<1 or c>3:
print('Invalid Number!')
t += 1
if c>=1 and c<=3:
for line in range(1, n + 1):
if line <= c or line > n - c:
dummy = ''.join(['*'] * n)
print(dummy)
dummy = ''
else:
dummy = ''.join(['*'] * c)
dummy = dummy + ''.join([' '] * (n - 2*c))
dummy = dummy + ''.join(['*'] * c)
print(dummy)
break

Creating a triangle of characters from a users input

For an assignment I'm suppose to make a triangle using the users input if the characters are equal to an even number. The triangle is suppose to print up to 5 lines in height and the left of it should be the left half of the string and the right side of the triangle should be the right side of the string.
Example of what the triangle is suppose to look like
The problem is I can't figure out how to divide my triangle in half without hard coding it or how to properly display the white space without a loop (were not allowed to in the assignment). Right now if I were to put in "ab" it would return:
aabb
aabbaabb
aabbaabbaabb
aabbaabbaabbaabb
aabbaabbaabbaabbaabb
Instead of:
aabb
aaaabbbb
aaaaaabbbbbb
aaaaaaaabbbbbbbb
aaaaaaaaaabbbbbbbbbb
Here's my code:
#GET Users String
userString = input("Please enter a string with a value of 7 or less characters: ")
#CALCULATE IF userString is less than or equal to 7 and is even
if len(userString) <= 7 and len(userString) % 2 == 0:
print (" " * 5 + userString)
print(" " * 4 + userString * 2)
print(" " * 3 + userString * 3)
print(" " * 2 + userString * 4)
print(" " + userString * 5)
#CALCULATE IF userString is less than 7 but and off
elif len(userString) <=7 and len(userString) % 2 == 1:
print("You are odd")
#CALCULATE IF userString is over 7 characters
else:
print ('The string is too long. \nGood-bye!')
Here's how you can do this:
def print_next(st, index):
if index < 6: # have not reached 5 - print offset and string
offset = 6-index
print ' '*offset+st
index=index+1 # increase counter
print_next((st[0:2]+st[-2:len(st)])*index,index) # recursively go next
print_next('aabb',1) # initial call with index set to 1
I think you can use a stack to save each line so you can easily get a triangle-like output. Also because you can't use loop so my suggestion would be recursive.
public_stack = []
def my_func(original_str, line_count, space_num):
if(line_count == 0):
return
times = line_count * 2
half_length = len(original_str) / 2
left_str = original_str[:half_length] * times
right_str = original_str[half_length:] * times
space_str = ' ' * space_num
complete_str = space_str + left_str + right_str
global public_stack
public_stack.append(complete_str)
space_num += len(original_str)
line_count -= 1
return my_func(original_str,line_count,space_num)
if __name__ == '__main__':
original_str = 'ab'
line_count = 5
space_num = 0
my_func(original_str,line_count,space_num)
global public_stack
for i in range(len(public_stack)):
line = public_stack.pop()
print line

HackerRank Staircase Python

I am trying to solve a problem in HackerRank and I am having an issue with my submission. My code works in PyCharm but HackerRank is not accepting my submission.
Here is the problem I am trying to solve: https://www.hackerrank.com/challenges/staircase
Here is my code:
def staircase(num_stairs):
n = num_stairs - 1
for stairs in range(num_stairs):
print ' ' * n, '#' * stairs
n -= 1
print '#' * num_stairs
staircase(12)
Any ideas why HackerRank is not accpeting my answer?
Your output is incorrect; you print an empty line before the stairs that should not be there. Your range() loop starts at 0, so you print n spaces and zero # characters on the first line.
Start your range() at 1, and n should start at num_stairs - 2 (as Multiple arguments to print() adds a space:
from __future__ import print_function
def staircase(num_stairs):
n = num_stairs - 2
for stairs in range(1, num_stairs):
print(' ' * n, '#' * stairs)
n -= 1
print('#' * num_stairs)
You can simplify this to one loop:
def staircase(num_stairs):
for stairs in range(1, num_stairs + 1):
print(' ' * (num_stairs - stairs) + '#' * stairs)
Note that I use concatenation now to combine spaces and # characters, so that in the last iteration of the loop zero spaces are printed and num_stairs # characters.
Last but not least, you could use the str.rjust() method (short for “right-justify”) to supply the spaces:
def staircase(num_stairs):
for stairs in range(1, num_stairs + 1):
print(('#' * stairs).rjust(num_stairs))
You can use rjust to justify the string to the right:
def staircase(n):
for i in range(1, n+1):
print(("#" * i).rjust(n))
Another solution
n = int(raw_input())
s = '#'
for i in xrange( 1 , n+1):
print " "*(n-i) + s*i
first, create a list, then print with join \n'
def staircase(n):
print("\n".join([' ' * (n-x) + '#' * x for x in range(1, n+1)]))
def staircase(n):
for i in range(0, n): # n rows
print(' '*(n-i-1) + '#'*(i+1)) # first print n-i-1 spaces followed by i '#'
n = int(input())
staircase(n)
its look like secondary diagonal
def staircase(n):
for i in range(n):
for j in range (n):
if i+j == n-1:
print(" "*j+"#"*(n-j))
output-
#
##
###
####
#####
######
for i in range(n):
result = ' '*(n-i-1) +('#')*(i+1)
print(result)
I was getting an error until I replaced the comma with a plus sign:
print(' ' * (n - i - 1) + '#' * (i + 1))
Understanding the problem is 80% of the solution. The requirement states the min/max total of stairs.
"""
Prints a staircase with a total number of stairs
Note: total number of stairs must be between 1 and 100 inclusive, as per requirements
"""
def staircase(n):
if n < 1 or n > 100:
print("Error: Total number of stairs must be between 1, 100 inclusive!")
else:
for x in range(1, n+1):
print(" " * (n - x) + "#" * x )
#-----------------------
staircase(0)
Error: Total number of stairs must be between 1, 100 inclusive!
staircase(101)
Error: Total number of stairs must be between 1, 100 inclusive!
staircase(4)
#
##
###
####
def staircase(n):
space = n-1
for i in range(n):
x = i + 1
print(" " * space + "#" * x)
space -= 1
one more solution:
def staircase(n):
for i in reversed(range(n)):
print(i*' '+(n-i)*'#')
You can just change the sep argument of print from ' ' to '', and your answer will be correct
def staircase(n):
for i in range(1, n+1):
print(' ' * (n-i), '#' * (i), sep='')
The answer you submitted is not accepted because the default print settings adds an empty space in front of the printouts, and one of the question requirements is for there to have no spaces in the output.
The default sep in print is a space character i.e. ' '.
This might not be the cleanest way to write the code, but it works:
print('\n'.join(' ' * (n - i) + '#' * i for i in range(1, n + 1)))
Another Answer
H = int(input())
for i in range(1,H+1):
H = H - 1
print(' '*(H) + ('#'*(i)))
you can simply use while loop also.
import sys
n1=int(raw_input())-1
n2=1
while n1>=0:
print " "*n1,"#"*n2
n1=n1-1
n2=n2+1
def staircase(n):
for in range(i,n+1):
print str("#"*i).rjust(n)

Categories