Palindrome Matrix for the given n number - python-3.x

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)

Related

what is the good way to add 1 in column values if value greater than 2 python

I want to add 1 in column values if column value is greater than 2
here is my dataframe
df=pd.DataFrame({'A':[1,1,1,1,1,1,3,2,2,2,2,2,2],'flag':[1,1,0,1,1,1,5,1,1,0,1,1,1]})
df_out
df=pd.DataFrame({'A':[1,1,1,1,1,1,3,2,2,2,2,2,2],'flag':[1,1,0,1,1,1,6,1,1,0,1,1,1]})
Use DataFrame.loc with add 1:
df.loc[df.A.gt(2), 'flag'] += 1
print (df)
A flag
0 1 1
1 1 1
2 1 0
3 1 1
4 1 1
5 1 1
6 3 6
7 2 1
8 2 1
9 2 0
10 2 1
11 2 1
12 2 1
Or:
df['flag'] = np.where(df.A.gt(2), df['flag'] + 1, df['flag'])
EDIT:
mean = df.groupby(pd.cut(df['x'], bins))['y'].transform('mean')
df['flag'] = np.where(mean.gt(2), df['y'] + 1, df['y'])
And then:
x= df.groupby(pd.cut(df['x'], bins))['y'].apply(lambda x:abs(x-np.mean(x)))

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

all possible steps by 1 or 2 to reach nth stair

I am working on a python program where I want to find all possible ways to reach nth floor.
Here is my program taken from here:
# A program to count the number of ways to reach n'th stair
# Recurssive program to find n'th fibonacci number
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
# returns no. of ways to reach s'th stair
def countWays(s):
return fib(s + 1)
# Driver program
s = 10
print("Number of ways = ", countWays(s) )
Here I am getting the total number of ways to reach nth floor, but I want a function that can return an array of all possible ways to reach nth floor.
Example:
1) s = 3 output should be the possible steps which are {1,1,1}, {2,1}, {1,2}.
2) s = 10, has 89 combinations:
1 1 1 1 1 1 1 1 1 1
2 1 1 1 1 1 1 1 1
1 2 1 1 1 1 1 1 1
1 1 2 1 1 1 1 1 1
2 2 1 1 1 1 1 1
1 1 1 2 1 1 1 1 1
2 1 2 1 1 1 1 1
1 2 2 1 1 1 1 1
1 1 1 1 2 1 1 1 1
2 1 1 2 1 1 1 1
1 2 1 2 1 1 1 1
1 1 2 2 1 1 1 1
2 2 2 1 1 1 1
1 1 1 1 1 2 1 1 1
2 1 1 1 2 1 1 1
1 2 1 1 2 1 1 1
1 1 2 1 2 1 1 1
2 2 1 2 1 1 1
1 1 1 2 2 1 1 1
2 1 2 2 1 1 1
1 2 2 2 1 1 1
1 1 1 1 1 1 2 1 1
2 1 1 1 1 2 1 1
1 2 1 1 1 2 1 1
1 1 2 1 1 2 1 1
2 2 1 1 2 1 1
1 1 1 2 1 2 1 1
2 1 2 1 2 1 1
1 2 2 1 2 1 1
1 1 1 1 2 2 1 1
2 1 1 2 2 1 1
1 2 1 2 2 1 1
1 1 2 2 2 1 1
2 2 2 2 1 1
1 1 1 1 1 1 1 2 1
2 1 1 1 1 1 2 1
1 2 1 1 1 1 2 1
1 1 2 1 1 1 2 1
2 2 1 1 1 2 1
1 1 1 2 1 1 2 1
2 1 2 1 1 2 1
1 2 2 1 1 2 1
1 1 1 1 2 1 2 1
2 1 1 2 1 2 1
1 2 1 2 1 2 1
1 1 2 2 1 2 1
2 2 2 1 2 1
1 1 1 1 1 2 2 1
2 1 1 1 2 2 1
1 2 1 1 2 2 1
1 1 2 1 2 2 1
2 2 1 2 2 1
1 1 1 2 2 2 1
2 1 2 2 2 1
1 2 2 2 2 1
1 1 1 1 1 1 1 1 2
2 1 1 1 1 1 1 2
1 2 1 1 1 1 1 2
1 1 2 1 1 1 1 2
2 2 1 1 1 1 2
1 1 1 2 1 1 1 2
2 1 2 1 1 1 2
1 2 2 1 1 1 2
1 1 1 1 2 1 1 2
2 1 1 2 1 1 2
1 2 1 2 1 1 2
1 1 2 2 1 1 2
2 2 2 1 1 2
1 1 1 1 1 2 1 2
2 1 1 1 2 1 2
1 2 1 1 2 1 2
1 1 2 1 2 1 2
2 2 1 2 1 2
1 1 1 2 2 1 2
2 1 2 2 1 2
1 2 2 2 1 2
1 1 1 1 1 1 2 2
2 1 1 1 1 2 2
1 2 1 1 1 2 2
1 1 2 1 1 2 2
2 2 1 1 2 2
1 1 1 2 1 2 2
2 1 2 1 2 2
1 2 2 1 2 2
1 1 1 1 2 2 2
2 1 1 2 2 2
1 2 1 2 2 2
1 1 2 2 2 2
2 2 2 2 2
Update:
I found this working code in Java, I am not able to understand how do I change this to python
public static void main(String args[]) {
int s = 10;
List<Integer> vals = new ArrayList<>();
ClimbWays(s, 0, new int[s], vals);
vals.sort(null);
System.out.println(vals);
}
public static void ClimbWays(int n, int currentIndex, int[] currectClimb, List<Integer> vals) {
if (n < 0)
return;
if (n == 0) {
vals.add(currentIndex);
int last = 0;
for (int i = currentIndex - 1; i >= 0; i--) {
int current = currectClimb[i];
int res = current - last;
last = current;
System.out.print(res + " ");
}
System.out.println();
return;
}
currectClimb[currentIndex] = n;
ClimbWays(n - 1, currentIndex + 1, currectClimb, vals);
ClimbWays(n - 2, currentIndex + 1, currectClimb, vals);
}
It seems like you are looking for a modification of the partitions of a number:
import itertools as it
def partitions(n, I=1):
yield (n,)
for i in range(I, n//2 + 1):
for p in partitions(n-i, i):
yield (i,) + p
def countWays(s):
for i in partitions(s):
if s in i: continue # just the original number
yield from set(it.permutations(i)) # set to remove duplicates
print(list(countWays(3)))
Displays:
[(1, 2), (2, 1), (1, 1, 1)]
Note that this will return them in no particularly sorted order.
(Partitions algorithm from here.)
Here is a conversion of your java code into python:
def climbWays(n, currentIndex, currentClimb, vals):
if n < 0:
return
if n == 0:
vals.append(currentIndex)
last = 0
for i in range(currentIndex - 1, -1, -1):
current = currentClimb[i]
res = current - last
last = current
print(res, end=" ")
print()
return
currentClimb[currentIndex] = n
climbWays(n - 1, currentIndex + 1, currentClimb, vals)
climbWays(n - 2, currentIndex + 1, currentClimb, vals)
s = 10
vals = []
climbWays(s, 0, [0] * s, vals)
vals.sort()
print(vals)

How can I define m loops inside each other automatically to generate a n^m row table with all unique combinations?

There are m states that each n items can have, we can code n loops inside each other with m iterations, but the problem is that we need add another loop when n changed to n+1...
the table that i want to generate for n=3, m=2 is as follows:
m = 2
n = 3
for i in range(m):
for j in range(m):
for k in range(m):
print(i+1, j+1, k+1)
1 1 1
1 1 2
1 2 1
1 2 2
2 1 1
2 1 2
2 2 1
2 2 2
when n = 4, m = 2
for i in range(2):
for j in range(2):
for k in range(2):
for l in range(2):
print(i+1, j+1, k+1, l+1)
1 1 1 1
1 1 1 2
1 1 2 1
1 1 2 2
1 2 1 1
1 2 1 2
1 2 2 1
1 2 2 2
2 1 1 1
2 1 1 2
2 1 2 1
2 1 2 2
2 2 1 1
2 2 1 2
2 2 2 1
2 2 2 2
how can write a code that can work with any m and n values?
If you use the correct tool for the job (in this case itertools.product) then you get a dynamic solution:
from itertools import product
m = 2
n = 3
print('\n'.join(' '.join(map(str, prod)) for prod in product(range(1, m + 1), repeat=n)))
Outputs
1 1 1
1 1 2
1 2 1
1 2 2
2 1 1
2 1 2
2 2 1
2 2 2
Now in case something changes all that needs to be changed are the values of m and n.

how to store python console output in python variable

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.

Resources