how to print string inside pyramid python - 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
*
*$*
*$$$*
*$ $$*
*$$$ $$*
*$$$ $$$$*
*$ $$$$$ $*
*$$$$ $$$$$ *
*****************

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 do I print 2 variable alternatively n number of time

I got my homework problem. I need to input 2 variables and print them out alternatively n number of times without using if-else or loop statement.
a = input() #character
b = input() #character
n = input("n ")
I want to print out string of "ababa"
e.g.
a = "#"
b = "%"
n = 5
Expected output: #%#%#
or
n = 4
Expected output: #%#%
Since you have shown some effort in your comments I will give an answer. This uses the // integer division and % modulus operators. Note that I had to convert the value of n to an integer.
a = input("a? ") # character
b = input("b? ") # character
n = int(input("n? "))
print((a + b) * (n // 2) + a * (n % 2))

Nested Triangle in Python

My assingment
At each level the complete triangle for the previous level is placed into an extra outer triangle. The user should be asked to input the two characters to be used and the width of the innermost triangle, which must be odd. In addition to the test for negative input the function should test whether the supplied number is odd and display an appropriate message if it is not.
I need to print 3 triangles but every one of them includes other. It needs to get printed with two different character(like *-) and the user have to specify the length of innermost triangle and which has to be an odd number. Example,
Example output for 5 value
Ok, let me explain my way,
Every triangle should be in dictionary.
tri1 = {1:"*****", 2:"***", 3:"*"}
tri2 = {1:"..........", ...}
And couldn't find how I can deal with user input?
If enter 5,
length - 5 unit, height 3 unit
length - 11 unit, height 6 unit
length - 23 unit, height 12 unit.
How can i know? What is the logic?
Ok lets say if I did. I understand I should put a tringle in another triangle with nested loop, can simply iterate it another dictionary but, I need to check second character's position.
Thanks in advance.
My code,
ch1, ch2 = input("Please enter the characters you want to use: ")
num = int(input("Please specify the length of innermost triangle(only odd number): "))
if (num % 2 == 0) or (num < 3):
print("Number can not be even, less then 3 and negative")
num2 = (2 * num) + 1
num3 = (2 * num2) +1
tri1 = {}
tri2 = {}
tri3 = {}
for i in range(3):
tri1[i] = ch1*num
num -= 2
check = 1
cont = 0
var = 1
for ii in range(6):
tri2[ii] = ch2*check
check += 2
if (ii >= 3):
tri2[ii] = ch2*var + tri1[cont] + ch2*var
cont += 1
var += 2
for i in tri1:
print('{:^5}'.format(tri1[i]))
for i in tri2:
print('{:^11}'.format(tri2[i]))
The dictionary can be created using a simple function:
def create_tri_dict(tri_chars, tri_height):
level_str = {0:tri_chars[0]}
for i in range(1,tri_height):
level_length = i *2 +1
tri_char = tri_chars[i%2]
level_str[i] = level_str[i-1] + '\n' + tri_char * level_length
return level_str
Then the main logic of your program could be:
tri_chars = input('Input triangle characters: ')
tri_length = int(input('Input triangle base length: '))
tri_height = (tri_length + 1)//2
if tri_length %2 == 0:
raise Exception('Triangle base length not odd')
tri_dict = create_tri_dict(tri_chars, tri_length)
Then to print the final 3(?) triangles:
print(tri_dict[tri_height-2])
print(tri_dict[tri_height-1])
print(tri_dict[tri_height])

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

Asterisks Triangle in 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)

Categories