Use nested for loops to create the following printout:
The number of rows should be read from the user. Use formatted printouts
so that the numbers are aligned even for two-digit numbers.
• All printed numbers correspond to column numbers.
• No number is printed if the column number is less than the row number.
• Print a suitable number of spaces to fill an empty column.
# Program to print a pattern with numbers
print("Program to print a pattern with numbers ")
print("-" * 50)
n = int(input("Please enter the number of rows "))
print("-" * 50)
for i in range(n + 1):
# Increase triangle hidden
for j in range(i):
print(" ", end=' ')
# Decrease triangle to include numbers in pattern not in increment
for j in range(i, n):
print(j + 1, end=" ")
print()
The code above produces the required output but the numbers are not aligned in an input with 2 digits. How do I format the iterables to make a perfectly aligned output printout.
Output:
This is how you might modify your code to use str.rjust. Adjust the 2 in rjust(2) to whatever number you want.
print("Program to print a pattern with numbers ")
print("-" * 50)
n = int(input("Please enter the number of rows "))
print("-" * 50)
for i in range(n + 1):
# Increase triangle hidden
for j in range(i):
print(" ".rjust(2), end=" ")
# Decrease triangle to include numbers in pattern not in increment
for j in range(i, n):
print(str(j+1).rjust(2), end=" ")
print()
For your example, this gives:
Program to print a pattern with numbers
--------------------------------------------------
Please enter the number of rows 12
--------------------------------------------------
1 2 3 4 5 6 7 8 9 10 11 12
2 3 4 5 6 7 8 9 10 11 12
3 4 5 6 7 8 9 10 11 12
4 5 6 7 8 9 10 11 12
5 6 7 8 9 10 11 12
6 7 8 9 10 11 12
7 8 9 10 11 12
8 9 10 11 12
9 10 11 12
10 11 12
11 12
12
You can use str.rjust to right-justify a string. As long as you know the overall length of each line, that makes it easy to align each line so that they're all aligned on the right:
>>> n = 5
>>> for i in range(1, n+1):
... print(''.join(str(j).rjust(3) for j in range(i, n+1)).rjust(n*3))
...
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
I'm embarrassed to ask such a simple question. My term does not start for two more weeks so I can't ask a professor, and the suspense would kill me.
Why does 2 mod 4 = 2?
Mod just means you take the remainder after performing the division. Since 4 goes into 2 zero times, you end up with a remainder of 2.
Modulo is the remainder, not division.
2 / 4 = 0R2
2 % 4 = 2
The sign % is often used for the modulo operator, in lieu of the word mod.
For x % 4, you get the following table (for 1-10)
x x%4
------
1 1
2 2
3 3
4 0
5 1
6 2
7 3
8 0
9 1
10 2
Modulo (mod, %) is the Remainder operator.
2%2 = 0 (2/2 = 1 remainder 0)
1%2 = 1 (1/2 = 0 remainder 1)
4%2 = 0 (4/2 = 2 remainder 0)
5%2 = 1 (5/2 = 2 remainder 1)
Much easier if u use bananas and a group of people.
Say you have 1 banana and group of 6 people, this you would express: 1 mod 6 / 1 % 6 / 1 modulo 6.
You need 6 bananas for each person in group to be well fed and happy.
So if you then have 1 banana and need to share it with 6 people, but you can only share if you have 1 banana for each group member, that is 6 persons, then you will have 1 banana (remainder, not shared on anyone in group), the same goes for 2 bananas. Then you will have 2 banana as remainder (nothing is shared).
But when you get 6 bananas, then you should be happy, because then there is 1 banana for each member in group of 6 people, and the remainder is 0 or no bananas left when you shared all 6 bananas on 6 people.
Now, for 7 bananas and 6 people in group, you then will have 7 mod 6 = 1, this because you gave 6 people 1 banana each, and 1 banana is the remainder.
For 12 mod 6 or 12 bananas shared on 6 people, each one will have two bananas, and the remainder is then 0.
2 / 4 = 0 with a remainder of 2
I was confused about this, too, only a few minutes ago. Then I did the division long-hand on a piece of paper and it made sense:
4 goes into 2 zero times.
4 times 0 is 0.
You put that zero under the 2 and subtract which leaves 2.
That's as far as the computer is going to take this problem. The computer stops there and returns the 2, which makes sense since that's what "%" (mod) is asking for.
We've been trained to put in the decimal and keep going which is why this can be counterintuitive at first.
Someone contacted me and asked me to explain in more details my answer in the comment of the question. So here is what I replied to that person in case it can help anyone else:
The modulo operation gives you the remainder of the euclidian disivion
(which only works with integer, not real numbers). If you have A such
that A = B * C + D (with D < B), then the quotient of the euclidian division of A
by B is C, and the remainder is D. If you divide 2 by 4, the quotient
is 0 and the remainder is 2.
Suppose you have A objects (that you can't cut). And you want to
distribute the same amount of those objects to B people. As long as
you have more than B objects, you give each of them 1, and repeat.
When you have less than B objects left you stop and keep the remaining
objects. The number of time you have repeated the operation, let's
call that number C, is the quotient. The number of objects you keep at
the end, let's call it D, is the remainder.
If you have 2 objects and 4 people. You already have less than 4
objects. So each person get 0 objects, and you keep 2.
That's why 2 modulo 4 is 2.
The modulo operator evaluates to the remainder of the division of the two integer operands. Here are a few examples:
23 % 10 evaluates to 3 (because 23/10 is 2 with a remainder of 3)
50 % 50 evaluates to 0 (50/50 is 1 with a remainder of 0)
9 % 100 evaluates to 9 (9/100 is 0 with a remainder of 9)
mod means the reaminder when divided by. So 2 divided by 4 is 0 with 2 remaining. Therefore 2 mod 4 is 2.
Modulo is the remainder, expressed as an integer, of a mathematical division expression.
So, lets say you have a pixel on a screen at position 90 where the screen is 100 pixels wide and add 20, it will wrap around to position 10. Why...because 90 + 20 = 110 therefore 110 % 100 = 10.
For me to understand it I consider the modulo is the integer representation of fractional number. Furthermore if you do the expression backwards and process the remainder as a fractional number and then added to the divisor it will give you your original answer.
Examples:
100
(A) --- = 14 mod 2
7
123
(B) --- = 8 mod 3
15
3
(C) --- = 0 mod 3
4
Reversed engineered to:
2 14(7) 2 98 2 100
(A) 14 mod 2 = 14 + --- = ----- + --- = --- + --- = ---
7 7 7 7 7 7
3 8(15) 3 120 3 123
(B) 8 mod 3 = 8 + --- = ----- + --- = --- + --- = ---
15 15 15 15 15 15
3 3
(B) 0 mod 3 = 0 + --- = ---
4 4
When you divide 2 by 4, you get 0 with 2 left over or remaining. Modulo is just the remainder after dividing the number.
I think you are getting confused over how the modulo equation is read.
When we write a division equation such as 2/4 we are dividing 2 by 4.
When a modulo equation is wrote such as 2 % 4 we are dividing 2 by 4 (think 2 over 4) and returning the remainder.
MOD is remainder operator. That is why 2 mod 4 gives 2 as remainder. 4*0=0 and then 2-0=2. To make it more clear try to do same with 6 mod 4 or 8 mod 3.
This is Euclid Algorithm.
e.g
a mod b = k * b + c => a mod b = c, where k is an integer and c is the answer
4 mod 2 = 2 * 2 + 0 => 4 mod 2 = 0
27 mod 5 = 5 * 5 + 2 => 27 mod 5 = 2
so your answer is
2 mod 4 = 0 * 4 + 2 => 2 mod 4 = 2
For:
2 mod 4
We can use this little formula I came up with after thinking a bit, maybe it's already defined somewhere I don't know but works for me, and its really useful.
A mod B = C where C is the answer
K * B - A = |C| where K is how many times B fits in A
2 mod 4 would be:
0 * 4 - 2 = |C|
C = |-2| => 2
Hope it works for you :)
Mod operation works with reminder.
This is called modular arithmetic.
a==b(mod m)
then m|(a-b)
a-b=km
a=b+km
So, 2=2+0*4
To answer a modulo x % y, you ask two questions:
A- How many times y goes in x without remainder ? For 2%4 that's 0.
B- How much do you need to add to get from that back to x ? To get from 0 back to 2 you'll need 2-0, i.e. 2.
These can be summed up in one question like so:
How much will you need to add to the integer-ish result of the division of x by y, to get back at x?
By integer-ish it is meant only whole numbers and not fractions whatsoever are of interest.
A fractional division remainder (e.g. .283849) is not of interest in modulo because modulo only deals with integer numbers.
For a visual way to think about it, picture a clock face that, in your particular example, only goes to 4 instead of 12. If you start at 4 on the clock (which is like starting at zero) and go around it clockwise for 2 "hours", you land on 2, just like going around it clockwise for 6 "hours" would also land you on 2 (6 mod 4 == 2 just like 2 mod 4 == 2).
This could be a good time to mention the modr() function. It returns both the whole and the remainder parts of a division.
print("\n 17 // 3 =",17//3," # Does the same thing as int(17/3)")
print(" 17 % 3 =",17%3," # Modulo division gives the remainder.")
whole, remain = divmod(17,3)
print(" divmod(17,3) returns ->",divmod(17,3),end="")
print(" because 3 goes into 17,",whole,"times with a remainder of",remain,end=".\n\n")
The way I go about it is, 2%4 can be interpreted as what is the highest factor of 4 that is less or equal to 2, and that is 0, therefore 2 (the left operand from 2%4) minus(-) 0 is 2
So far I have tried to create a table of the first 6 multiples of 2 that should give:
2 4 6 8 10 12
My code for this currently looks like:
i = 1
while i <= 6:
print(2*i ,' \t' , )
i = i + 1
But this outputs them vertically, not horizontally so:
2
4
6
8
10
12
There is also a tab after each number.
You can use a simple for-loop as they are more Pythonic for this application than while loops.
So just loop through the numbers between 1 and 6 and print that number multiplied by 2 with a space instead of the new-line character. Finally, you can call one more print at the end to move to the next line after they have all been printed.
for i in range(1, 7):
print(i * 2, end=' ')
print()
which outputs:
2 4 6 8 10 12
If you wanted do this whole thing in one-line, you could use a generator and string.join(). You may not fully understand this, but the following produces the same result:
print(" ".join(str(i*2) for i in range(1, 7)))
which gives:
2 4 6 8 10 12
Note that one last thing is that this method doesn't produce a uniformly spaced table. To show what I mean by "uniformly spaced", here are some examples:
not uniformly spaced:
1234 1 123 12 12312 123
uniformly spaced:
1234 1 123 12 12312 123
To make the output print nicely like above, we can use .ljust:
print("".join(str(i*2).ljust(3) for i in range(1, 7)))
which gives a nicer table:
2 4 6 8 10 12
Finally, if you wanted to make this into a function that is more general purpose, you could do:
def tbl(num, amnt):
print("".join(str(i*num).rjust(len(str(num*amnt))+1) for i in range(1,amnt+1)))
and some examples of this function:
>>> tbl(3, 10)
3 6 9 12 15 18 21 24 27 30
>>> tbl(9, 5)
9 18 27 36 45
>>> tbl(10, 10)
10 20 30 40 50 60 70 80 90 100
Change your print statement to be like this: print(2*i, end=' \t') The end key argument sets what the ending character should be. By default, it's a newline, as you know.
I need to create a function that takes inputs of lists from the user and returns them as such:
>>> print_table([[0,1,2,3,4,5],[0,1,4,9,16,25],[0,1,8,27,64,125]])
0 1 2 3 4 5
0 1 4 9 16 25
0 1 8 27 64 125
>>> print_table(times_table(6,6))
0 0 0 0 0 0 0
0 1 2 3 4 5 6
0 2 4 6 8 10 12
0 3 6 9 12 15 18
0 4 8 12 16 20 24
0 5 10 15 20 25 30
0 6 12 18 24 30 36
The times_table refers to my current code:
def times_table(s):
n = int(input('Please enter a positive integer between 1 and 15: '))
for row in range(n+1):
s = ''
for col in range(n+1):
s += '{:3} '.format(row * col)
print(s)
Help me if you can....
To get two values as input from the user, i.e. number of columns and rows, you can do as follows:
in_values = input('Please enter two positive integers between 1 and 15, separated by comma (e.g. 2,3): ')
m,n = map(int, in_values.split(','))
print(m,n)
To print out a formatted list of lists, you may wish to consider using string formatting through the format() method of strings. One thing I notice in your upper example is that you only get to 3 digits, and the space between the numbers seems to be unchanging. For lists with large numbers, this will likely mess up the formatting of the table. By using the format() method, you can take this into account and keep your table nicely spaced.
The easiest way I can think of to accomplish this is to determine what is the single largest number (most digits) in the entire list of lists and then incorporate that in the formatting. I would recommend you read up on string formatting for the python type string (including the mini formatting language).
Assuming s is the argument passed in to print_table:
maxchars = len(str(max(max(s))))
This will provide the largest number of characters in a single entry in the list. You can then utilize this number in the formatting of the rows in a for loop:
for lst in l:
output = ""
for i in lst:
output += "{0:<{1}} ".format(i, maxchars)
print(output)
the line output += "{0:<{1}} ".format(i, maxchars) means to print the number ({0} maps to the i in the call to format) left adjusted (<) in a space of characters "maxchars" wide ({1} maps to maxchars in the call to format).
So given your list of lists above, it will print it as:
0 1 2 3 4 5
0 1 4 9 16 25
0 1 8 27 64 125
but if the numbers are much larger (or any of the numbers are much larger, such as the 125 being replaced with 125125, it will unfortunately look like this because it is padding each item with the appropriate number of character spaces to contain a number of 6 characters:
0 1 2 3 4 5
0 1 4 9 16 25
0 1 8 27 64 125125
The above example takes a variable number of characters into account, however you could also format the string using an integer by replacing the {1} with an integer and omitting the maxchars portion (including both setting it and it being passed to format) if that is sufficient.
output += "{0:<4} ".format(i)
Optionally, you could figure out how to determine the largest number in a given column and then just format that column appropriately, however I am not going to put that in this answer.
The output of this code is quite similar but not exactly what it's supposed to be.
The code is:
def printMultiples(n):
i = 1
while (i <= 10):
print(n*i, end = ' ')
i += 1
n = 1
while (i<= 3):
printMultiples(n)
n += 1
The output is:
1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30
Whereas it should be like:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
How should this code be modified?
add an empty print at the end of the printMultiples, outside the while (i <= 10): loop.
Your problem is that you are not printing a new line after each list of multiples. You could solve this by putting at the end of your printMultiples function outside of the loop the line
print()
To make the columns line up, you will need to completely change your approach. Currently, printMultiples() cannot know how many spaces to put after each number because it doesn't know how many times it will be called in the outer while loop.
What you might do is:
create a two dimensional array of string representations for each multiple (without printing anything yet) - the str() function will be useful for this
for each column, check the length of the longest number in that column (it will always be the last one) and add one
print each row, adding the appropriate number of spaces after each string to match the number of spaces required for that column
A simpler approach, if you're only interested in columnar output and not the precise spacing, would be to print each number with enough space after it to accommodate the largest number you expect to output. So you might get:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
(Note how there are three spaces after each number in the first three columns even though you don't need all three spaces.)
Changing your existing code to do that would be easier. See Format String Syntax for details.
If you already know you wish to pad numbers to be of width 3, then a suitable (and more pythonic) printMultiples is
def printMultiples(n):
txt = "".join(["{0: <3d}".format(n*i) for i in range(1, 11)])
print(txt)
Better would be to allow the width to change. And you could then pass a width you prefer as, eg, the width of the largest number you expect
def printMultiples(n, width=3):
txt = "".join(["{0: <{1}d}".format(n*i, width) for i in range(1, 11)])
print(txt)
width = len(str(4 * 10)) + 1
for i in range(1, 4):
printMultiples(i, width )