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
*
***
*****
*******
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 get the length of a string including a part of the string that represents its own length without padding or using structs or anything like that that forces fixed lengths.
So for example I want to be able to take this string as input:
"A string|"
And return this:
"A string|11"
On the basis of the OP tolerating such an approach (and to provide an implementation technique for the eventual python answer), here's a solution in Java.
final String s = "A String|";
int n = s.length(); // `length()` returns the length of the string.
String t; // the result
do {
t = s + n; // append the stringified n to the original string
if (n == t.length()){
return t; // string length no longer changing; we're good.
}
n = t.length(); // n must hold the total length
} while (true); // round again
The problem of, course, is that in appending n, the string length changes. But luckily, the length only ever increases or stays the same. So it will converge very quickly: due to the logarithmic nature of the length of n. In this particular case, the attempted values of n are 9, 10, and 11. And that's a pernicious case.
A simple solution is :
def addlength(string):
n1=len(string)
n2=len(str(n1))+n1
n2 += len(str(n2))-len(str(n1)) # a carry can arise
return string+str(n2)
Since a possible carry will increase the length by at most one unit.
Examples :
In [2]: addlength('a'*8)
Out[2]: 'aaaaaaaa9'
In [3]: addlength('a'*9)
Out[3]: 'aaaaaaaaa11'
In [4]: addlength('a'*99)
Out[4]: 'aaaaa...aaa102'
In [5]: addlength('a'*999)
Out[5]: 'aaaa...aaa1003'
Here is a simple python port of Bathsheba's answer :
def str_len(s):
n = len(s)
t = ''
while True:
t = s + str(n)
if n == len(t):
return t
n = len(t)
This is a much more clever and simple way than anything I was thinking of trying!
Suppose you had s = 'abcdefgh|, On the first pass through, t = 'abcdefgh|9
Since n != len(t) ( which is now 10 ) it goes through again : t = 'abcdefgh|' + str(n) and str(n)='10' so you have abcdefgh|10 which is still not quite right! Now n=len(t) which is finally n=11 you get it right then. Pretty clever solution!
It is a tricky one, but I think I've figured it out.
Done in a hurry in Python 2.7, please fully test - this should handle strings up to 998 characters:
import sys
orig = sys.argv[1]
origLen = len(orig)
if (origLen >= 98):
extra = str(origLen + 3)
elif (origLen >= 8):
extra = str(origLen + 2)
else:
extra = str(origLen + 1)
final = orig + extra
print final
Results of very brief testing
C:\Users\PH\Desktop>python test.py "tiny|"
tiny|6
C:\Users\PH\Desktop>python test.py "myString|"
myString|11
C:\Users\PH\Desktop>python test.py "myStringWith98Characters.........................................................................|"
myStringWith98Characters.........................................................................|101
Just find the length of the string. Then iterate through each value of the number of digits the length of the resulting string can possibly have. While iterating, check if the sum of the number of digits to be appended and the initial string length is equal to the length of the resulting string.
def get_length(s):
s = s + "|"
result = ""
len_s = len(s)
i = 1
while True:
candidate = len_s + i
if len(str(candidate)) == i:
result = s + str(len_s + i)
break
i += 1
This code gives the result.
I used a few var, but at the end it shows the output you want:
def len_s(s):
s = s + '|'
b = len(s)
z = s + str(b)
length = len(z)
new_s = s + str(length)
new_len = len(new_s)
return s + str(new_len)
s = "A string"
print len_s(s)
Here's a direct equation for this (so it's not necessary to construct the string). If s is the string, then the length of the string including the length of the appended length will be:
L1 = len(s) + 1 + int(log10(len(s) + 1 + int(log10(len(s)))))
The idea here is that a direct calculation is only problematic when the appended length will push the length past a power of ten; that is, at 9, 98, 99, 997, 998, 999, 9996, etc. To work this through, 1 + int(log10(len(s))) is the number of digits in the length of s. If we add that to len(s), then 9->10, 98->100, 99->101, etc, but still 8->9, 97->99, etc, so we can push past the power of ten exactly as needed. That is, adding this produces a number with the correct number of digits after the addition. Then do the log again to find the length of that number and that's the answer.
To test this:
from math import log10
def find_length(s):
L1 = len(s) + 1 + int(log10(len(s) + 1 + int(log10(len(s)))))
return L1
# test, just looking at lengths around 10**n
for i in range(9):
for j in range(30):
L = abs(10**i - j + 10) + 1
s = "a"*L
x0 = find_length(s)
new0 = s+`x0`
if len(new0)!=x0:
print "error", len(s), x0, log10(len(s)), log10(x0)
I'm trying to create a histogram in python as a part of my python class
It is supposed to look like this:
However, I can't figure out the histogram. This is my code so far:
sumValues = []
print("Enter 10 integers")
for i in range( 10 ):
newValue = int( input("Enter integer %d: " % (i + 1) ))
sumValues.append(newValue)
print("\nCreating a histogram from values: ")
print("%s %10s %10s" %("Element", "Value", "Histogram"))
How do I create the actual histogram?
Some hints:
New-style Python formatting allows this:
In [1]: stars = '*' * 4 # '****'
In [2]: '{:<10s}'.format(stars)
Out[3]: '**** '
That is, you can take a string of 4 stars (formed by repetition of '*' four times) and place it in a string of length 10 characters, aligned to the left (<) and padded to the right with whitespace.
(If you don't need the histogram to have the same number of characters (stars or spaces), just print the stars; no need to format)
Just like this:
# fake data
sumValues = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
...
# calculate how long is the list and adjust the padding for 'Element'
padding = max(len(sumValues), len('Element'))
# now the padding for 'Value'
padding1 = max(len(str(max(sumValues))), len('Value'))
print("\nCreating a histogram from values: ")
print("%s %10s %10s" %("Element", "Value", "Histogram"))
# use enumerate to loop your list and giving the index started from 1
for i,n in enumerate(sumValues, start=1):
print '{0} {1} {2}'.format( # print each line with its elements
str(i).ljust(padding), # print with space using str.ljust
str(i).rjust(padding1), # print with space using str.rjust
'*'*n) # '*' * n = '*' multiply by 'n' times
Creating a histogram from values:
Element Value Histogram
1 1 *
2 2 **
3 3 ***
4 4 ****
5 5 *****
6 6 ******
7 7 *******
8 8 ********
9 9 *********
10 10 **********
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
Trying to iterate through a number string in python and print the product of the first 5 numbers,then the second 5, then the third 5, etc etc. Unfortunately, I just keep getting the product of the first five digits over and over. Eventually I'll append them to a list. Why is my code stuck?
edit: Original number is an integer so I have to make it a string
def product_of_digits(number):
d= str(number)
for integer in d:
s = 0
k = []
while s < (len(d)):
print (int(d[s])*int(d[s+1])*int(d[s+2])*int(d[s+3])*int(d[s+4]))
s += 1
print (product_of_digits(a))
Let me list out the mistakes in the program.
You are iterating over d for nothing. You don't need that.
s += 1 is not part of the while loop. So, s will never get incremented, leading to infinite loop.
print (product_of_digits(a)) is inside the function itself, where a is not defined.
To find the product of all the consecutive 5 numbers, you cannot loop till the end of d. So, the loop should have been while s <= (len(d)-5):
You have initialized k, but used it nowhere.
So, the corrected program looks like this
def product_of_digits(number):
d, s = str(number), 0
while s <= (len(d)-5):
print(int(d[s]) * int(d[s+1]) * int(d[s+2]) * int(d[s+3]) * int(d[s+4]))
s += 1
product_of_digits(123456)
Output
120
720
You can also use a for loop, like this
def product_of_digits(number):
d = str(number)
for s in range(len(d) - 4):
print(int(d[s]) * int(d[s+1]) * int(d[s+2]) * int(d[s+3]) * int(d[s+4]))
There are a few problems with your code:
1) Your s+=1 indentation is incorrect
2) It should be s+=5 instead (assuming you want products of 1-5, 6-10, 11-15 and so on otherwise s+=1 is fine)
def product_of_digits(number):
d = str(number)
s = 0
while s < (len(d)-5):
print (int(d[s])*int(d[s+1])*int(d[s+2])*int(d[s+3])*int(d[s+4]))
s += 5 (see point 2)
print (product_of_digits(124345565534))
numpy.product([int(i) for i in str(s)])
where s is the number.