how to store python console output in python variable - python-3.x

below is my code :
def combinationUtil(arr, n, r,index, data, i):
if(index == r):
for j in range(r):
print(data[j], end = " ")
print(" ")
return
if(i >= n):
return
data[index] = arr[i]
combinationUtil(arr, n, r, index + 1, data, i + 1)
combinationUtil(arr, n, r, index, data, i + 1)
def printcombination(arr, n, r):
data = list(range(r))
combinationUtil(arr, n, r, 0, data, 0)
var = []
pp = 5
r = 3
arr = []
for i in range(1, pp+1):
arr.append(i)
n = len(arr)
printcombination(arr, n, r)
it gives me this output:
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
i want to save this output as a variable in python

You have a combination utility routine that produces the output of interest.
If you were calling someone else's routine, you might need to assign
sys.stdout to an io.StringIO() to capture the output.
But as it stands, you have control over the source code,
so you can easily replace
for j in range(r):
print(data[j], end=' ')
print(' ')
with the following more convenient interface:
yield [data[j] for j in range(r)]
Then iterate, e.g.:
for row in combinationUtil(arr, n, r, 0, list(range(r)), 0):
print(row)
Cf itertools.

Related

Palindrome Matrix for the given n number

Output ExampleHow do I create a 2*n+1 matrix as mentioned below:
Input:
1
Output:
1 2 1
2 1 2
1 2 1
Input:
2
Output:
1 2 3 2 1
2 3 1 3 2
3 1 2 1 3
2 3 1 3 2
1 2 3 2 1
I had this code written. Hope it helps, just create a first row and then use that as reference for adding new rows.
INPUT = 3
MATRIX_DIM = (2 * INPUT) + 1
palindorme_matrix = []
current_value = 1
current_row = []
for idx in range(MATRIX_DIM):
current_row.append(current_value)
if idx >= (INPUT):
current_value -= 1
else:
current_value += 1
palindorme_matrix.append(current_row)
for row in range(1, MATRIX_DIM):
new_row = current_row.copy()
for i in range(len(current_row)):
new_row[i] += 1
if new_row[i] > (INPUT + 1):
new_row[i] = 1
palindorme_matrix.append(new_row)
current_row = new_row.copy()
print("Palindrome Matrix ", palindorme_matrix)

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)*"* ")

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

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")

Need numbering above each column of a python grid

I need to modify a program the program 'x' so that it outputs the original grid, but each row and column is labeled with it's respective number. i.e. column 1 has a first, row 1 has a 1 first. I have figured out how to put numbering in front of the rows, but cannot figure out how to modify the program so that the columns are numbered.
'x'
import random
aGrid = []
SIZE = 10
for r in range (0,SIZE,1):
aGrid.append ([])
for c in range (0,SIZE,1):
element = random.randint(0,9)
aGrid[r].append (element)
for r in range (0,SIZE,1):
for c in range (0,SIZE,1):
print(aGrid[r][c], end="")
print()
Here is my attempt at getting numbering in front of the rows
import random
aGrid = []
SIZE = 11
for r in range (0,SIZE - 1,1):
aGrid.append ([])
aGrid[r].append (r )
aGrid[r].append (" ")
for c in range (0,SIZE + 1,1):
element = random.randint(0,9)
aGrid[r].append (element)
for r in range (0,SIZE - 1,1):
for c in range (0,SIZE + 1,1):
print(aGrid[r][c], end="")
print()
You don't need to change aGrid. Just print the row and column numbers in the print loop:
import random
aGrid = []
SIZE = 10
for r in range (SIZE):
aGrid.append ([])
for c in range (SIZE):
element = random.randint(0,9)
aGrid[r].append (element)
print(" ", end="")
for c in range (SIZE):
print(c, end="")
print()
for i, r in enumerate(range(SIZE)):
print(i, end="")
for c in range(SIZE):
print(aGrid[r][c], end="")
print()
Output:
0123456789
01958724133
17006217440
21488953544
35615572045
49849348546
54207744418
63316678723
76651582077
85713263320
91939404287
A version that starts counting from 1 and has some spaces for better readability:
import random
aGrid = []
SIZE = 10
for r in range (SIZE):
aGrid.append ([])
for c in range (SIZE):
element = random.randint(0,9)
aGrid[r].append (element)
print(" ", end=" ")
for c in range (1, SIZE + 1):
print(c, end=" ")
print()
for i, r in enumerate(range(SIZE), 1):
print('{:2d}'.format(i), end=" ")
for c in range(SIZE):
print(aGrid[r][c], end=" ")
print()
Output:
1 2 3 4 5 6 7 8 9 10
1 3 0 4 6 3 9 3 3 6 3
2 5 6 1 6 6 3 2 5 6 1
3 6 9 0 5 0 7 1 1 7 7
4 7 4 3 9 0 9 1 0 7 8
5 5 1 1 1 1 7 1 4 4 8
6 4 5 8 1 6 3 6 2 8 6
7 4 1 0 5 7 4 5 6 6 4
8 4 5 5 4 3 3 0 9 2 1
9 3 6 7 0 0 9 5 8 5 9
10 3 1 2 3 5 0 1 6 2 9

Resources