I need to convert the elements of a matrix from str to int (after I read them from a file).
I don't want to use any external library.
This is what I produced so far and it's working, but I'm not happy with it (not very pythonic):
def str2int(matrix):
n = 1
m = 1
if type(matrix) is ListType:
n = len(matrix)
if type(matrix[0]) is ListType:
m = len(matrix[0])
new_matrix = []
i = 0
while i < n:
new_matrix.append([])
j = 0
while j < m:
new_matrix[i].append(int(matrix[i][j]))
j += 1
i += 1
return new_matrix
Any better ideas?
Thanks.
Use a list comprehension:
return [[int(i) for i in row] for row in matrix]
Related
This is a program to print a matrix whose sum of each row , column or diagonal elements are equal.
I have a working code but my program gives same output each time i run it. I need a program to print different matrix output for same input.
def matrix(n):
m = [[0 for x in range(n)]for y in range(n)]
i = n // 2
j = n - 1
num = 1
while num <= (n * n):
if i == -1 and j == n:
j = n - 2
i = 0
else:
if j == n:
j = 0
if i < 0:
i = n - 1
if m[int(i)][int(j)]:
j = j - 2
i = i + 1
continue
else:
m[int(i)][int(j)] = num
num = num + 1
j = j + 1
i = i - 1
print ("Sum of eggs in each row or column and diagonal : ",int(n*(n*n+1)/2),"\n")
for i in range(0, n):
for j in range(0, n):
print('%2d ' % (m[i][j]),end = '')
if j == n - 1:
print()
n=int(input("Number of rows of the matrix : "))
matrix(n)
I am unsure whether this is what you are looking for, but one solution is to add a random number to each value of the matrix, as this doesn't break the property
a matrix whose sum of each row, column or diagonal elements are equal.
Here is how you could do it:
add = random.randint(0, 50)
m = [[v+add for v in row] for row in m]
Moreover, you can rotate and add two magic squares without loosing their property. Therefore, you can rotate the magic square you have and add it to the original. This can add some nonlinearity to the results.
def rotate(m): # 90 degrees counter clockwise
return [[m[j][i] for j in range(len(m))] for i in range(len(m[0])-1, -1, -1)]
# add the matrix with its rotated version
m = list(map(lambda e: [sum(x) for x in zip(*e)], zip(m, rotate(m))))
I hope this helps!
In the excel Table I have following entires:
Now I import the entries of M[i][j] as follows:
M = [[0]* n[i] for i in range(nJobs)]
iter_i = 0
for i in range(nJobs):
if i != 0:
iter_i = iter_i+n[i-1]
for j in range(n[i]):
M[i][j] = DataSheet.cell(5 + j + iter_i, 5).value
Each element of M[i][j] is saved as a float, however I need them to be integers or list of integers (for cells with multiple numbers separated by a comma), since those elements are needed for iteration. Is there any way to convert each of the elements of M[i][j] to a list of integers?
Solved as follows:
M = [[0]* n[i] for i in range(nJobs)]
iter_i = 0
cellInfo = []
for i in range(nJobs):
if i != 0:
iter_i = iter_i+n[i-1]
for j in range(n[i]):
cellInfo = DataSheet.cell(5 + j + iter_i, 5).value
M[i][j] = [int(y) for y in cellInfo.split(",")]
I am working on a problem which takes a nums, row, column as parameters and returns a resultant matrix of size row x column.
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
count = 0
i = j = 0
m = [[0]*c]*r
for row in nums:
for val in row:
if j < c and i < r:
print(val,m[i][j], i, j)
m[i][j] = val
print(val,m[i][j], i, j)
count += 1
j += 1
if j == c:
i += 1
j = 0
if count == (r*c):
return m
else:
return nums
When I tested for input like ([[1,2],[3,4]], 4, 1) it generates output [[4],[4],[4],[4]] instead of [[1],[2],[3],[4]]
m = [[0]*c]*r
This creates a list of r references to the same inner list. So, whenever you modify m[0], you're also modifying m[1], and so on, because they're the same list.
You probably wanted something like this:
m = [[0 for _ in range(c)] for _ in range(r)]
[0]*4 gives you four copies of the same object, not four independent lists.
Try
m = [[0 for i in range(c)] for j in range(r)]
Here is my code:
NUM = 3
A = [1,5,6,2,8,4,3,2,5]
B = []
m = []
check = False
summ=0
n = len(A) / NUM
while check == False:
for i in A:
if A.index(i) >= n:
B.append(m)
m = []
n *= 2
m.append(i)
B.append(m)
for j in B:
s1=(sum(B[0]))
s2=(sum(B[1]))
s3=(sum(B[2]))
print(B)
if s1==s2==s3:
summ=s1
check = True
else:
B = [0] * len(A)
ilg = len(A)
B[0]=A[ilg-1]
for i in range(len(A)-1):
B[i+1] = A[i]
for i in range(len(A)):
A[i]=B[i]
What I am trying to do is to split my list into 3 lists and if sum of numbers in those lists are equal print sum out, if not print 'FALSE'.
For example: [1,2,3,4,5,6,7,8,9],
after split: [1,2,3],[4,5,6],[7,8,9]
but I am getting an error:
s1=[sum(B[0])] TypeError: 'int' object is not iterable
What I am doing wrong?
EDIT: Here what I have more, the part after else should change list from [1,5,6,2,8,4,3,2,5] to [5,1,5,6,2,8,4,3,2] and so on.
Your problem is this line:
B[0]=A[ilg-1]
You're assigning an integer to B[0], which is not an iterable object. On your second iteration around the loop, you pass B[0] to the sum function, which attempts to iterate over it, throwing the exception.
A = [1,5,6,2,8,4,3,2,5]
NUM = 3
n = len(A) / NUM
# here make sure that len(A) is a multiple of NUM
sums = [sum([item for item in A[i * NUM :(i + 1) * NUM]]) for i in range(n)]
# for python versions older than 3 use xrange instead of range.
for i in sums[1:]:
if i != sums[0]:
print "FALSE"
break
else:
print sums[0]
Because you're defining your range incorrectly. You want i to be your index, right? So use:
for i in np.arange(0, len(B)):
after importing numpy:
import numpy as np
Edit: Actually no package is needed, just: for i in range(0, len(B)):
I'm going to do Matrix Addition on Python.(Not finish). But it shows an error.
m, n = (int(i) for i in raw_input().split())
a = [[0 for i in range(m)] for j in range(n)]
b = [[0 for i in range(m)] for j in range(n)]
c = []
total = []
for i in range(m):
x = raw_input()
for j in range(n):
value = [int(i) for i in x.split()]
c[i][j] = a[i][j]
#c.append(value)
print a
for i in c:
print i
I want to input
3 3 <-- matrix dimensional m*n
1 2 3 >
3 2 1 > matrix A
1 3 2 >
1 1 1 >
1 1 1 > matrix B
1 1 1 >
and shows as
2 3 4 >
4 3 2 > matrix A + B
2 4 3 >
You are using i in your outer for loop, and it is an int. Then in the loop you have:
value = [int(i) for i in x.split()]
which makes i a string (which is what split returns). Maybe you think there is some sort of scoping inside [ ]? There isn't. You have a name collision, change one of them.
You are using same variable in inner for loop.
for i in range(m):
x = raw_input()
for j in range(n):
# variable i is refering to outer loop
value = [int(p) for p in x.split()]
c[i][j] = a[i][j]
#c.append(value)
print a
for i in c:
print i
Beyond the first two answers you'll have a problem with this statement:
c[i][j] = a[i][j]
When the loop starts i will be 0 and that's so far OK, but c is an empty list and has no iterable at the first position so c[0][0] will return an error.
Get rid of it and uncomment the following line:
#c.append(value)
EDIT:
Your code won't return what you want. You'd better make something like this to create a matrix with the given sides:
for i in range(m):
d = []
for j in range(n):
x = raw_input()
d.append(int(x))
c.append(d)
If you have 3 for both m and n, then you will create matrix with sides 3 x 3 saved in the variable c.
In this way you don't have to split the user input. The user can give a number at a time. And you could even change the following line:
x = raw_input()
to:
x = raw_input("{0}. row, {1}. column: ".format(i+1, j+1))
Try it out!
import time
m, n = (int(i) for i in raw_input().split())
a = []
b = []
total = [[0 for i in range(n)] for j in range(m)]
for i in range(m):
x = raw_input()
for j in range(n):
value = [int(i) for i in x.split()]
a.append(value)
#print a
for i in range(m):
x = raw_input()
for j in range(n):
value = [int(i) for i in x.split()]
b.append(value)
#print b
for i in range(m):
for j in range(n):
total[i][j] = a[i][j] + b[i][j]
for i in total:
print ' '.join(map(str, i))
time.sleep(2)
OK! I just figured it out! Thank you
you can also hit this error if you declare an int and treat it like a dict
>>> a = []
>>> a['foo'] = 'bar'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str