i'm working on this challenge, wherein based on a number given it will show the asterisk (*) increment per odd number. Basically the result should be if I run the function below and set the n_floor to 5 it should show the result below. My code somehow iterates per number of floor and increments the * per odd number but the result fails but this is because the spacing of the asterisk between those quotes are wrong. Any idea/tip how to fix this?
a. Correct Result
[' * ', ' *** ', ' ***** ', ' ******* ', '*********']
b. REsult from my script below:
['*', '***', '*****', '*******', '*********']
def tower_builder(n_floor):
a = '*'
b = 1
c= 0
result = []
num=range(1, n_floor+1)
# * to increment by odd number
for x in num:
c = a
result.append(c)
a += str('**')
return result
Here's a better way which calculates the width you need:
def tower_builder(n_floor):
result = []
width = (n_floor * 2) - 1
for x in range(1, 2 * n_floor, 2):
stars = x * '*'
line = stars.center(width)
result.append(line)
return result
assert tower_builder(1) == ['*']
assert tower_builder(2) == [' * ', '***']
assert tower_builder(3) == [' * ', ' *** ', '*****']
assert tower_builder(4) == [' * ', ' *** ', ' ***** ', '*******']
assert tower_builder(5) == [' * ', ' *** ', ' ***** ', ' ******* ', '*********']
Here is a one-liner function:
def tower_builder(n):
return [('*' * i).center(n * 2 - 1) for i in range(1, 2 * n + 1, 2)]
Because each row of the tower is formed of an odd number of *, we need to loop oddly, Thus we set the loop max to the 2 * n with step of 2 to ensure that we are looping through odds.
Then we use center function to give the tower the final Pyramidal shape.
Like the comments say, you will want to use str.center.
For a concrete example, it would also point out that every "floor" has an odd number of characters, so you can actually simplify your function a bit.
def tower_builder(n_floor):
window = '☐'
total_width = 20 # this may get bigger if you have a very tall building
floor_strings = []
for floor_idx in range(n_floor):
# because widths are always odd
width = 2 * floor_idx + 1
# construct this floor
floor_string = (window*width).center(total_width)
# add it to the list
floor_strings.append(floor_string)
# join them all together with newlines
return '\n'.join(floor_strings)
print(tower_builder(5))
☐
☐☐☐
☐☐☐☐☐
☐☐☐☐☐☐☐
☐☐☐☐☐☐☐☐☐
As a side note, you can actually calculate what total_width must be by starting with the widest floor (or calculating it, which isn't terribly hard) and using that as total_width.
Related
Hope to find some help here with a new excercise.
I luckily understand how to use recursive functions, but this one is killing me, im probably just thinking too much outside of the box.
We're given a string:
c = "3+4*5+6+1*3"
And now we have to code a function, which recursivly gives us the result of that calculation.
Now i know the recursive end should be the length of the string, which should be 1.
Our professor did give us another example which we should use for this function.
int(number)
string.split(symbol, 1)
we have following code given:
c = "3+4*5+6+1*3"
print(c)
print()
sub1, sub2 = c.split("+", 1)
print("Result with '+':")
print("sub1=" + sub1)
print("sub2=" + sub2)
print()
sub1, sub2 = c.split("*", 1)
print("Result with '*':")
print("sub1=" + sub1)
print("sub2=" + sub2)
print()
My thoughts were to split the strings to a minimum, so i can turn them into integers and than sum them together. But im absolutly lost there how the code should look like, im a real beginner so im really sorry. I dont even know it the beginning i was thinking of is right. Still hoping, someone can help!
what i had:
def calc(string):
if len(string) == 1:
return string
Thanks for all of you!
Greets
Chrissi
I created a function that solves equations like these. However, the only characters possible are numbers, and operators add (+) and mult (*). If you try to use any other characters such as spaces, there's going to be errors.
# Solves a mathematical equation containing digits [0-9], and operators
# such as add + or multiply *
def solve(equation, operators, oindex=0):
# If an operator is available, use the operator
if (oindex < len(operators)):
# Get the current operator and pair: a op b
op = operators[oindex]
pair = equation.split(op, 1)
# If the pair is a pair (has 2 elements)
if (len(pair) == 2):
# Solve left side
a = solve(pair[0], operators)
# Solve right side
b = solve(pair[1], operators)
# If current operator is multiply: multiply a and b
if (op == '*'):
print(a, '*', b, '=', a*b)
return a * b
# If current operator is add: add a and b
elif (op == '+'):
print(a, '+', b, '=', a+b)
return a + b
# If it's not a pair, try using another operator
else:
return solve(equation, operators, oindex+1)
else:
# If no operators are available, then equation is
# just a number.
return int(equation)
if __name__ == '__main__':
equation = "3+4*5+6+1*3"
# If mult (*) takes precedence, operator order is "+*"
# > 3+4*5+6+1*3 = ((3)+((4*5)+((6)+(1*3))))
# = ((3)+((20)+((6)+(3))))
# = ((3)+(20+(9)))
# = ((3)+(29))
# = (32)
print("MULT, then ADD -> ",equation + " = ", solve(equation, "+*"))
# If add (+) takes precedence, operator order is "*+"
# > 3+4*5+6+1*3 = ((3+4)*(((5)+(6+1))*(3)))
# = ((7)*((5+7)*(3)))
# = ((7)*(12*3))
# = (7*36)
# = (252)
print("ADD, then MULT -> ",equation + " = ", solve(equation, "*+"))
To set the operators, you can use the paramter operators, which is a string that takes all supported operators. In this case: +*.
The order of these characters matter, changing the precedence of each operator inside the equation.
Here's the output:
4 * 5 = 20
1 * 3 = 3
6 + 3 = 9
20 + 9 = 29
3 + 29 = 32
MULT, then ADD -> 3+4*5+6+1*3 = 32
3 + 4 = 7
6 + 1 = 7
5 + 7 = 12
12 * 3 = 36
7 * 36 = 252
ADD, then MULT -> 3+4*5+6+1*3 = 252
Given a odd positive integer h, greater than or equal to 5, create a bowtie pattern with h rows and 2h columns.
input: 5
output:
* *
*** ***
**********
*** ***
* *
or
input: 7
output:
* *
*** ***
***** *****
**************
***** *****
*** ***
* *
I created code that only works for one given value of h but I'm not sure how to make it functional for any value of h. I also tried taking advantage of the symmetry so I made only half of the bowtie.
h = input()
n = int(h)
x = "*"
space = " "
print(x)
print(-(-n // 2)*x)
print(n*x)
print(-(-n // 2)*x)
print(x)
You can build up the top half by left and right justifying the * repeated as many times as necessary (we use range with a step for this as the first row will have 1 *, the next 2 more, the next 2 more again up until we reach N) padded left and right with width n, eg:
n = int(input())
top = [('*' * i).ljust(n) + ('*' * i).rjust(n) for i in range(1, n, 2)]
This gives you a top (for n=5) of:
['* *', '*** ***']
Then, we print the top, the middle (which is always * repeated N*2 times) and then top in reverse order for the bottom separated by newlines, eg:
print(*top, '*' * n * 2, *reversed(top), sep='\n')
Gives you (n=5):
* *
*** ***
**********
*** ***
* *
Or for (n=11):
* *
*** ***
***** *****
******* *******
********* *********
**********************
********* *********
******* *******
***** *****
*** ***
* *
Symmetry tells you that the left and the right have the same number of *. It also tells you that the middle row is all stars (n * 2), and that each row the same distance above and below the middle row has the same size. Further, as you move away from the center, you lose 4 stars total, 2 from each side.
The two secrets to coding this concise are to 1) number the rows symmetrical, not from 1 to n, but from -n//2 to n//2; and 2) to think of the rows as a number of spaces drawn on a background of *s, rather than a number of *s surrounding spaces.
Once you figure out how many spaces are in each row (call it f(i), based on the value of i in for i in range(-n//2, n//2+1): ..., you can draw that row with (" "*f(i)).center(2*n, "*").
it will work for any odd number
h = input()
n = int(h)
i = 1
if(n%2)!=0 and n > 4:
halfmark= n//2
str=""
while i <= n:
if(i<=halfmark):
blank = ' '* (4*(halfmark +1-i))
elif i > (halfmark+1):
blank = ' '*(4*(i-(halfmark+1)))
else:
blank = ''
star = '*'*((2*n-len(blank))//2)
str = star+blank+star
print(str)
i +=1
I want to print out a list of the character '&' as many times as there are in a given number. So if the number is 10, I want the result to be '&&&&&&&&&&&'
What I have done is turned the int into a list so I can better visualize what I want to perform.
def print_list_&(size):
"""super serious docstring"""
result_1 = 1
result_2 = size + 1
result = list(range(result_1, result_2))
return result
I'm stuck on where I go from here. This is university work so I'm better off with a push in the right direction than a straight answer.
'&' * 10 will give you '&&&&&&&&&&'. Therefore it seems you just need '&' * size.
Python 2:
N = int(raw_input())
print '&' * N
Python 3:
N = int(input())
print ('&' * N)
I am trying to make a code that draws a bow tie with a given input.
A bow tie:
* *
*** ***
**********
*** ***
* *
I am working on 2 methods here. Can anyone tell me if I am on the correct path? I seem to be lost...
num = int(input("Enter an odd number greater than 4: "))
row = 1
row_space = row*2-1
space_tot = num*2 - row_space*2
stars = int((num*2 - space_tot)/2)
space = ""
for x in range(num):
print("*"*stars+" "*space_tot+"*"*stars)
row += 1
space_tot -= 2
def triangle(n):
for x in range(n,0,2):
print ('*'*x)
for x in range(n,0,-2):
print ('*'*x)
n -= 1
triangle(num)
num = int(input("Enter an odd number greater than 4: "))
center = (num - 1)//2
for row in range(num):
nspaces = 2*abs(row - center)
nstars = num - nspaces
print nstars*'*' + 2*nspaces*' ' + nstars*'*'
How it works
Let's look at the desired output (with row numbers added) for the case num=5:
0 * *
1 *** ***
2 **********
3 *** ***
4 * *
Let us think about this as a left half and a right half. Observe each half has num stars in the center row. The number of spaces in the center row is zero. The number of spaces in each half increases by two for each row that we move away from the center. Expressed mathematically:
nspaces = 2*abs(row - center)
Each half is num columns wide. So, if a half has nspaces spaces, then the number of stars in that half is:
nstars = num - nspaces
Having computed both of those, it is only a matter of printing it all out:
print nstars*'*' + 2*nspaces*' ' + nstars*'*'
This is done once for each row.
When you are learning Python, it is good to look through its library functions. In Python, everything is an object. And every object has methods. Here is a link to everything you need to know about strings in Python.
https://docs.python.org/2/library/string.html
You'll get a number of functions here which directly relate to your problem. The more familier you are with the objects in Python, the better you become in programming in Python. This is true for any language. If you want to become better at a particular language, learn its specifics.
For your problem, you can learn about the methods ljust(), rjust() and join(). How do you use them?
In [126]: '[' + 'abcd'.ljust(10) + ']'
Out[126]: '[abcd ]'
In [127]: '[' + 'abcd'.rjust(10) + ']'
Out[127]: '[ abcd]'
In [134]: '-][-'.join(['A', 'list', 'of', 'strings'])
Out[134]: 'A-][-list-][-of-][-strings'
Of course, you can replace the 'abcd' with '*'s. In this case, you have,
In [129]: ('*'*3).ljust(5) + ('*'*3).rjust(5)
Out[129]: '*** ***'
Now, you just replace the 3 with a counter for your choice. Note that your numbers increments in 2s. Before you do that, I hope you know about list comprehension. If not, you can just learn about it here:
https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions
In [132]: [('*'*i).ljust(5) + ('*'*i).rjust(n) for i in range(1, n+2, 2)]
Out[132]: ['* *', '*** ***', '**********']
Let us now save this in a variable, and join them together ...
In [135]: l = [('*'*i).ljust(5) + ('*'*i).rjust(n) for i in range(1, n+2, 2)]
In [137]: print '\n'.join(l)
* *
*** ***
**********
Of course, you need the other half as well. For that you will need to use nearly all of the list you created above as l. Notice:
In [138]: l # Original list
Out[138]: ['* *', '*** ***', '**********']
In [139]: l[:-1] # Original list - the last value in the list
Out[139]: ['* *', '*** ***']
In [140]: l[:-1][::-1] # reverse that one
Out[140]: ['*** ***', '* *']
In [141]: l + l[:-1][::-1] # join the reversed list to the original list
Out[141]: ['* *', '*** ***', '**********', '*** ***', '* *']
Finally, we can join the two lists and form the bwotie:
In [143]: print '\n'.join(l + l[:-1][::-1])
* *
*** ***
**********
*** ***
* *
So in summary, you need 3 lines to print a bowtie:
n = 5 # Or a user input here ...
l = [('*'*i).ljust(5) + ('*'*i).rjust(n) for i in range(1, n+2, 2)]
print '\n'.join(l + l[:-1][::-1])
Hopefully, you see that it pays to go through the documentation in Python. You will be able to get a lot of useful methods, which can make coding very easy. The more familier you are with Python libraries, the better your coding. Most of these libraries are fine-tuned for a particular system, so it will be difficult to beat their effeciency as well. So you get twice the advantage, for the same amount of effort :).
Good luck with your programming.
def triangle(n):
for x in range(n,0,2):
print ('*'*x)
for x in range(n,0,-2):
print ('*'*x)
n -= 1
Here is my code but I'm having trouble getting the pyramid to be spaced correctly like a pyramid and also to only have odd number of asterisks per line.
Output when you enter 7 for the base should be
*
***
*****
*******
This is my code:
base = int(input( 'enter an odd number for the base : ' ) )
for i in range( 0, base ):
print '*' * i
You could use str.center():
for i in range(1, base + 1, 2):
print ('*' * i).center(base)
but do use a step size of 2, and adjust your range. The first line starts with 1 star always, and range() doesn't include the last value.
For 7, that means you want to print 1, 3, 5 and 7 stars, incrementing by 2 each iteration.
There are some errors in your code:
since you're using print '...' instead of function print, you may be in python2, where raw_input is needed instead of input;
range(1, base+1, 2) is needed instead, for your sample output.
Demo:
In [6]: base = int(raw_input( 'enter an odd number for the base : ' ) )
...: for i in range(1, base+1, 2):
...: print ('*' * i).center(base)
enter an odd number for the base : 7
*
***
*****
*******