I have a matrix in Python defined like this:
matrix = [['A']*4 for i in range(4)]
How do I print it in the following format:
0 1 2 3
0 A A A A
1 A A A A
2 A A A A
3 A A A A
>>> for i, row in enumerate(matrix):
... print i, ' '.join(row)
...
0 A A A A
1 A A A A
2 A A A A
3 A A A A
I guess you'll find out how to print out the first line :)
Something like this:
>>> matrix = [['A'] * 4 for i in range(4)]
>>> def solve(mat):
print " ", " ".join([str(x) for x in xrange(len(mat))])
for i, x in enumerate(mat):
print i, " ".join(x) # or " ".join([str(y) for y in x]) if elements are not string
...
>>> solve(matrix)
0 1 2 3
0 A A A A
1 A A A A
2 A A A A
3 A A A A
>>> matrix = [['A'] * 5 for i in range(5)]
>>> solve(matrix)
0 1 2 3 4
0 A A A A A
1 A A A A A
2 A A A A A
3 A A A A A
4 A A A A A
This function matches your exact output.
>>> def printMatrix(testMatrix):
print ' ',
for i in range(len(testMatrix[1])): # Make it work with non square matrices.
print i,
print
for i, element in enumerate(testMatrix):
print i, ' '.join(element)
>>> matrix = [['A']*4 for i in range(4)]
>>> printMatrix(matrix)
0 1 2 3
0 A A A A
1 A A A A
2 A A A A
3 A A A A
>>> matrix = [['A']*6 for i in range(4)]
>>> printMatrix(matrix)
0 1 2 3 4 5
0 A A A A A A
1 A A A A A A
2 A A A A A A
3 A A A A A A
To check for single length elements and put an & in place of elements with length > 1, you could put a check in the list comprehension, the code would change as follows.
>>> def printMatrix2(testMatrix):
print ' ',
for i in range(len(testmatrix[1])):
print i,
print
for i, element in enumerate(testMatrix):
print i, ' '.join([elem if len(elem) == 1 else '&' for elem in element])
>>> matrix = [['A']*6 for i in range(4)]
>>> matrix[1][1] = 'AB'
>>> printMatrix(matrix)
0 1 2 3 4 5
0 A A A A A A
1 A AB A A A A
2 A A A A A A
3 A A A A A A
>>> printMatrix2(matrix)
0 1 2 3 4 5
0 A A A A A A
1 A & A A A A
2 A A A A A A
3 A A A A A A
a=[["A" for i in range(4)] for j in range(4)]
for i in range(len(a)):
print()
for j in a[i]:
print("%c "%j,end='')
it will print like this:
A A A A
A A A A
A A A A
A A A A
Use pandas for showing any matrix with indices:
>>> import pandas as pd
>>> pd.DataFrame(matrix)
0 1 2 3
0 A A A A
1 A A A A
2 A A A A
3 A A A A
Related
I cannot find a solution for this very specific problem I have.
In essence, I have two lists with two elements each: [A, B] and [1,2]. I want to create a nested loop that iterates and expands on the second list and adds each element of first list after each iteration.
What I want to see in the end is this:
A B
1 A
1 B
2 A
2 B
1 1 A
1 2 A
2 1 A
2 2 A
1 1 B
1 2 B
2 1 B
2 2 B
1 1 1 A
1 1 2 A
...
My problem is that my attempt at doing this recursively splits the A and B apart so that this pattern emerges (note the different first line, too):
A
1 A
2 A
1 1 A
1 2 A
2 1 A
2 2 A
1 1 1 A
1 1 2 A
...
B
1 B
2 B
1 1 B
1 2 B
2 1 B
2 2 B
1 1 1 B
1 1 2 B
...
How do I keep A and B together?
Here is the code:
def second_list(depth):
if depth < 1:
yield ''
else:
for elements in [' 1 ', ' 2 ']:
for other_elements in list (second_list(depth-1)):
yield elements + other_elements
for first_list in [' A ', ' B ']:
for i in range(0,4):
temp=second_list(i)
for temp_list in list(temp):
print temp_list + first_list
I would try something in the following style:
l1 = ['A', 'B']
l2 = ['1', '2']
def expand(l1, l2):
nl1 = []
for e in l1:
for f in l2:
nl1.append(f+e)
yield nl1[-1]
yield from expand(nl1,l2)
for x in expand(l1, l2):
print (x)
if len(x) > 5:
break
Note: the first line of your output does not seem to be the product of the same rule, so it is not generated here, you can add it, if you want, manually.
Note2: it would be more elegant not to build the list of the newly generated elements, but then you would have to calculate them twice.
matrix = []
for index, value in enumerate(['A','C','G','T']):
matrix.append([])
matrix[index].append(value + ':')
for i in range(len(lines[0])):
total = 0
for sequence in lines:
if sequence[i] == value:
total += 1
matrix[index].append(total)
unity = ''
for i in range(len(lines[0])):
column = []
for row in matrix:
column.append(row[1:][i])
maximum = column.index(max(column))
unity += ['A', 'C', 'G', 'T'][maximum]
print("Unity: " + unity)
for row in matrix:
print(' '.join(map(str, row)))
OUTPUT:
Unity: GGCTACGC
A: 1 2 0 2 3 2 0 0
C: 0 1 4 2 1 3 2 4
G: 3 3 2 0 1 2 4 1
T: 3 1 1 3 2 0 1 2
With this code I get this matrix but I want to form the matrix like this:
A C G T
G: 1 0 3 3
G: 2 1 3 1
C: 0 4 2 1
T: 2 2 0 3
A: 3 1 1 2
C: 2 3 2 0
G: 0 2 4 1
C: 0 4 1 2
But I don't know how. I hope someone can help me. Thanks already for the answers.
The sequences are:
AGCTACGT
TAGCTAGC
TAGCTACG
GCTAGCGC
TGCTAGCC
GGCTACGT
GTCACGTC
You're needing to do a transpose of your matrix. I've added comments in the code below to explain what has been changed to make the table.
matrix = []
for index, value in enumerate(['A','C','G','T']):
matrix.append([])
# Don't put colons in column headers
matrix[index].append(value)
for i in range(len(lines[0])):
total = 0
for sequence in lines:
if sequence[i] == value:
total += 1
matrix[index].append(total)
unity = ''
for i in range(len(lines[0])):
column = []
for row in matrix:
column.append(row[1:][i])
maximum = column.index(max(column))
unity += ['A', 'C', 'G', 'T'][maximum]
# Tranpose matrix
matrix = list(map(list, zip(*matrix)))
# Print header with tabs to make it look pretty
print( '\t'+'\t'.join(matrix[0]))
# Print rows in matrix
for row,unit in zip(matrix[1:],unity):
print(unit + ':\t'+'\t'.join(map(str, row)))
The following will be printed:
A C G T
G: 1 0 3 3
G: 2 1 3 1
C: 0 4 2 1
T: 2 2 0 3
A: 3 1 1 2
C: 2 3 2 0
G: 0 2 4 1
C: 0 4 1 2
I think that the best way is to convert your matrix to pandas dataframe and to then use transpose function.
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.transpose.html
I have an array
arr = [1,2,3, ..., N]
and a list of windows (of length N)
windows = [2,2,1, ...]
Is it possible to do a rolling sum computation on arr with the time varying windows stored in windows?
For example at t=3, you have arr=[1,2,3] and window=1 so this would indicate returning a 1 day rolling sum such that out[2] = 3
At t=2, you have arr = [1,2] and window=2 so this would indicate a 2 day rolling sum such that out[1]=3
I can not grantee the speed , but it will achieve what you need
df['New']=np.clip(df.index-df.windows+1,a_min=0,a_max=None)
df
Out[626]:
val windows New
0 1 2 0
1 2 2 0
2 3 1 2
3 4 1 3
4 5 3 2
df.apply(lambda x : df.iloc[x['New']:x.name+1,0].sum(),1)
Out[630]:
0 1
1 3
2 3
3 4
4 12
dtype: int64
This might be what you are after:
arr = [1,2,3]
windows = [2,2,1]
out = [0,0,0]
for t, i in enumerate(windows):
newarr = arr[:t+1]
out[t] = sum(newarr[:-(i+1):-1])
print('t = ' + str(t+1))
print('arr = ' + str(newarr))
print('out[' + str(t) + '] = ' + str(out[t]))
print('\n')
Gives:
t = 1
arr = [1]
out[0] = 1
t = 2
arr = [1, 2]
out[1] = 3
t = 3
arr = [1, 2, 3]
out[2] = 3
I have
for i in range(0, 11): print i, "\n", i
I'd like my python program to print this way for each for loop
1st loop:
1
1
2nd loop:
1
2
2
1
3rd loop:
1
2
3
3
2
1
I've tried using \r\n or \033[1A but they just overwrite the previous line. Is there a way I can "push" the outputted line down so I don't overwrite it?
One way to do this,
def foo(x, limit):
if x < limit :
print x
foo(x + 1, limit)
print x
foo(1, 11)
It's not possible to do it in 1 for loop as you're currently trying.
As I suggested, you can do it like this by using lists
>>> l1 = []
>>> l2 = []
>>> for i in range(0, 11):
... l1.append(i)
... l2 = [i] + l2
>>> l1.extend(l2)
>>> for i in l1:
... print i
0
1
2
3
4
5
6
7
8
9
10
10
9
8
7
6
5
4
3
2
1
0
Concatenation of two list generators.
>>> ladder = [x for x in range(5)] + [x for x in range(5,-1,-1)]
>>> ladder
[0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0]
>>> for x in ladder:
... print x
...
0
1
2
3
4
5
4
3
2
1
0
>>>
one of ways to solve this
def two_side_print(start, end):
text = [str(i) for i in range(start,end)]
print '\n'.join(text), '\n', '\n'.join(reversed(text))
two_side_print(1, 11)
Another option is to save the printed values in a list and print that list in reverse order in each loop iteration.
My suggestion:
l = []
for i in range(1, 5):
print 'Loop '+str(i) # This is to ease seeing the printing results
for val in l:
print val
print i
l.insert(len(l),i)
for val in reversed(l):
print val
The output for a loop iterating from 0 to 5:
Loop 1
1
1
Loop 2
1
2
2
1
Loop 3
1
2
3
3
2
1
Loop 4
1
2
3
4
4
3
2
1
I hope this is what you are looking for.
You can use a recursive function to help here:
def print_both_ways(start, end):
print(start)
if start != end:
print_both_ways(start+1, end)
print(start)
Usage:
print_both_ways(1,3) # prints 1,2,3,3,2,1 on separate lines
I'm trying to create a triangle like the following:
1 2 3 4 5 6
2 3 4 5 6
3 4 5 6
4 5 6
5 6
6
Without using while, for in, lists, etc. Just "if-else" cases and recursive functions. I've just learned how to do an asterisk triangle.
def triangle(i, t=0):
if i == 0:
return ' '
else:
print '*' * i
return triangle( i - 1, t + 1 )
triangle(6)
It has the same idea I want to apply to my exercise, but I really don't know how to do with the code for changing term by term and print them all to the right like this one.
Here is my solution. Note that there is neither range nor join, which implies for or list
In [1]: def tri(size, row = 0, col = 0):
...: if row < size:
...: num = row + col + 1
...: if num == size + 1:
...: print '\n',
...: tri(size, row + 1, 0)
...: if num <= size:
...: print num, '',
...: tri(size, row, col + 1)
...:
In [2]: tri(6)
1 2 3 4 5 6
2 3 4 5 6
3 4 5 6
4 5 6
5 6
6
If range is acceptable, then here is a short one:
def tri2(size):
row = map(str, range(1, size + 1))
print '\n'.join(map(lambda n: ' '.join(row[n:]), range(size)))
You can use range() or xrange() to get the list of numbers, and decrease the range with each recursion:
def triangle(i, t):
if i == t:
return i
else:
print " ".join([str(x) for x in range(i,t+1)])
return triangle( i + 1, t )
output:
>>> triangle(1,6)
1 2 3 4 5 6
2 3 4 5 6
3 4 5 6
4 5 6
5 6
6
>>> triangle(1,8)
1 2 3 4 5 6 7 8
2 3 4 5 6 7 8
3 4 5 6 7 8
4 5 6 7 8
5 6 7 8
6 7 8
7 8
8
By calling the function recursively You have realized a kind of loop.
Now you can replicate the same idea:
def OneLess(i,j):
print i,
if i < j:
OneLess(i+1,j)
else:
print ""
def triangle(i, t=1):
OneLess(t,i)#print '*' * i
if i == t:
return ' '
return triangle( i , t + 1 )
triangle(6)
I'd suggest something like this:
def triangle(i, t = 1):
if i > 0:
print ' '.join([str(n+t) for n in range(i)])
triangle( i - 1, t + 1 )
The range gives you a list of the numbers needed at each level, and the t offset is increased by one so you're starting from a higher value each level you go down.
Update
I've just noticed your requirement for no for in and lists, which probably makes the above example wrong. So here is another suggestion using only recursion:
def triangle(size, col = 1, row = 1):
if col < size:
print col,
triangle(size, col+1, row)
else:
print col
if row < size:
triangle(size, row+1, row+1)