Related
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=' ')
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
I have some arrays m rows by 2 `columns (like series of coordinates) and I want to automatize my code so that I will not use nested loop for every coord. Here is my code it runs well and gives right answer coordinates but I want to make a dynamic loop:
import numpy as np
A = np.array([[1,5,7,4,6,2,2,6,7,2],[2,8,2,9,3,9,8,5,6,2],[3,4,0,2,4,3,0,2,6,7],\
[1,5,7,3,4,5,2,7,9,7],[6,2,8,8,6,7,9,6,9,7],[0,2,0,3,3,5,2,3,5,5],[5,5,5,0,6,6,8,5,9,0]\
,[0,5,7,6,0,6,9,9,6,7],[5,5,8,5,0,8,5,3,5,5],[0,0,6,3,3,3,9,5,9,9]])
number = 8292
number = np.asarray([int(i) for i in str(number)]) #split number into array
#the coordinates of every single value contained in required number
coord1=np.asarray(np.where(A == number[0])).T
coord2=np.asarray(np.where(A == number[1])).T
coord3=np.asarray(np.where(A == number[2])).T
coord4=np.asarray(np.where(A == number[3])).T
coordinates = np.array([[0,0]]) #initialize the array that will return all the desired coordinates
solutions = 0 #initialize the array that will give the number of solutions
for j in coord1:
j = j.reshape(1, -1)
for i in coord2 :
i=i.reshape(1, -1)
if (i[0,0]==j[0,0]+1 and i[0,1]==j[0,1]) or (i[0,0]==j[0,0]-1 and i[0,1]==j[0,1]) or (i[0,0]==j[0,0] and i[0,1]==j[0,1]+1) or (i[0,0]==j[0,0] and i[0,1]==j[0,1]-1) :
for ii in coord3 :
ii=ii.reshape(1, -1)
if (np.array_equal(ii,j)==0 and ii[0,0]==i[0,0]+1 and ii[0,1]==i[0,1]) or (np.array_equal(ii,j)==0 and ii[0,0]==i[0,0]-1 and ii[0,1]==i[0,1]) or (np.array_equal(ii,j)==0 and ii[0,0]==i[0,0] and ii[0,1]==i[0,1]+1) or (np.array_equal(ii,j)==0 and ii[0,0]==i[0,0] and ii[0,1]==i[0,1]-1) :
for iii in coord4 :
iii=iii.reshape(1, -1)
if (np.array_equal(iii,i)==0 and iii[0,0]==ii[0,0]+1 and iii[0,1]==ii[0,1]) or (np.array_equal(iii,i)==0 and iii[0,0]==ii[0,0]-1 and iii[0,1]==ii[0,1]) or (np.array_equal(iii,i)==0 and iii[0,0]==ii[0,0] and iii[0,1]==ii[0,1]+1) or (np.array_equal(iii,i)==0 and iii[0,0]==ii[0,0] and iii[0,1]==ii[0,1]-1) :
point = np.concatenate((j,i,ii,iii))
coordinates = np.append(coordinates,point,axis=0)
solutions +=1
coordinates = np.delete(coordinates, (0), axis=0)
import itertools
A = [1, 2, 3]
B = [4, 5, 6]
C = [7, 8, 9]
for (a, b, c) in itertools.product (A, B, C):
print (a, b, c);
outputs:
1 4 7
1 4 8
1 4 9
1 5 7
1 5 8
1 5 9
1 6 7
1 6 8
1 6 9
2 4 7
2 4 8
2 4 9
2 5 7
2 5 8
2 5 9
2 6 7
2 6 8
2 6 9
3 4 7
3 4 8
3 4 9
3 5 7
3 5 8
3 5 9
3 6 7
3 6 8
3 6 9
See documentation for details.
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
* * * * * *
I am having trouble getting this python code to work right. it is a code to display pascal's triangle using binomials. I do not know what is wrong. The code looks like this
from math import factorial
def binomial (n,k):
if k==0:
return 1
else:
return int((factorial(n)//factorial(k))*factorial(n-k))
def pascals_triangle(rows):
rows=20
for n in range (0,rows):
for k in range (0,n+1):
print(binomial(n,k))
print '\n'
This is what it keeps printing
1
1 1
1
2
1
1
12
3
1
1
144
24
4
1
1
2880
360
40
5
1
1
86400
8640
720
60
6
1
1
3628800
302400
20160
1260
and on and on. any help would be welcomed.!!
from math import factorial
def binomial (n,k):
if k==0:
return 1
else:
return int((factorial(n)//factorial(k))*factorial(n-k))
def pascals_triangle(rows):
for n in range (rows):
l = [binomial(n, k) for k in range (0,n+1)]
print l
pascals_triangle(5)
output:
[1]
[1, 1]
[1, 2, 1]
[1, 12, 3, 1]
[1, 144, 24, 4, 1]
there are many wrong things.
The first one is the way you compute the values : if building a pascal triangle, you want to use the previous line to compute the current one, and not use the binomial computation (which is expensive due to the number of multiplications).
then by default, print appends a "\n"
Correct implementation:
def print_line(x):
print (" ".join(map(str,x)))
def pascals_triangle(rows):
cur_line=[1,1]
for x in range (2,rows):
new_line=[1]
for n in range (0,len(cur_line)-1):
new_line.append(cur_line[n]+cur_line[n+1])
new_line.append(1)
print_line (new_line)
cur_line=new_line
this provides the following output
$ python pascal.py
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
Your binomial function had a small bracketing mistake in it, which was giving you incorrect output:
from math import factorial
def binomial(n, k):
if k==0:
return 1
else:
return int((factorial(n)/(factorial(k)*factorial(n-k))))
def pascals_triangle(rows, max_width):
for n in range (0,rows):
indent = (rows - n - 1) * max_width
print(' ' * indent, end='')
for k in range(0, n+1):
print("{:^{w}}".format(binomial(n, k), w = max_width*2), end='')
print()
pascals_triangle(7, 2)
With the addition of a padding parameter, the output can be made to look like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1