write a program that prints a nested loop in Python - 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

Related

I cant get my code to draw a number pattern with nested loops in Python that will align all number printouts in a neat manner

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

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

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

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