We were asked to print the following output:
1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2
3 3 3 3 3 3 3 3
4 4 4 4 4 4 4
5 5 5 5 5 5
6 6 6 6 6
7 7 7 7
8 8 8
9 9
10
I understand that it would require two loops so I tired this:
a = int(input())
i = a
f = 1
while i>0:
for j in range(i):
print(f,end=' ')
f += 1
i -= 1
print('\r')
With this I am getting the desired output, but as soon as I remove the last line of print('\r') the output becomes something like this:
1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 5 5 5 5 5 5 6 6 6 6 6 7 7 7 7 8 8 8 9 9 10
The desired output also comes out when I used print(' ') instead of print('\r'), I don't understand why this is happening?
Ps: I am a noob coder, starting my freshman year, so please go easy on me, if the formatting is not up to the mark, or the code looks bulky.
Probably not helping you so much but the following code produces the expected output:
a = 10
for i, j in enumerate(range(a, 0, -1), 1):
print(*[i] * j)
# Output:
1 1 1 1 1 1 1 1 1 1 # i=1, j=10
2 2 2 2 2 2 2 2 2 # i=2, j=9
3 3 3 3 3 3 3 3 # i=3, j=8
4 4 4 4 4 4 4 # i=4, j=7
5 5 5 5 5 5 # i=5, j=6
6 6 6 6 6 # i=6, j=5
7 7 7 7 # i=7, j=4
8 8 8 # i=8, j=3
9 9 # i=9, j=2
10 # i=10, j=1
The two important parameters here are sep (when you print a list) and end as argument of print. Let's try to use it:
a = 10
for i, j in enumerate(range(a, 0, -1), 1):
print(*[i] * j, sep='-', end='\n\n')
# Output:
1-1-1-1-1-1-1-1-1-1
2-2-2-2-2-2-2-2-2
3-3-3-3-3-3-3-3
4-4-4-4-4-4-4
5-5-5-5-5-5
6-6-6-6-6
7-7-7-7
8-8-8
9-9
10
Update
Step by step:
# i=3; j=8
>>> print([i])
[3]
>>> print([i] * j)
[3, 3, 3, 3, 3, 3, 3, 3]
# print takes an arbitrary number of positional arguments.
# So '*' unpack the list as positional arguments (like *args, **kwargs)
# Each one will be printed and separated by sep keyword (default is ' ')
>>> print(*[i] * j)
To make it all easier and prevent errors, you can simply do this:
n = 10
for i in range(1, n + 1):
txt = str(i) + " " # Generate the characters with space between
print(txt * (n + 1 - i)) # Print the characters the inverse amount of times i.e. 1 10, 10 1
Where it generates the text which is simply the number + a space, then prints it out the opposite amount of times, (11 - current number), i.e. 1 ten times, 10 one time.
I suggest using 2 or 4 spaces for indenting. Let's take a look:
a = int(input())
i = a
f = 1
while i>0:
for j in range(i):
print(f,end=' ')
f += 1
i -= 1
print('\r')
Notice the print(f,end=' ') within the inner loop. the end=' ' bit is important because print() appends a trailing new line \n to every call by default. Using end=' ' instead appends a space.
Now take a look at print('\r'). It does not specify end=' ', so it does still append a newline after each call to print. The fact that you additionally print a \r is inconsequential in this case. You could also just do print().
you can do this way :
rows = 10
b = 0
for i in range(rows, 0, -1):
b += 1
for j in range(1, i + 1):
print(b, end=' ')
print('\r')
No need for multiple loops.
for i in range(1,11):
# concatenate number + a space repeatedly, on the same line
# yes, there is an extra space at the end, which you won't see ;-)
print(f"{i} " * (11-i))
output:
1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2
3 3 3 3 3 3 3 3
4 4 4 4 4 4 4
5 5 5 5 5 5
6 6 6 6 6
7 7 7 7
8 8 8
9 9
10
As to what's happening with your code...
A basic Python print prints on a line, meaning that it ends with a line feed (which moves it to the next line).
So, if I take your word for it, you've done all the hard work of say the first line of 10 ones with spaces, when you are done at the following point.
#your code
f += 1
i -= 1
Now, so far you've avoided that line feed by changing the end parameter to print so that it doesn't end with a newline. So you have:
1 1 1 1 1 1 1 1 1 1
And still no line feed. Great!
But if you now start printing 2 2 2 2 2 2 2 2 2 , it will just get added to... the end of the previous line, without line feed.
So to force a line feed, you *print anything you want, but without the end parameter being set, so that print now ends with the linefeed it uses by default.
Example:
#without line feed
print("1 " * 3, end=' ')
print("2 " * 2, end=' ')
output:
1 1 1 2 2
Lets try printing something, anything, without a end = ' ')
print("1 " * 3, end=' ')
#now add a line by a print that is NOT using `end = ' '`
print("!")
print("2 " * 2, end=' ')
output:
1 1 1 !
2 2
OK, so now we have a line feed after ! so you jump to the next line when printing the 2s. But you don't want to see anything after the 1s.
Simples, print anything that is invisible.
print("1 " * 3, end=' ')
#now add a line by a print, but using a non-visible character.
#or an empty string. Tabs, spaces, etc... they will all work
print(" ")
print("2 " * 2, end=' ')
output:
1 1 1
2 2
This would also work:
print("1 " * 3, end=' ')
#we could also print a linefeed and end without one...
print("\n", end="")
print("2 " * 2, end=' ')
Related
Im having a hard time with the logic of the function def rotate: for example If I have a square of 3x3
0 5 2
7 8 4
1 6 3
and I rotate it:
Up on 2nd row
0 5 4
7 8 3
1 6 2
Down on 2nd
0 5 2
7 8 4
1 6 3
Left on 1st row- not sure its right but
0 5 2
8 4 7
1 6 3
Down on 2nd row
0 5 3
8 4 2
1 6 7
the final rotation should be
0 5 3
8 4 2
1 6 7
but i get rotation
0 5 4
8 4 2
1 6 2
below is are my function> if someone can help out with an error that would be great
def rotate(torusSquare,direction,index):
if(direction=='L' and index<3):
vals=torusSquare[index]
temp=vals[0]
vals[0]=vals[1]
vals[1]=vals[2]
vals[2]=temp
torusSquare[index]=vals
elif(direction=='R' and index<3):
vals=torusSquare[index]
temp=vals[2]
vals[2]=vals[1]
vals[1]=vals[0]
vals[0]=temp
torusSquare[index]=vals
elif(direction=='U' and index<3):
temp=torusSquare[0][index]
torusSquare[0][index]=torusSquare[1][index]
torusSquare[1][index]=torusSquare[2][index]
torusSquare[2][index]=temp
elif(direction=='D' and index<3):
temp=torusSquare[2][index]
torusSquare[1][index]=torusSquare[0][index]
torusSquare[2][index]=torusSquare[1][index]
torusSquare[0][index]=temp
def readfile(x):
torusSquare=[]
file= open(x)
count=0
maxcount=0
while True:
line = file.readline()
if count<3:
line=line.rstrip('\n').split(' ')
vals=[]
for val in line:
vals.append(int(val))
torusSquare.append(vals)
count+=1
elif count==3:
maxcount=int(line.rstrip('\n'))
print("Before The Rotation")
for i in range(count):
for j in range(count):
print(torusSquare[i][j],' ',end=' ')
print()
count+=1
elif maxcount>0:
line=line.rstrip('\n')
lst=line.split(' ')
rotate(torusSquare,lst[0],int(lst[1]))
maxcount-=1
elif maxcount==maxcount:
print("After The Final Rotation")
for i in range(3):
for j in range(3):
print(torusSquare[i][j],' ',end=' ')
print()
break
I think the error is in the misnumbering of the indices, try switching your down section to the following:
elif(direction=='D'):
temp=torusSquare[2][index]
torusSquare[2][index]=torusSquare[1][index]
torusSquare[1][index]=torusSquare[0][index]
torusSquare[0][index]=temp
This question already has answers here:
Print several values in the same line with commas
(2 answers)
Closed 4 years ago.
I need to modify this code, to replace the
number 1 with the number of the current measure. So, the first
number in each measure will always rise.
instead of
1
2
3
4
1
2
3
4
1
2
3
4
(with each number on its own line), I'd now print
1 2 3 4 2 2 3 4 3 2 3 4
, and so on.
beats_per_measure = 4
measures = 5
for measure in range(0, measures):
for beat in range(1, beats_per_measure + 1):
print(beat)
Perhaps you need something like below.
beats_per_measure = 4
measures = 5
### loop from 1 to 5 measures ###
# remove +1 to get sequence of 4
# iterations
for measure in range(1, measures+1):
# print the measure value in a single line
# first at iteration of outer loop to get
# the sequence
print(measure, end = " ")
## then loop from 2 to measure
for beat in range(2, beats_per_measure + 1):
# print each beat
print(beat, end = " ")
Output
1 2 3 4 2 2 3 4 3 2 3 4 4 2 3 4 5 2 3 4
If you are using python 3, this is the answer(tested):
beats_per_measure = 4
measures = 5
for measure in range(1, measures+1):
print(measure, end = ' ')
for beat in range(2, beats_per_measure + 1):
print(beat, end = ' ')
Or if you are using python 2, use this (tested):
beats_per_measure = 4
measures = 5
for measure in range(1, measures+1):
print measure,
for beat in range(1, beats_per_measure + 1):
print beat,
More info here: https://www.quora.com/How-do-I-print-something-on-the-same-line-in-Python
You can solve this by manually printing the measure you are currently in - followed by the remaining beats:
beats_per_measure = 4
measures = 5
for m in range(measures):
# manually print the measure you are in
print(m+1, end=" ") # do not put a newline after the print statement
# print the beats 0...bmp-1 == 0,1,2 - output adds 2 to each => 2,3,4
for beat in range(beats_per_measure - 1):
print(beat+2, end = " ") # do not put a newline after the print statement
Output:
1 2 3 4 2 2 3 4 3 2 3 4 4 2 3 4 5 2 3 4
* * * * *
The * are manually printed, the others filled in by the for-loop
You can read more about printing in one line here:
Print in one line dynamically
Python: multiple prints on the same line
Print several values in the same line with commas
Doku: https://docs.python.org/3/library/functions.html#print
You can also create a generator that counts measures on its own (I'll mark the measure-number with * manually):
def gimme_measure(beats_per_measure):
beats = list(range(2,beats_per_measure+1))
yield gimme_measure.measure
gimme_measure.measure += 1
yield from beats
gimme_measure.measure = 1 # defines the starting measure
# print 2*10 measures
for _ in range(10):
print(*gimme_measure(4), end = " ") # the * decomposes the values from the generator
for _ in range(10): # continues the beat measuring
print(*gimme_measure(4), end = " ") # the * decomposes the values from the generator
Output:
1 2 3 4 2 2 3 4 3 2 3 4 4 2 3 4 5 2 3 4 6 2 3 4 7 2 3 4 8 2 3 4 9 2 3 4 10 2 3 4 11 2 3 4 12 2 3 4 13 2 3 4 14 2 3 4 15 2 3 4 16 2 3 4 17 2 3 4 18 2 3 4 19 2 3 4 20 2 3 4
* * * * * * * * * ** ** ** ** ** ** ** ** ** ** **
The generator gimme_measure has it's own measure counter which is initialized to 1 and incremented each time you generate a new measure using the generator - if you do not reset the gimme_measure.measure to some other number it keeps counting upwards any time you print another generated measure.
You can even chain different bpm together:
# piece with 2 measures of 4 beats, 2 measures of 8 beats, 2 measures of 3 beats
for _ in range(2):
print(*gimme_measure(4), end = " ")
for _ in range(2): # continues the beat measuring
print(*gimme_measure(8), end = " ")
for _ in range(2): # continues the beat measuring
print(*gimme_measure(3), end = " ")
Output:
1 2 3 4 2 2 3 4 3 2 3 4 5 6 7 8 4 2 3 4 5 6 7 8 5 2 3 6 2 3
* * * * * *
this is my code right now:
loop_count = 1
for i in range(mystery_int):
for x in range(1,mystery_int):
print(x*loop_count, end=" ")
print (loop_count)
loop_count+=1
this is what it is supposed to print:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
But it prints:
1 2 3 4 1
2 4 6 8 2
3 6 9 12 3
4 8 12 16 4
5 10 15 20 5
You need to range till mystery_int + 1 because in range, second argument is exclusive. So, for example, range(1,6) gives numbers from 1 to 5.
Also, I added an empty print() which basically adds a newline to match with desired output.
Using end='\t' further aligns output properly.
loop_count = 1
mystery_int = 5
for i in range(mystery_int):
for x in range(1, mystery_int + 1):
print(x * loop_count, end='\t')
print()
loop_count += 1
the range for x should be range(1,mystery_int+1), and you also incorrectly print loop_count at the end of each line (which I replaced with the empty string, just to produce a newline).
loop_count = 1
for i in range(mystery_int):
for x in range(1,mystery_int+1):
print(x*loop_count, end=" ")
print('')
loop_count+=1
Note that the loop_count variable is not really needed. You could write the program as:
for i in range(1,mystery_int+1):
for x in range(1,mystery_int+1):
print(x*i, end=" ")
print('')
or even better as:
for i in range(1,mystery_int+1):
print(*[x*i for x in range(1,mystery_int+1)], sep=" ")
you are running on two for loops in addition to using another counter, i would recommend sticking only to the loops:
for i in range(1,mystery_int+1):
for x in range(1,mystery_int+1):
print(i*x, end=" ")
print("") # new line
I have this strange problem when following a reference, this code:
for r in range(10):
for c in range(r):
print "",
for c in range(10-r):
print c,
print ""
should print out something like this:
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8
0 1 2 3 4 5 6 7
0 1 2 3 4 5 6
0 1 2 3 4 5
0 1 2 3 4
0 1 2 3
0 1 2
0 1
0
but Instead I am getting this:
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8
0 1 2 3 4 5 6 7
0 1 2 3 4 5 6
0 1 2 3 4 5
0 1 2 3 4
0 1 2 3
0 1 2
0 1
0
Can anyone explain to me what is causing in indent on right side, it seems so simple but I have no clue what I can do to fix this?
You were printing the leading spaces incorrectly. You were printing empty quotes ("") which is printing only a single space. When you do print c, there is a space printed after c is printed. You should print " " instead to get the correct spacing. This is a very subtle thing to notice.
for r in range(10):
for c in range(r):
print " ", #print it here
for c in range(10-r):
print c,
print ""
Test
If you want to format it just so, it might be better to just let Python do it for you instead of counting explicit and the hidden implicit spaces. See the string formatting docs for what {:^19} means and more.
for i in range(10):
nums = ' '.join(str(x) for x in range(10 - i))
#print '{:^19}'.format(nums) # reproduces your "broken" code
print '{:>19}'.format(nums) # your desired output
Using the print function is a good alternative sometimes, as you can eliminate hidden spaces by setting the keyword argument end to an empty string:
from __future__ import print_function # must be at the top of the file.
# ...
print(x, end='')
You are simply not creating enough indent on the left side (there is no such thing as right side indent while printing).
For every new line you want to increase the indent by two spaces, because you are adding a number+whitespace on the line above. "", automatically adds one whitespace (this is why there is whitespaces between the numbers). Since you need to add two, simply add a whitespace within the quotes, like this: " ",.
The extra whitespace is filling the space of the number in the line above. The comma in "", is only filling the space between the numbers. To clarify: " ", uses the same space as c,, two characters, while "", only uses one character.
Here is your code with the small fix:
for r in range(10):
for c in range(r):
print " ", # added a whitespace here for correct indent
for c in range(10-r):
print c,
print ""
I'm writing a program, and the goal is to take a list of numbers and return all the six-letter combinations for it using a recursive function (without importing a function to do it for me). Say, for example, my numbers are "1 2 3 4 5 6 7 8 9", output would be:
1 2 3 4 5 6
1 2 3 4 5 7
1 2 3 4 5 8
1 2 3 4 5 9
1 2 3 4 6 7
1 2 3 4 6 8
1 2 3 4 6 9
1 2 3 4 7 8
... etcetera, all the way down to
4 5 6 7 8 9
I'm not looking for code, persay, just a push in the right direction conceptually. What I've attempted thus far has failed and I've driven myself into a logical rut.
I've included the code I used before below, but it isn't really a recursive function and only seems to work for 6-8-digit values. It's very messy, and I'd be fine with scrapping it entirely:
# Function prints all the possible 6-number combinations for a group of numbers
def lotto(constantnumbers, variablenumbers):
# Base case: No more constant variables, or only 6 numbers to begin with
if len(constantnumbers) == 0 or len(variablenumbers) == 0:
if len(constantnumbers) == 0:
print(" ".join(variablenumbers[1:7]))
else:
print(" ".join(constantnumbers[0:6]))
i = 6 - len(constantnumbers)
outvars = variablenumbers[1:i + 1]
if len(variablenumbers) > len(outvars) + 1:
print(" ".join(constantnumbers + outvars))
for index in range(len(outvars), 0, -1):
outvars[index - 1] = variablenumbers[index + 1]
print(" ".join(constantnumbers + outvars))
else:
i = 6 - len(constantnumbers)
outvars = variablenumbers[1:i + 1]
print(" ".join(constantnumbers + outvars))
if len(variablenumbers) > len(outvars) + 1:
for index in range(len(outvars), 0, -1):
outvars[index - 1] = variablenumbers[index + 1]
print(" ".join(constantnumbers + outvars))
#Reiterates the function until there are no more constant numbers
lotto(constantnumbers[0:-1], constantnumbers[-1:] + variablenumbers)
import itertools
for combo in itertools.combinations(range(1,10), 6):
print(" ".join(str(c) for c in combo))
which gives
1 2 3 4 5 6
1 2 3 4 5 7
1 2 3 4 5 8
...
3 4 6 7 8 9
3 5 6 7 8 9
4 5 6 7 8 9
Edit: ok, here is a recursive definition:
def combinations(basis, howmany):
for index in range(0, len(basis) - howmany + 1):
if howmany == 1:
yield [basis[index]]
else:
this, remainder = basis[index], basis[index+1:]
for rest in combinations(remainder, howmany - 1):
yield [this] + rest
Edit2:
Base case: A 1-item combination is any basis item.
Induction: An N-item combination is any basis item plus an (N-1)-item combination from the remaining basis.