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
Related
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.
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 going through a past test and the output of the code is this:
Enter the height:
5
5
44
333
2222
11111
I have to write down the code - so far I know how to make a normal triangle with:
for i in range(5):
print('*'*i)
*
**
***
****
My main question is how do I get the body if the triangle to iterate over the numbers?
So what would the code of the first triangle be?
Help would be appreciated:)
The code for this is virtually the same, you just need to change the number of times you print each character, and change the * that you are printing to a number.
for i in range(5):
print(str(5-i) * (i+1))
This generates:
5
44
333
2222
11111
To make it right aligned, like in your example, just use string multiplication on a space character.
for i in range(5):
print(' ' * (4-i) + str(5-i) * (i+1))
This will get you:
5
44
333
2222
11111
You can use str:
for i in range(5):
print(str(i)*i)
Some of the other answers have been essentially correct, but this one right justifies your triangle like the original output.
def print_triangle(rows):
for i in range(rows + 1):
print((str(rows + 1-i)*i).rjust(rows))
height = 5
for i in range(height, 0, -1):
empty_chars = ' ' * (i - 1)
filler_chars = str(i) * (height - i + 1)
print('{}{}'.format(empty_chars, filler_chars))
Formatted string & spacing with an external array and a negated variable.
def height(num):
rangenum=range(num+1)
for i in rangenum:
print(("%"+str(num)+"s")%(i*str(rangenum[-i])))
print("%(spacing as a number)s"%(a string))
returns
(spacing as a number)-(a string)
example:
print("%10s"%"this")
returns:
" this"
side note:
%-(a number)s
is right justified.
(though python tries to cut down the millions of ways to do the same thing, there still are thousands)
https://docs.python.org/2/tutorial/inputoutput.html
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I want to know what is the biggest number you can make from multiplying digits entered by the user like this:
5*6*7*2 OR 567*2 OR 67*25 ...etc
so 5/6/7/2 should be entered by the user as variables, but how do I tell python to form a number from two variables (putting the two digits next to each other and treating the outcome as a number by itself).
how do I tell python to form a number from two variables (putting the two digits next to each other and treating the outcome as a number by itself)
Provided the two digits are stored in integer variables, the following will do it:
In [1]: v1 = 5
In [2]: v2 = 6
In [3]: v1 * 10 + v2
Out[3]: 56
This can be generalized to a sequence of digits:
In [7]: l = (1, 2, 6, 3)
In [8]: reduce(lambda x,y: x * 10 + y, l)
Out[8]: 1263
I feel you have posted a mistake in your question. You ask for permutations? Are you sure?
If so, see #mbeckish's answer. It's pretty simple, and not a very good exercise in programming.
(it is, however, a good exercise in trick questions with riddle-like "gotchas" for solutions)
A better approach is to ditch the permutations requirement, so that the order of the input can actually affect the answer. For that approach, we get a much more interesting solution:
def largest_product(*args):
numbers = ''.join(map(str, args))
results = []
for i in range(1, len(numbers) - 1):
multicand = int(numbers[:i])
multiplier = int(numbers[i:])
m, n = multicand, multiplier
results.append(( m * n, "%s * %s" % (m, n)))
return max(results)
>>> largest_product(*range(8))
(827115, '12345 * 67')
so 5/6/7/2 should be entered by the user as variables, but how do I tell python to form a number from two variables (putting the two digits next to each other and treating the outcome as a number by itself).
Seems the root of your problem is capturing data from the user, combining it, and converting it:
>>> a = raw_input()
8
>>> b = raw_input()
3
>>> a
'8'
>>> b
'3'
>>> a + b
'83'
>>> int(a+b)
83
It's that easy.
Now as far as biggest number you can make from multiplying digits entered goes... we can prove that with math if you'd like so you don't have a pile of combinations to try:
We can sort the digits a >= b >= c >= d
First let's look at splitting the digits 3 and 1. We need to compare a * bcd, b * acd, c * abd, d * abc.
Comparing a * bcd = 100ab + 10ac + ad with b * acd = 100ab + 10bc + bd we see the former is larger because a >= b. A similar argument will show that a * bcd beats the others.
Similarly we can compare ac * bd = 100ab + 10(ad+bc) + bd with ad * bc = 100ab + 10(ac+bd) + cd. We would rather have more copies of the big a, so the second wins.
Finally we need to compare a * bcd = 100ab + 10ac + ad with ad * bc = 100ab + 10(ac+bd) + cd. The second is the winner.
You probably took the input in a loop as an array, so if you have:
(a) arr[0] = '5' arr[0] = '7'
(b) arr[1] = '6' sort em => arr[1] = '6'
(c) arr[2] = '7' arr[2] = '5'
(d) arr[3] = '2' arr[3] = '2'
The largest would be:
int(arr[0] + arr[3]) * int(arr[1] + arr[2]) = 4680
Any solution that has you trying all permutations of digits will be horribly inefficient, running in O(n!). Just 14 digits (and the multiply operator) would give around 1 trillion combinations!
An O(n lg n) solution would be:
Sort the digits from high to low.
Concatenate them into one string.
Print the string.
If you must multiply at least one digit, then
Sort.
Take the highest digit and multiply by the concatenation of the remaining digits.
Print the result.
If you must multiply at least one digit, then you might need to try all permutations (see #Mike's answer).
I assume you get the numbers as string, so you can simply strip them, join and translate to int:
string = "5*6*7*2"
value = int( "".join(string.split('*')) )
# value == 5672
I get this error when using a python script that calculates pi using the Gauss-Legendre algorithm. You can only use up to 1024 iterations before getting this:
C:\Users\myUsernameHere>python Desktop/piWriter.py
End iteration: 1025
Traceback (most recent call last):
File "Desktop/piWriter.py", line 15, in <module>
vars()['t' + str(sub)] = vars()['t' + str(i)] - vars()['p' + str(i)] * math.
pow((vars()['a' + str(i)] - vars()['a' + str(sub)]), 2)
OverflowError: long int too large to convert to float
Here is my code:
import math
a0 = 1
b0 = 1/math.sqrt(2)
t0 = .25
p0 = 1
finalIter = input('End iteration: ')
finalIter = int(finalIter)
for i in range(0, finalIter):
sub = i + 1
vars()['a' + str(sub)] = (vars()['a' + str(i)] + vars()['b' + str(i)])/ 2
vars()['b' + str(sub)] = math.sqrt((vars()['a' + str(i)] * vars()['b' + str(i)]))
vars()['t' + str(sub)] = vars()['t' + str(i)] - vars()['p' + str(i)] * math.pow((vars()['a' + str(i)] - vars()['a' + str(sub)]), 2)
vars()['p' + str(sub)] = 2 * vars()['p' + str(i)]
n = i
pi = math.pow((vars()['a' + str(n)] + vars()['b' + str(n)]), 2) / (4 * vars()['t' + str(n)])
print(pi)
Ideally, I want to be able to plug in a very large number as the iteration value and come back a while later to see the result.
Any help appreciated!
Thanks!
Floats can only represent numbers up to sys.float_info.max, or 1.7976931348623157e+308. Once you have an int with more than 308 digits (or so), you are stuck. Your iteration fails when p1024 has 309 digits:
179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216L
You'll have to find a different algorithm for pi, one that doesn't require such large values.
Actually, you'll have to be careful with floats all around, since they are only approximations. If you modify your program to print the successive approximations of pi, it looks like this:
2.914213562373094923430016933707520365715026855468750000000000
3.140579250522168575088244324433617293834686279296875000000000
3.141592646213542838751209274050779640674591064453125000000000
3.141592653589794004176383168669417500495910644531250000000000
3.141592653589794004176383168669417500495910644531250000000000
3.141592653589794004176383168669417500495910644531250000000000
3.141592653589794004176383168669417500495910644531250000000000
In other words, after only 4 iterations, your approximation has stopped getting better. This is due to inaccuracies in the floats you are using, perhaps starting with 1/math.sqrt(2). Computing many digits of pi requires a very careful understanding of the numeric representation.
As noted in previous answer, the float type has an upper bound on number size. In typical implementations, sys.float_info.max is 1.7976931348623157e+308, which reflects the use of 10 bits plus sign for the exponent field in a 64-bit floating point number. (Note that 1024*math.log(2)/math.log(10) is about 308.2547155599.)
You can add another half dozen decades to the exponent size by using the Decimal number type. Here is an example (snipped from an ipython interpreter session):
In [48]: import decimal, math
In [49]: g=decimal.Decimal('1e12345')
In [50]: g.sqrt()
Out[50]: Decimal('3.162277660168379331998893544E+6172')
In [51]: math.sqrt(g)
Out[51]: inf
This illustrates that decimal's sqrt() function performs correctly with larger numbers than does math.sqrt().
As noted above, getting lots of digits is going to be tricky, but looking at all those vars hurts my eyes. So here's a version of your code after (1) replacing your use of vars with dictionaries, and (2) using ** instead of the math functions:
a, b, t, p = {}, {}, {}, {}
a[0] = 1
b[0] = 2**-0.5
t[0] = 0.25
p[0] = 1
finalIter = 4
for i in range(finalIter):
sub = i + 1
a[sub] = (a[i] + b[i]) / 2
b[sub] = (a[i] * b[i])**0.5
t[sub] = t[i] - p[i] * (a[i] - a[sub])**2
p[sub] = 2 * p[i]
n = i
pi_approx = (a[n] + b[n])**2 / (4 * t[n])
Instead of playing games with vars, I've used dictionaries to store the values (the link there is to the official Python tutorial) which makes your code much more readable. You can probably even see an optimization or two now.
As noted in the comments, you really don't need to store all the values, only the last, but I think it's more important that you see how to do things without dynamically creating variables. Instead of a dict, you could also have simply appended the values to a list, but lists are always zero-indexed and you can't easily "skip ahead" and set values at arbitrary indices. That can occasionally be confusing when working with algorithms, so let's start simple.
Anyway, the above gives me
>>> print(pi_approx)
3.141592653589794
>>> print(pi_approx-math.pi)
8.881784197001252e-16
A simple solution is to install and use the arbitrary-precisionmpmath module which now supports Python 3. However, since I completely agree with DSM that your use ofvars()to create variables on the fly is an undesirable way to implement the algorithm, I've based my answer on his rewrite of your code and [trivially] modified it to make use ofmpmath to do the calculations.
If you insist on usingvars(), you could probably do something similar -- although I suspect it might be more difficult and the result would definitely harder to read, understand, and modify.
from mpmath import mpf # arbitrary-precision float type
a, b, t, p = {}, {}, {}, {}
a[0] = mpf(1)
b[0] = mpf(2**-0.5)
t[0] = mpf(0.25)
p[0] = mpf(1)
finalIter = 10000
for i in range(finalIter):
sub = i + 1
a[sub] = (a[i] + b[i]) / 2
b[sub] = (a[i] * b[i])**0.5
t[sub] = t[i] - p[i] * (a[i] - a[sub])**2
p[sub] = 2 * p[i]
n = i
pi_approx = (a[n] + b[n])**2 / (4 * t[n])
print(pi_approx) # 3.14159265358979