Print a number table in a simple format - python

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

Related

Matrix Rotation in Python

In this Program I need to rotate the matrix by one element in clockwise direction.I had done with the code but I have a problem with removing the newlione in the the last row in the given Matrix. In this Program the user has to give the input. The code is
def rotate(m):
if not len(m):
return
top=0
bottom=len(m)-1
left=0
right=len(m[0])-1
while(left<right and top < bottom):
prev=m[top+1][left]
for i in range(left,right+1):
curr=m[top][i]
m[top][i]=prev
prev=curr
top+=1
for i in range(top,bottom+1):
curr=m[i][right]
m[i][right]=prev
prev=curr
right-=1
for i in range(right,left-1,-1):
curr=m[bottom][i]
m[bottom][i]=prev
prev=curr
bottom-=1
for i in range(bottom,top-1,-1):
curr=m[i][left]
m[i][left]=prev
prev=curr
left+=1
return m
def printMatrix(m):
for row in m:
print(' '.join(str(n) for n in row))
n = int(input())
m = []
for i in range(1,n+1):
l = list(map(int, input ().split ()))
m.append(l)
marix=rotate(m)
printMatrix(m)
The Test Case is given Below
Input
4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Expected Output:
5 1 2 3\n
9 10 6 4\n
13 11 7 8\n
14 15 16 12
Actual Output Which i get:
5 1 2 3\n
9 10 6 4\n
13 11 7 8\n
14 15 16 12\n
This is just an issue with your printMatrix() function, print() by defaults adds a newline. You could replace it with below to eliminate the last newline (though I'm not sure why this is so critical):
def printMatrix(m):
print('\n'.join(' '.join(str(n) for n in row) for row in m), end='')

Wrong string formatting?

Here's the program:
layout = "{0:>5}"
layout += "{1:>10}"
for i in range(2, 13):
layout += "{"+str(i)+":9>}"
index = []
for i in range(13):
index.append(i)
index = tuple(index)
print(layout.format(*index))
and it prints out like this:
0 123456789101112
but I want it to look something like this(number of spaces might be wrong):
0 1 2 3 4 5 6 7 8 9 10 11 12
What did I do wrong?
":9>}"
should be
":>9}"
This gives:
0 1 2 3 4 5 6 7 8 9 10 11 12
To look exactly like what you ask:
Actually, you're asking for something weird, but here's a more succint way to write what you wrote:
layout = "{0:>5}{1:>5}" + ''.join("{" + str(i) + ":>4}" for i in range(2, 13))
print(layout.format(*range(13)))
Gives:
0 1 2 3 4 5 6 7 8 9 10 11 12

write a program that prints a nested loop in Python

I'm trying to print a nested loops that looks like this:
1 2 3 4
5 6 7 8
9 10 11 12
This is what I have so far:
def main11():
for n in range(1,13)
print(n, end=' ')
however, this prints the numbers in one line: 1 2 3 4 5 6 7 8 9 10 11 12
You can do that using string formatting:
for i in range(1,13):
print '{:2}'.format(i),
if i%4==0: print
[OUTPUT]
1 2 3 4
5 6 7 8
9 10 11 12
Modulus Operator (%)
for n in range(1,13):
print(n, end=' ')
if n%4 == 0:
print
for offset in range(3):
for i in range(1,5):
n = offset*4 + i
print(n, end=' ')
print()
Output:
1 2 3 4
5 6 7 8
9 10 11 12
Or if you want it nicely formatted the way you have in your post:
for offset in range(3):
for i in range(1,5):
n = offset*4 + i
print("% 2s"%n, end=' ')
print()
Output:
1 2 3 4
5 6 7 8
9 10 11 12
Most of the time when you write a for loop, you should check if this is the right implementation.
From the requirements you have, I would write something like this:
NB_NB_INLINE = 4
MAX_NB = 12
start = 1
while start < MAX_NB:
print( ("{: 3d}" * NB_NB_INLINE).format(*tuple( j+start for j in range(NB_NB_INLINE))) )
start += NB_NB_INLINE

Number Pyramid Nested for Loop

I'm wondering if you could help me out. I'm trying to write a nested for loop in Python 3 that displays a number pyramid that looks like;
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
Can anybody help me out? It would be much appreciated!
This is what I have so far:
col = 1
for i in range(-1, 18, col*2):
for j in range(1, 0, 1):
print(" ", end = "")
for j in range(i, 0, -2):
print(j, end = " ")
print()
So, I can only get half of the pyramid to display.
I guess the main problems I'm having is:
How do i get the output to display an increasing and then decreasing value (ie. 1, 2, 4, 2, 1)?
An alternate way using list comprehensions.
Always break the problem down into digestable chunks. Each line is a mirror of itself, so lets just deal with first making out set of numbers we need.
This generates a list of strings that hold all powers of two which is what this is generating
lines = []
for i in range(1,9):
lines.append([str(2**j) for j in range(i)])
But if we just print this list, a) its going to only have half, and b) its going to mush the numbers together. We need to buffer the numbers with spaces. Fortunately, the last row will have the largest digits for any column, so:
Firstly, how long does each line need to end up being (we need this later) and also, what is the longest number in each column. We can use len as we cast the numbers to strings above.
b = len(lines[-1])
buffers = [len(x) for x in lines[-1]]
Now I have everything I need to print the strings (we stopped using numbers above):
So, for each line, find out how long it is, and expand the array it to the length of the longest line by filling the left of the array with empty strings (for this we're still pretending we're only printing the left half of the triangle):
for line in lines:
l = len(line)
line = [" "]*(b-len(line)) + line
With each line now buffered, we'll make a new array that we will print from. By zip()ing together the line and the buffer, we can easily right justify (String.rjust()) numberic strings, expanded out to the length required.
out = []
for x,y in zip(line,buffers):
out.append(x.rjust(y))
Remmeber until now, we've still just been working with the left half of the pyramid. So we take the output array, reverse it (array[::-1]) and then take every element but the first (array[1:]) and join it all together with a string and print it out.
print(" ".join(out+out[::-1][1:]))
Voila! The completed code:
lines = []
for i in range(1,9):
lines.append([str(2**j) for j in range(i)])
b = len(lines[-1])
buffers = [len(x) for x in lines[-1]]
for line in lines:
l = len(line)
line = [" "]*(b-len(line)) + line
out = []
for x,y in zip(line,buffers):
out.append(x.rjust(y))
print(" ".join(out+out[::-1][1:]))
Output:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
height = 8
maxHeight = height - 1
for i in range(height):
k, Max = 1, i * 2 + 1
print(maxHeight * " ", end="")
maxHeight -= 1
for j in range(Max):
print("%5d" % k, end="")
if (j < (Max // 2)):
k *= 2
else:
k //= 2
print()
Output:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
This could be the other 9 line solution.
Generate power of two's numbers as series
Find the offset need to add in each rows
Print the empty space for the each row before printing the palindromic list.
Ie. (offset * (n - i)) times " "(empty space)
Build palindromic series by slice operation ie. temp + temp[::-1][1:]
Print the palindromic series and offset spaces relative to the length of the number you are printing.
Code:
n = 8
numbers = [2**x for x in range(n)] # Generate interseted series.
offset = len(str(numbers[-1:])) -1 # Find the max offset for the tree.
for i in range(1, n+1): # Iterate n times. 1 to n+1 helps eazy slicing.
temp = numbers[:i] # Slice series to get first row numbers.
print(' ' * (offset * (n - i)), end=" ") # Prefix spaces, multiples of offset.
for num in temp + temp[::-1][1:]: # Generate palindromic series for the row.
print(num, end=" " * (offset - len(str(num)))) # Adjust offset for the number.
print('')
output:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1

Aligning items from 2 lists(simple python)

I was wondering how I could align every item in one list, to the corresponding index in the second list. Here is my code so far:
letters=['a','ab','abc','abcd','abcde','abcdef','abcdefg','abcdefgh','abcdefghi','abcdefghij']
numbers=[1,2,3,4,5,6,7,8,9,10]
for x in range(len(letters)):
print letters[x]+"----------",numbers[x]
This is the output I get:
a---------- 1
ab---------- 2
abc---------- 3
abcd---------- 4
abcde---------- 5
abcdef---------- 6
abcdefg---------- 7
abcdefgh---------- 8
abcdefghi---------- 9
abcdefghij---------- 10
This is the output I want:
a---------- 1
ab--------- 2
abc-------- 3
abcd------- 4
abcde------ 5
abcdef----- 6
abcdefg---- 7
abcdefgh--- 8
abcdefghi-- 9
abcdefghij- 10
You could use string formatting:
for left, right in zip(letters, numbers):
print '{0:-<12} {1}'.format(left, right)
And the output:
a----------- 1
ab---------- 2
abc--------- 3
abcd-------- 4
abcde------- 5
abcdef------ 6
abcdefg----- 7
abcdefgh---- 8
abcdefghi--- 9
abcdefghij-- 10
Something like this using string.formatting:
def solve(letters,numbers):
it=iter(range( max(numbers) ,0,-1))
for x,y in zip(letters,numbers):
print "{0}{1} {2}".format(x,"-"*next(it),y)
....:
In [38]: solve(letters,numbers)
a---------- 1
ab--------- 2
abc-------- 3
abcd------- 4
abcde------ 5
abcdef----- 6
abcdefg---- 7
abcdefgh--- 8
abcdefghi-- 9
abcdefghij- 10
letters=['a','ab','abc','abcd','abcde','abcdef','abcdefg','abcdefgh','abcdefghi','abcdefghij']
for c,x in enumerate(letters, start=1):
print x+("-"*(10-c))+" %s" % c
a--------- 1
ab-------- 2
abc------- 3
abcd------ 4
abcde----- 5
abcdef---- 6
abcdefg--- 7
abcdefgh-- 8
abcdefghi- 9
abcdefghij 10
letters=['a','ab','abc','abcd','abcde','abcdef','abcdefg','abcdefgh','abcdefghi','abcdefghij']
numbers=[1,2,3,4,5,6,7,8,9,10]
for x in range(len(letters)):
print '{0:11}{1}'.format(letters[x],numbers[x]).replace(' ','-');
a----------1
ab---------2
abc--------3
abcd-------4
abcde------5
abcdef-----6
abcdefg----7
abcdefgh---8
abcdefghi--9
abcdefghij-10

Categories

Resources