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.
Related
How do I make a 3x5 grid out of a list containing 15 items/strings?
I have a list containing 15 symbols but it could very well also just be a list such as mylist = list(range(15)), that I want to portray in a grid with 3 rows and columns. How does that work without importing another module?
I've been playing around with the for loop a bit to try and find a way but it's not very intuitive yet so I've been printing long lines of 0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 etc I do apologize for this 'dumb' question but I'm an absolute beginner as you can tell and I don't know how to move forward with this simple problem
This is what I was expecting for an output, as I want to slowly work my way up to making a playing field or a tictactoe game but I want to understand portraying grids, lists etc as best as possible first
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
A mxn Grid? There are multiple ways to do it. Print for every n elements.
mylist = list(range(15))
n = 5
chunks = (mylist[i:i+n] for i in range(0, len(mylist), n))
for chunk in chunks:
print(*chunk)
Gives 3x5
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
Method 2
If you want more cosmetic then you can try
Ref
pip install tabulate
Code
mylist = list(range(15))
wrap = [mylist[x:x+5] for x in range(0, len(mylist),5)]
from tabulate import tabulate
print(tabulate(wrap))
Gives #
-- -- -- -- --
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
-- -- -- -- --
I'm supposed to create code that will simulate a d20 sided dice rolling 25 times using np.random.choice.
I tried this:
np.random.choice(20,25)
but this still includes 0's which wouldn't appear on a dice.
How do I account for the 0's?
Use np.arange:
import numpy as np
np.random.seed(42) # for reproducibility
result = np.random.choice(np.arange(1, 21), 50)
print(result)
Output
[ 7 20 15 11 8 7 19 11 11 4 8 3 2 12 6 2 1 12 12 17 10 16 15 15
19 12 20 3 5 19 7 9 7 18 4 14 18 9 2 20 15 7 12 8 15 3 14 17
4 18]
The above code draws numbers from 0 to 20 both inclusive. To understand why, you could check the documentation of np.random.choice, in particular on the first argument:
a : 1-D array-like or int
If an ndarray, a random sample is generated from its elements. If an
int, the random sample is generated as if a was np.arange(n)
np.random.choice() takes as its first argument an array of possible choices (if int is given it works like np.arrange), so you can use list(range(1, 21)) to get the output you want
+1
np.random.choice(20,25) + 1
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.
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
|++++||||++++||||++++||||++++||||++++||||++++???????????
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 )