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
Related
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)
With Python editor I am trying to recreate this specific line pattern over here:
666666
6 6
6 6
6 6
66
6
This is the Code that I have created:
steps=6
for s in range(steps):
print('6' + (' ' * r) + '6')
However the output that I get instead is:
66
6 6
6 6
6 6
6 6
6 6
Thus as you can see it almost does the opposite operation to what I wanted in the opening output above. If there is a way to reverse this output I have to what I want please share.
You can use the built-in reversed function that returns an iterator that goes through the range in reverse.
steps=6
for r in reversed(range(steps)):
print('#' + (' ' * r) + '#')
Or you can use list splicing to revers the list like so:
steps=6
for r in range(steps)[::-1]:
print('#' + (' ' * r) + '#')
Aside from Martijn's comment on considering what kind of pattern you need to follow, i.e. how the number of spaces evolves from one line to the next, you may want to look into the documentation of the command range at PythonDocs on range(). Currently you are only providing one argument:
range(stop)
Python will then use default values for the remaining arguments: start=0 and step=1. However, you can provide these explicitly. The 'step' argument is where you can put in reversed counting:
range(start, stop[, step])
Let us start with building it in ascending order, that is like the diagram below
6
66
6 6
6 6
66666
There is a series to the number of spaces depending after height = 1, that is from height = 2 the number of spaces have the series 0,1,2 and so on, therefore if height is n then the series begins at 2 where the space = 0 and ends at n - 1 where the number of spaces is equal to n - 3, and at height = n the number of 6s is equal to n - 2.
The code for this would be
def print6(height):
... print 6
... for s in range(0, height - 2):
... print str(6) + ' '*s + str(6)
... print str(6)*2+str(6)*(height-2)
To reverse this
def print6(height):
... print str(6)*2+str(6)*(height-2)
... for s in range(0, height - 2):
... print str(6) + ' '*(height-3-s) + str(6)
... print 6
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
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'm wondering how I could create one of those nifty console counters in Python as in certain C/C++-programs.
I've got a loop doing things and the current output is along the lines of:
Doing thing 0
Doing thing 1
Doing thing 2
...
what would be neater would be to just have the last line update;
X things done.
I've seen this in a number of console programs and am wondering if/how I'd do this in Python.
An easy solution is just writing "\r" before the string and not adding a newline; if the string never gets shorter this is sufficient...
sys.stdout.write("\rDoing thing %i" % i)
sys.stdout.flush()
Slightly more sophisticated is a progress bar... this is something I am using:
def start_progress(title):
global progress_x
sys.stdout.write(title + ": [" + "-"*40 + "]" + chr(8)*41)
sys.stdout.flush()
progress_x = 0
def progress(x):
global progress_x
x = int(x * 40 // 100)
sys.stdout.write("#" * (x - progress_x))
sys.stdout.flush()
progress_x = x
def end_progress():
sys.stdout.write("#" * (40 - progress_x) + "]\n")
sys.stdout.flush()
You call start_progress passing the description of the operation, then progress(x) where x is the percentage and finally end_progress()
A more elegant solution could be:
def progress_bar(current, total, bar_length=20):
fraction = current / total
arrow = int(fraction * bar_length - 1) * '-' + '>'
padding = int(bar_length - len(arrow)) * ' '
ending = '\n' if current == total else '\r'
print(f'Progress: [{arrow}{padding}] {int(fraction*100)}%', end=ending)
Call this function with current and total:
progress_bar(69, 100)
The result should be
Progress: [-------------> ] 69%
Note:
For Python 3.6 and below
For Python 2.x.
In python 3 you can do this to print on the same line:
print('', end='\r')
Especially useful to keep track of the latest update and progress.
I would also recommend tqdm from here if one wants to see the progress of a loop. It prints the current iteration and total iterations as a progression bar with an expected time of finishing. Super useful and quick. Works for python2 and python3.
I wrote this a while ago and really happy with it. Feel free to use it.
It takes an index and total and optionally title or bar_length. Once done, replaces the hour glass with a check-mark.
⏳ Calculating: [████░░░░░░░░░░░░░░░░░░░░░] 18.0% done
✅ Calculating: [█████████████████████████] 100.0% done
I included an example that can be run to test it.
import sys
import time
def print_percent_done(index, total, bar_len=50, title='Please wait'):
'''
index is expected to be 0 based index.
0 <= index < total
'''
percent_done = (index+1)/total*100
percent_done = round(percent_done, 1)
done = round(percent_done/(100/bar_len))
togo = bar_len-done
done_str = '█'*int(done)
togo_str = '░'*int(togo)
print(f'\t⏳{title}: [{done_str}{togo_str}] {percent_done}% done', end='\r')
if round(percent_done) == 100:
print('\t✅')
r = 50
for i in range(r):
print_percent_done(i,r)
time.sleep(.02)
I also have a version with responsive progress bar depending on the terminal width using shutil.get_terminal_size() if that is of interest.
It can be done without using the sys library if we look at the print() function
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Here is my code:
def update(n):
for i in range(n):
print("i:",i,sep='',end="\r",flush=True)
time.sleep(1)
For anyone who stumbles upon this years later (like I did), I tweaked 6502's methods a little bit to allow the progress bar to decrease as well as increase. Useful in slightly more cases. Thanks 6502 for a great tool!
Basically, the only difference is that the whole line of #s and -s is written each time progress(x) is called, and the cursor is always returned to the start of the bar.
def startprogress(title):
"""Creates a progress bar 40 chars long on the console
and moves cursor back to beginning with BS character"""
global progress_x
sys.stdout.write(title + ": [" + "-" * 40 + "]" + chr(8) * 41)
sys.stdout.flush()
progress_x = 0
def progress(x):
"""Sets progress bar to a certain percentage x.
Progress is given as whole percentage, i.e. 50% done
is given by x = 50"""
global progress_x
x = int(x * 40 // 100)
sys.stdout.write("#" * x + "-" * (40 - x) + "]" + chr(8) * 41)
sys.stdout.flush()
progress_x = x
def endprogress():
"""End of progress bar;
Write full bar, then move to next line"""
sys.stdout.write("#" * 40 + "]\n")
sys.stdout.flush()
The other answer may be better, but here's what I was doing. First, I made a function called progress which prints off the backspace character:
def progress(x):
out = '%s things done' % x # The output
bs = '\b' * 1000 # The backspace
print bs,
print out,
Then I called it in a loop in my main function like so:
def main():
for x in range(20):
progress(x)
return
This will of course erase the entire line, but you can mess with it to do exactly what you want. I ended up make a progress bar using this method.
If I understood well (not sure) you want to print using <CR> and not <LR>?
If so this is possible, as long the console terminal allows this (it will break when output si redirected to a file).
from __future__ import print_function
print("count x\r", file=sys.stdout, end=" ")
Added a little bit more functionality to the example of Aravind Voggu:
def progressBar(name, value, endvalue, bar_length = 50, width = 20):
percent = float(value) / endvalue
arrow = '-' * int(round(percent*bar_length) - 1) + '>'
spaces = ' ' * (bar_length - len(arrow))
sys.stdout.write("\r{0: <{1}} : [{2}]{3}%".format(\
name, width, arrow + spaces, int(round(percent*100))))
sys.stdout.flush()
if value == endvalue:
sys.stdout.write('\n\n')
Now you are able to generate multiple progressbars without replacing the previous one.
I've also added name as a value with a fixed width.
For two loops and two times the use of progressBar() the result will look like:
from time import sleep
max_val = 40
for done in range(max_val):
sleep(0.05)
undone = max_val - 1 - done
proc = (100 * done) // (max_val - 1)
print(f"\rProgress: [{('#' * done) + ('_' * undone)}] ({proc}%)", end='\r')
print("\nDone!")
Progress: [###################_____________________] (47%)
Progress: [########################################] (100%)
Done!
Below code will count Message from 0 to 137 each 0.3 second replacing previous number.
Number of symbol to backstage = number of digits.
stream = sys.stdout
for i in range(137):
stream.write('\b' * (len(str(i)) + 10))
stream.write("Message : " + str(i))
stream.flush()
time.sleep(0.3)
Had the same problem and tried many solutions.
import sys
sys.stdout.write('\r Blablabla')
worked like a charm!