How do I create a horizontal multiplication table in Python? - python

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.

Related

Print a number table in a simple format

I am stuck trying to print out a table in Python which would look like this (first number stands for amount of numbers, second for amount of columns):
>>> print_table(13,4)
0 1 2 3
4 5 6 7
8 9 10 11
12 13
Does anyone know a way to achieve this?
This is slightly more difficult than it sounds initially.
def numbers(n, r):
print('\n'.join(' '.join(map(str, range(r*i, min(r*(i + 1), n + 1)))) for i in range(n//r + 1)))
numbers(13, 4)
#>>> 0 1 2 3
4 5 6 7
8 9 10 11
12 13
def numbers(a,b):
i=0;
c=0;
while i<=a:
print(i,end="") #prevents printing a new line
c+=1
if c>=b:
print("\n") #prints a new line when the number of columns is reached and then reset the current column number
c=0;
I think it should work
def num2(n=10, r=3):
print('\n'.join(' '.join(tuple(map(str, range(n+1)))[i:i+r]) for i in range(0, n+1, r)))
<<<
0 1 2
3 4 5
6 7 8
9 10

Check a variable is a multiple of 10

I need my program to check an in putted variable (e_gtin) and then calculate the GTIN from it (times the 1,3,5 and 7th number by three then add the 7 numbers up and divide by the nearest 10 times table) So far, it times the numbers and adds them up but I don't know where to go from there in terms of making it a multiple of ten
In Addition i eventually used this code
calculator = int(e_gtin[0])*3+int(e_gtin[1])+\
int(e_gtin[2])*3+int(e_gtin[3])+\
int(e_gtin[4])*3+int(e_gtin[5])+\
int(e_gtin[6])*3
rounding = round(calculator+4)
The plus 4 is so the variable will always round up rather than rounding down (The GTIN calculation specifies this)
e_gtin being an inputted 7 digit GTIN code.
Thanks go to --->
https://stackoverflow.com/users/906693/roadrunner66
You are presumably asking about calculating the check-digit on a GTIN8 number. An explanation is given here http://www.gs1.org/how-calculate-check-digit-manually
e = input("Enter a 7 digit number - ")
# note: an integer number can not be accessed like a string or list,
# make it a string first
e=str(e)
sum= int(e[0])*3+int(e[1])+\
int(e[2])*3+int(e[3])+\
int(e[4])*3+int(e[5])+\
int(e[6])*3
checkdigit = 9 - (sum-1) % 10
print sum,checkdigit
To understand the working of a the modulo operator, just play with it, make yourself a table etc.
import numpy as np
sums=np.array([50,51,52,53,54,55,56,57,58,59,60,61])
print sums
print sums % 10
print 10 - sums % 10 # all results right except for 10s which should be zeros
print 10 - (sums-1) % 10 -1
output:
[50 51 52 53 54 55 56 57 58 59 60 61]
[0 1 2 3 4 5 6 7 8 9 0 1]
[10 9 8 7 6 5 4 3 2 1 10 9]
[0 9 8 7 6 5 4 3 2 1 0 9]

Python and CodeEval: Why isn't my solution to this Multiplication Table challenge not correct?

So I've been digging into some of the challenges at CodeEval during the last couple of days. One of them asks you to print a pretty-looking multiplication table going up to 12*12. While on my computer this solution works properly, the site does not accept it.
Can somebody help me out?
for i in range(1,13):
for j in range(1,13):
if j==1:
print i*j,
elif i>=10 and j==2:
print '{0:3}'.format(i*j),
else:
print '{0:4}'.format(i*j),
print
Here's a description of the challenge:
Print out the table in a matrix like fashion, each number formatted to a width of 4 (The numbers are right-aligned and strip out leading/trailing spaces on each line).
Print out the table in a matrix like fashion, each number formatted to a width of 4
(The numbers are right-aligned and strip out leading/trailing spaces on each line).
I think that following code may pass, according to the given rules. But it's only a guess
as I'm not playing on codeeval.
# python3 code, use from __future__ import print_function if you're using python2
for i in range(1,13):
for j in range(1,13):
print('{:4}'.format(i*j), end="")
print ("")
I guess your problem is that you're having a 5 alignment because you forgot that the print foo,
syntax in python 2 is adding a space. Also they say width of 4, whereas you tried to be smart, and
align accordingly to the size of the value.
edit: here's more details about what's wrong in your code, let's take two lines of your output:
1 2 3 4 5 6 7 8 9 10 11 12
10 20 30 40 50 60 70 80 90 100 110 120
AA␣BBB␣CCCC␣CCCC␣CCCC␣CCCC␣CCCC␣CCCC␣CCCC␣CCCC␣CCCC␣CCCC␣
so what your code is doing is:
if j==1: print i*j,
outputs the AA␣,
elif i>=10 and j==2:
print '{0:3}'.format(i*j),
outputs the BBB␣ and
else:
print '{0:4}'.format(i*j),
outputs the CCCC␣.
The ␣ is an extra space added by python because of the use of the , at the end of the print, to get that, see that snippet:
>>> def foo():
... print 1234,
... print 1234,
... print
...
>>> foo()
1234 1234
The format '{0:3}' right aligns the integer to the right as expected, but only with a padding of three, whereas the '{0:4}' does it according to the rules. But as you're adding an extra space at the end, it's not working as you're writing it. That's why it's better to use python3's print expression that makes it simpler, using the end keyword.
Print out the table in a matrix like fashion, each number formatted to a width of 4 (The numbers are right-aligned and strip out leading/trailing spaces on each line).
However, the output fails to meet this requirement which is made more visible by timing bars.
1 2 3 4 5 6 7 8 9 10 11 12^N
2 4 6 8 10 12 14 16 18 20 22 24^N
3 6 9 12 15 18 21 24 27 30 33 36^N
||||----||||----||||----||||----||||----||||----||||----
This correct padding for a "width of 4, right-aligned" should look like
1 2 3 4 5 6 7 8 9 10 11 12^N
||||++++||||++++||||++++||||++++||||++++||||++++
And then with "strip out leading/trailing spaces on each line" the correct result is
1 2 3 4 5 6 7 8 9 10 11 12^N
|++++||||++++||||++++||||++++||||++++||||++++
While the current incorrect output, with the timing bars for correct output looks like
1 2 3 4 5 6 7 8 9 10 11 12^N
|++++||||++++||||++++||||++++||||++++||||++++???????????

Python, printing two columns of numbers using for loop

I need some very basic help with Python 3.3. I'm trying to get a better understanding of formatting using a for loop and I want to simply print out the odd numbers from 1-20 in two columns.
Here is what I've tried:
for col1 in range(1,10,2):
for col2 in range(11,20,2):
print(col1,'\t',col2)
For some reason my output is very strange. The left column has the odd numbers from 1-10, but each number is listed five times before it goes to the next number
1 11
1 13
1 15
1 17
1 19
3 11
3 13
3 15
3 17
3 19
etc..
What i want is:
1 11
3 13
5 15
7 17
9 19
You should do it using zip:
for i,j in zip(range(1,10,2), range(11,20,2)):
print('{}\t{}'.format(i,j))
[OUTPUT]
1 11
3 13
5 15
7 17
9 19
When you use nested loops, the problem is that you are printing the second column for each number in the first column, which is not what you want. Instead, you want to iterate through them simultaneously. That is where zip comes in handy.
You do not need a second for-loop or zip here. Instead, all you need is this:
>>> for n in range(1, 10, 2):
... print(n, '\t', n + 10)
...
1 11
3 13
5 15
7 17
9 19
>>>
It works because the numbers in the second column are simply those in the first plus 10.

Can anyone help me figure out the parsing error in this code?

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 )

Categories

Resources