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(",")]
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!
I Wrote the program of Merge sort and while copying arrays i am getting error of list index out of range while assigning values to new array at L[i] = A[p+i]
A = [1,2,6,8,3,4,5,7]
# p = 0,r = 7 ,q = 3
def Merge(A,p,q,r):
n1 = q - p
n2 = r - q
L = []
R = []
for i in range(n1):
L[i] = A[p+i]
for i in range(n2):
R[i] = A[q+i]
i = 0
j = 0
Array = []
for x in range(p,r):
if L[i] < R[j]:
Array[x] = L[i]
i = i +1
else:
Array[x] = R[j]
j = j +1
Merge(A,0,3,7)
Your L and R arrays are empty and you try to access L[i] and R[i] in the for loop. This leads to the index error. Try to initialize the array first to access its index.
So I have this code in python and currently it only returns the maximum value for cutting a rod. How can I modify this to also give me where the cuts were made? It takes a list of prices whose indices+1 correspond to the value of the rod at each length, and n, for length of the rod.
the problem:http://www.radford.edu/~nokie/classes/360/dp-rod-cutting.html
def cutRod(price, n):
val = [0 for x in range(n+1)]
val[0] = 0
for i in range(1, n+1):
max_val = 0
for j in range(i):
max_val = max(max_val, price[j] + val[i-j-1])
val[i] = max_val
return val[n]
If this is the question : Rod cutting
Assuming code works fine, You will have to add a condition instead of Max operation to check which of two was picked and push that one in an array :
def cutRod(price, n):
val = [0 for x in range(n+1)]
val[0] = 0
output = list()
for i in range(1, n+1):
max_val = 0
cur_max_index = -1
for j in range(i):
cur_val = price[j] + val[i-j-1]
if(cur_val>max_val):
max_val = cur_val #store current max
cur_max_index = j #and index
if cur_max_index != -1:
output.append(cur_max_index) #append in output index list
val[i] = max_val
print(output) #print array
return val[n]
I know this is old but just in case someone else has a look...I was actually just looking at this problem. I think the issue is here that these dp problems can be tricky when handling indices. The previous answer is not going to print the solution correctly simply because this line needs to be adjusted...
cur_max_index = j which should be cur_max_index = j + 1
The rest...
def cut_rod(prices, length):
values = [0] * (length + 1)
cuts = [-1] * (length + 1)
max_val = -1
for i in range(1, length + 1):
for j in range(i):
temp = prices[j] + values[i - j - 1]
if temp > max_val:
max_val = prices[j] + values[i - j - 1]
cuts[i] = j + 1
values[i] = max_val
return values[length], cuts
def print_cuts(cuts, length):
while length > 0:
print(cuts[length], end=" ")
length -= cuts[length]
max_value, cuts = cut_rod(prices, length)
print(max_value)
print_cuts(cuts, length)
Well, if you need to get the actual pieces that would be the result of this process then you'd probably need a recursion.
For example something like that:
def cutRod(price, n):
val = [0 for x in range(n + 1)]
pieces = [[0, 0]]
val[0] = 0
for i in range(1, n + 1):
max_val = 0
max_pieces = [0, 0]
for j in range(i):
curr_val = price[j] + val[i - j - 1]
if curr_val > max_val:
max_val = curr_val
max_pieces = [j + 1, i - j - 1]
pieces.append(max_pieces)
val[i] = max_val
arr = []
def f(left, right):
if right == 0:
arr.append(left)
return
f(pieces[left][0], pieces[left][1])
f(pieces[right][0], pieces[right][1])
f(pieces[n][0], pieces[n][1])
return val[n], arr
In this code, there is an additional array for pieces which represents the best way to divide our Rod with some length.
Besides, there is a function f that goes through all pieces and figures out the optimal way to divide the whole Rod.
How do you sort a list with a while loop? Having a bit of a problem, thanks very much in advance.
a = [12,0,39,50,1]
first = a[0]
i = 0
j = 1
while i < len(a):
if a[i] < first:
tmp = a[i]
a[i] = a[j]
a[j] = tmp
i += 1
print(a)
You can create an empty list that would store your sorted numbers
a = [12,0,39,50,1]
kk = len(a)
new_a = []
i = 0
while i < kk:
xx = min(a) ## This would retreive the minimum value from the list (a)
new_a.append(xx) ## You store this minimum number in your new list (new_a)
a.remove(xx) ## Now you have to delete that minimum number from the list a
i += 1 ## This starts the whole process again.
print(new_a)
Please, note that I used the original length of the list a (kk) for the while statement so as not to stop the iteration because the length of the list a decreases as we delete the minimum numbers.
Following is the implementation of basic sorting using two while loops.
In every iteration, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray.
:
a=[12,0,39,50,1]
i=0
while i<len(a):
key=i
j=i+1
while j<len(a):
if a[key]>a[j]:
key=j
j+=1
a[i],a[key]=a[key],a[i]
i+=1
print(a)
# By using For loop
def ascending_array(arr):
print(f"Original array is {arr}")
arr_length = len(arr)
if arr_length <= 1:
return arr
for i in range(len(arr)):
for j in range(i+1, len(arr)):
if arr[i] >= arr[j]:
arr[i], arr[j] = arr[j], arr[i]
print(f"The result array is {arr}") # [0,0,0,1,10,20,59,63,88]
arr = [1,10,20,0,59,63,0,88,0]
ascending_array(arr)
# By using While loop
def ascending_array(arr):
print(f"Original array is {arr}")
arr_length = len(arr)
if arr_length <= 1:
return arr
i = 0
length_arr = len(arr)
while (i<length_arr):
j = i+1
while (j<length_arr):
if arr[i] > arr[j]:
arr[i], arr[j] = arr[j], arr[i]
j+=1
i+=1
print(f"The result array is {arr}") # [0,0,0,1,10,20,59,63,88]
arr = [1,10,20,0,59,63,0,88,0]
ascending_array(arr)
For-loop is best in terms of performance. while-loop is checking condition every iteration.
You can also concatenate two lists and sort them in decreasing/increasing order using this example:
x = [2,9,4,6]
y = [7,8,3,5]
z = []
maxi = x[0]
pos = 0
print('x: '+str(x))
print('y: '+str(y))
for i in range(len(y)):
x.append(y[i])
for j in range(len(x)-1):
maxi = x[0]
for i in range(len(x)):
if maxi < x[i]:
maxi = x[i]
pos = i
z.append(maxi)
del x[pos]
z.append(x[0])
print('z: '+str(z))
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]