How to generate pyramid of numbers (using only 1-3) using Python? - python-3.x

I'm wondering how to create a pyramid using only element (1,2,3) regardless of how many rows.
For eg. Rows = 7 ,
1
22
333
1111
22222
333333
1111111
I've have tried creating a normal pyramid with numbers according to rows.
eg.
1
22
333
4444
55555
666666
Code that I tried to make a Normal Pyramid
n = int(input("Enter the number of rows:"))
for rows in range (1, n+1):
for times in range (rows):
print(rows, end=" ")
print("\n")

You need to adjust your ranges and use the modulo operator % - it gives you the remainer of any number diveded by some other number.Modulo 3 returns 0,1 or 2. Add 1 to get your desired range of values:
1 % 3 = 1
2 % 3 = 2 # 2 "remain" as 2 // 3 = 0 - so remainder is: 2 - (2//3)*3 = 2 - 0 = 2
3 % 3 = 0 # no remainder, as 3 // 3 = 1 - so remainder is: 3 - (3//3)*3 = 3 - 1*3 = 0
Full code:
n = int(input("Enter the number of rows: "))
print()
for rows in range (0, n): # start at 0
for times in range (rows+1): # start at 0
print( rows % 3 + 1, end=" ") # print 0 % 3 +1 , 1 % 3 +1, ..., etc.
print("")
Output:
Enter the number of rows: 6
1
2 2
3 3 3
1 1 1 1
2 2 2 2 2
3 3 3 3 3 3
See:
Modulo operator in Python
What is the result of % in Python?
binary-arithmetic-operations

A one-liner (just for the record):
>>> n = 7
>>> s = "\n".join(["".join([str(1+i%3)]*(1+i)) for i in range(n)])
>>> s
'1\n22\n333\n1111\n22222\n333333\n1111111'
>>> print(s)
1
22
333
1111
22222
333333
1111111
Nothing special: you have to use the modulo operator to cycle the values.
"".join([str(1+i%3)]*(1+i)) builds the (i+1)-th line: i+1 times 1+i%3 (thats is 1 if i=0, 2 if i=1, 3 if i=2, 1 if i=4, ...).
Repeat for i=0..n-1 and join with a end of line char.

Using cycle from itertools, i.e. a generator.
from itertools import cycle
n = int(input("Enter the number of rows:"))
a = cycle((1,2,3))
for x,y in zip(range(1,n),a):
print(str(x)*y)
(update) Rewritten as two-liner
from itertools import cycle
n = int(input("Enter the number of rows:"))
print(*[str(y)*x for x,y in zip(range(1,n),cycle((1,2,3)))],sep="\n")

Related

how to add a space before a line in python

I want to print 2 space before every line of my code's output.
My code:
n = int(input())
for row in range(1, n+1):
for column in range(1, n+1):
print(column, end=' ')
print('')
input:
5
My output:
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
The output I want:
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
Try this:
n = int(input())
for row in range(1, n+1):
for column in range(1, n+1):
print(' ',column, end=' ') # we print some whitespace in front of every character and at the end.
print('')
This code prints 2 spaces before and 1 space after, like the output that you want.
You can achieve this by putting the whitespace in before the column value:
n = int(input())
for row in range(1, n+1):
for column in range(1, n+1):
print(' ', column, end='')
print()
This also removes the extra whitespace that your existing solution puts on the end of each line (though if you wanted that back, simple add more space to the 2nd print - i.e. print(' '))
You can use the join method for strings:
n = int(input())
for row in range(1, n+1):
print( " " + " ".join([str(x) for x in range(1, n+1)]) )

Printing patterns using loop in python

My program read an integer number N, that correspond to the order of a Bidimentional array of integers, and build the Array according to the below example. I want to fill the middle elements like my expected output.
My code:
n = int(input())
for row in range(1, n+1):
for colum in range(1, n+1):
print(row, end=" ")
print()
Input:
5
My output:
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5
The output I want:
1 1 1 1 1
1 2 2 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1
I want to fill the middle elements like this. The height number at the middle then the second height number and so on..
for the "1-2-3-2-1" sequence, you can get it as the "minimum between row and n + 1 - row" - - min(row, n + 1 - row). (And the symmetrical for column) - and then
you print the min of this calculation for row and cols:
n = int(input())
for row in range(1, n+1):
for column in range(1, n+1):
mrow = min(row, n + 1 - row)
mcol = min(column, n + 1 - column)
print(min(mrow, mcol), end=" ")
print()
I hope this is not a homework question, but i will help you.
This can be done a lot more easily with lists!:
def cell_value(i, j, n_rows):
return min(
abs(i - -1),
abs(i - n_rows),
abs(j - -1),
abs(j - n_rows),
)
rows=int(input("Enter the number of rows:"))
row2 = [
[
cell_value(i, j, rows)
for j in range(rows)
]
for i in range(rows)
]
for r in row2:
print(*r)
Or it can be done even more easily like this below:
numberOfRows = int(input("Enter the number of rows:"))
listOut = [[1]*numberOfRows] * numberOfRows #grid of 1s of appropriate size
for j in range(int((numberOfRows+1)/2)): #symmetrical, so only look to the middle
if j > 0:
listOut[j] = list(listOut[j-1]) #copy previous row
for i in range(int((numberOfRows+1)/2)):
if i>=j:
listOut[j][i] = j+1
listOut[j][numberOfRows-(i+1)] = j+1
#copy current row to appropriate distance from the end
listOut[numberOfRows-(j+1)] = list(listOut[j])
for row in listOut:
print(row)
Both of the above programs give the SAME result
Enter the number of rows:5
1 1 1 1 1
1 2 2 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1
Note:this is only possible for odd numbers!
Let me know if you have any doubts...
Cheers!
enter image description here
`for i in range(n):
````print((n-i)*" ",end=" ")
````print((i+1)*"* ")

Printing Pattern in Python

1. The Problem
Given a positive integer n. Print the pattern as shown in sample outputs.
A code has already been provided. You have to understand the logic of the code on your own and try and make changes to the code so that it gives correct output.
1.1 The Specifics
Input: A positive integer n, 1<= n <=9
Output: Pattern as shown in examples below
Sample input:
4
Sample output:
4444444
4333334
4322234
4321234
4322234
4333334
4444444
Sample input:
5
Sample output:
555555555
544444445
543333345
543222345
543212345
543222345
543333345
544444445
555555555
2. My Answer
2.1 My Code
n=int(input())
answer=[[1]]
for i in range(2, n+1):
t=[i]*((2*i)-3)
answer.insert(0, t)
answer.append(t)
for a in answer:
a.insert(0,i)
a.append(i)
print(answer)
outlst = [' '.join([str(c) for c in lst]) for lst in answer]
for a in outlst:
print(a)
2.2 My Output
Input: 4
4 4 4 4 4 4 4 4 4
4 4 3 3 3 3 3 3 3 4 4
4 4 3 3 2 2 2 2 2 3 3 4 4
4 3 2 1 2 3 4
4 4 3 3 2 2 2 2 2 3 3 4 4
4 4 3 3 3 3 3 3 3 4 4
4 4 4 4 4 4 4 4 4
2.3 Desired Output
4444444
4333334
4322234
4321234
4322234
4333334
4444444
Your answer isn't as expected because you add the same object t to the answer list twice:
answer.insert(0, t)
answer.append(t)
More specifically, when you assign t = [i]*(2*i - 3), a new data structure is created, [i, ..., i], and t just points to that data structure. Then you put the pointer t in the answer list twice.
In the for a in answer loop, when you use a.insert(0, i) and a.append(i), you update the data structure a is pointing to. Since you call insert(0, i) and append(i) on both pointers that point to the same data structure, you effectively insert and append i to that data structure twice. That's why you end up with more digits than you need.
Instead, you could run the loop for a in answer for only the top half of the rows in the answer list (and the middle row that has was created without a pair). E.g. for a in answer[:(len(answer)+1)/2].
Other things you could do:
using literals as the arguments instead of reusing the reference, e.g. append([i]*(2*i-3)). The literal expression will create a new data structure every time.
using a copy in one of the calls, e.g. append(t.copy()). The copy method creates a new list object with a "shallow" copy of the data structure.
Also, your output digits are space-separated, because you used a non-empty string in ' '.join(...). You should use the empty string: ''.join(...).
n=5
answer=[[1]]
for i in range(2, n+1):
t=[i]*((2*i)-3)
answer.insert(0, t)
answer.append(t.copy())
for a in answer:
a.insert(0,i)
a.append(i)
answerfinal=[]
for a in answer:
answerfinal.append(str(a).replace(' ','').replace(',','').replace(']','').replace('[',''))
for a in answerfinal:
print(a)
n = int(input())
for i in range(1,n*2):
for j in range(1,n*2):
if i <= j<=n*2-i: print(n-i+1,end='')
elif i>n and i>=j >= n*2 -i : print(i-n+1,end='')
elif j<=n: print(n-j+1,end="")
else: print(j-n+1,end='')
print()
n = int(input())
k = 2*n - 1
for i in range(k):
for j in range(k):
a = i if i<j else j
a = a if a<k-i else k-i-1
a = a if a<k-j else k-j-1
print(n-a, end = '')
print()

To print a pattern in Python using 'for' loop

I tried various programs to get the required pattern (Given below). The program which got closest to the required result is given below:
Input:
for i in range(1,6):
for j in range(i,i*2):
print(j, end=' ')
print( )
Output:
1
2 3
3 4 5
4 5 6 7
5 6 7 8 9
Required Output:
1
2 3
4 5 6
7 8 9 10
Can I get some hint to get the required output?
Note- A newbie to python.
Store the printed value outside of the loop, then increment after its printed
v = 1
lines = 4
for i in range(lines):
for j in range(i):
print(v, end=' ')
v += 1
print( )
If you don't want to keep track of the count and solve this mathematically and be able to directly calculate any n-th line, the formula you are looking for is the one for, well, triangle numbers:
triangle = lambda n: n * (n + 1) // 2
for line in range(1, 5):
t = triangle(line)
print(' '.join(str(x+1) for x in range(t-line, t)))
# 1
# 2 3
# 4 5 6
# 7 8 9 10

why dynamic integer right align in python 3

What I am trying to do below in my code is just print all the types of number formats available in right aligned manner.
def print_formatted(number):
for i in range(1, n+1):
width = len(format(i, 'b'))
print("{0:d} {0:o} {0:x} {0:{w}b}".format(i, w=len(format(i, 'b'))))
if __name__ == '__main__':
n = int(input())
print_formatted(n)
Input:
4
Expected Output:
1 1 1 1
2 2 2 10
3 3 3 11
4 4 4 100
But actual output:
1 1 1 1
2 2 2 10
3 3 3 11
4 4 4 100
The above code works fine if I give a static value in-place of 'w' but if I pass dynamic changing value it is not working as expected. What am I missing here
Thanks in advance for your help.

Resources