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
Related
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
*
*$*
*$$$*
*$ $$*
*$$$ $$*
*$$$ $$$$*
*$ $$$$$ $*
*$$$$ $$$$$ *
*****************
I am writing a program that calculates the factorial of a number, I am able to display the correct answer, however along with the answer I need the actual calculation to display, I am having trouble with that. So for example, when the user enters 4, I need it to display as:
I have been trying to figure out the right code, but do not know what to do.
Here is the code I have so far
number = int(input("Enter a number to take the factorial of: "))
factorial = 1
for i in range(1, number + 1):
factorial = factorial * i
print (factorial)
Right now, it displays the correct answer, however I need for it to include the equation as well as follows: 4! = 1 x 2 x 3 x 4 = 24
The simplest approach is to construct the string as you are iterating:
equation = str(number) + "! = "
factorial = 1
for i in range(1, number + 1):
factorial = factorial * i
equation += str(i) + "x"
equation = equation[:-1] + " = " + str(factorial)
print(equation)
Note that this method appends an unwanted 'x' after the last factor. This is removed by equation[:-1].
Alternatively, you could append this one-line solution to the end of your code. It uses the join method of the string class to concatenate an array of strings:
print(str(number) + "! = " + "x".join(str(n) for n in range(1, number + 1)) + " = " + str(factorial))
As you loop through the numbers to be multiplied, you can append each number's character to a string containing the equation, e.g ans, and print it at last. At the end of the code, I omitted the last letter because I didn't want an extra 'x' to be displayed.
def fact(number):
num_string=str(number)
factorial = 1
ans=num_string+"!="
for i in range(1, number + 1):
factorial = factorial * i
ans+=str(i)+"x"
ans=ans[:-1]
print(ans)
return factorial
fact(4)
You can append each value to the list and then print the equation using the f-string:
num = 5
l = []
f = 1
for i in range(1, num + 1):
f *= i
l.append(i)
print(f"{num}! = {' x '.join(map(str, l))} = {f}")
# 5! = 1 x 2 x 3 x 4 x 5 = 120
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])
Write a function called random_equation that takes as input a single parameter, the number of operators to generate in the random equation, and returns a string representing a random math equation involving the numbers 1-10 and operators +, -, *.
def random_equation(num):
result = ""
for i in range (num):
number = random.randint(1, 10)
if number == 1:
num_gen = (" 1 ")
elif number == 2:
num_gen = (" 2 ")
elif number == 3:
num_gen = (" 3 ")
elif number == 4:
num_gen = (" 4 ")
elif number == 5:
num_gen = (" 5 ")
elif number == 6:
num_gen = (" 6 ")
elif number == 7:
num_gen = (" 7 ")
elif number == 8:
num_gen = (" 8 ")
elif number == 9:
num_gen = (" 9 ")
else:
num_gen = (" 10 ")
operator = random.randint(1,4)
if operator == 1:
op_gen = (" + ")
elif operator == 2:
op_gen = (" - ")
else:
op_gen = (" * ")
math = result + num_gen + op_gen
I don't really know where to put the [i] to get it to repeat the loop since number is an integer and num_gen is the result
There are several issues here.
Your math gets replaced every time (e.g. "" + " 2 " + " - "), thus you never get to build longer sequences. You want to make result longer in each iteration: result = result + num_gen + op_gen, instead of always creating a new math with an empty result.
You never return anything. You will want to return result when the loop is finished.
You are now generating num numbers and num operators; that will produce equations like 1 + 3 *, which are a bit unbalanced. You will want to put only num - 1 pairs, and then one more number.
There are easier ways to make a string out of a number; str(num) will do what you do in twenty lines, just without the spaces.
With operator from 1 to 4, you will be generating as many * as you do + and - combined. Intentional?
import random
question = str(random.randint(-10,100)) + random.choice(op) + str(random.randint(-10,100)) + random.choice(op) + str(random.randint(-10,100))
q_formatted = question.replace('÷','/').replace('×', '*')
answer = eval(q_formatted)
print(answer)
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)