I am trying to solve 1st step from Numeric Matrix Processor (hyperskill.org). I have to write program (without using numpy) which takes 2 matrix and then if number of rows and number of columns are equal I have to output sum of these 2 matrix. I know that for now number of columns is not used (only in if condition) but it doesn't matter. The problem is "IndexError: list index out of range" after I call summing function. Can someone tell me what am I doing wrong? Thx for helping!
main = []
main2 = []
final = []
mat = []
def reading():
print("rows:")
reading.rows = int(input())
print("columns:")
reading.columns = int(input())
for i in range(reading.rows):
mat = input().split()
mat = list(map(int, mat))
main.append(mat)
return main
def reading2():
print("rows:")
reading2.rows = int(input())
print("columns:")
reading2.columns = int(input())
for i in range(reading2.rows):
mat = input().split()
mat = list(map(int, mat))
main2.append(mat)
return main2
def summing():
if reading.rows == reading2.rows and reading.columns == reading2.columns:
for i in range(reading.rows):
for j in range(reading.columns):
final[i][j] = main[i][j] + main2[i][j]
print(final[j][i], end=" ")
print()
else:
print('ERROR')
reading()
reading2()
summing()
Related
I'm new to here and I'm not really good at English so I apologize for probable future mistakes.
My teacher asked us to write this program with classification... Here is the code
class Matrix:
def __init__(self,lst):
self.mat = lst
self.dim = (len(lst), len(lst[0]))
self.rows=[lst[i][:] for i in range(self.dim[0])]
self.columns=[[lst[i][j] for i in range(self.dim[0])] for j in range(self.dim[1])]
def get(self,i,j):
if (i) <= self.dim[0] and (j) <= self.dim[1]:
return self.mat[i-1][j-1]
else:
print ("index not in matrix!")
return None
def __multList(self,list1,list2):
if len(list1)==len(list2):
return sum([list1[i]*list2[i] for i in range(len(list1))])
def mult(self,other):
matrix=[]
for i in range(len(self.rows)):
rows=[]
for j in range(len(other.columns)):
rows.append(self.__multList(other.columns[j],self.rows[i]))
matrix.append(rows)
return Matrix(matrix)
and this the driver:
from Matrixclass import Matrix
print("For first matrix enter number of row and column respectively: (Ex: 4 5)")
m,n = list(map(int,input().split()))
print("Enter Row values")
mat1 = []
for i in range(m) :
print("Enter row",i + 1,"value:")
row = list(map(int,input().split()))
mat1.append(row)
print("For 2nd matrix enter number of row and column respectively: (Ex: 5 4)")
p,q = list(map(int,input().split()))
print("Enter Row wise values")
mat2 = []
for j in range(p) :
print("Enter row",j + 1,"value:")
row = list(map(int,input().split()))
mat2.append(row)
print("Matrix 1:",mat1)
print("Matrix 2:",mat2)
A = Matrix(mat1)
B = Matrix(mat2)
C=A.mult(B)
print("The Multiplication of two Matrix:\n",C.mat)
And when i run it, i got this error
AttributeError: 'list' object has no attribute 'mult'
Update: Now it works; 🙏thanks
i have made a list by using while list and then used if statements. In the first two conditions, the code runs perfectly without any error. But in the third condition it is showing that the list is empty. I have no clue what is wrong here.
CODE:
# time table generator with python
import random
no_of_classes = int(input("Please enter the number of classes in a day: "))
name_of_classes = input("Please enter the subject name/name of classes (please separate then by commas): ")
class_name_list = name_of_classes.split(",")
days_in_week = int(input("Enter the number of days in a week for which the school is working:"))
list_1 = [] `list with the problem`
x = 1
while x <= no_of_classes:
list_1.append(x)
x += 1
final_list = []
for j in range(days_in_week):
subject_list = []
if no_of_classes > len(class_name_list):
for i in class_name_list:
a = random.choice(list_1)
subject_list.insert((a - 1), i)
for m in range(no_of_classes - len(class_name_list)):
b = random.choice(class_name_list)
subject_list.append(b)
final_list.append(subject_list)
elif no_of_classes == len(class_name_list):
for i in class_name_list:
a = random.choice(list_1)
subject_list.insert((a-1), i)
final_list.append(subject_list)
else: `having problem with this condition`
temp_class_list = []
list_2 = class_name_list
for m in range(no_of_classes):
n = random.choice(list_2)
a = random.choice(list_1)
list_1.remove(a)
list_2.remove(n)
subject_list.insert((a-1), n)
for k in range(days_in_week):
print(final_list[k])
OUTPUT:
Traceback (most recent call last):
File "/Users/arungupta/Documents/trial (delete).py", line 24, in <module>
a = random.choice(list_1)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/random.py", line 301, in choice
raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence
THANK YOU FOR YOUR HELP. MUCH APPRECIATED!!!
You just forgot to fill the final_list : final_list.append(subject_list)
else:
temp_class_list = []
list_2 = class_name_list
for m in range(no_of_classes):
n = random.choice(list_2)
a = random.choice(list_1)
list_1.remove(a)
list_2.remove(n)
subject_list.insert((a-1), n)
final_list.append(subject_list)
There are two problems actually:
You forgot final_list.append(subject_list) as noted by Castiell
You emptied list_1, which makes your program crash in the next iteration (and actually, the error message you showed is due to this)
Here is my proposed correction: make a copy of list_1 before you empty it:
else:
temp_class_list = []
list_2_copy = class_name_list.copy()
list_1_copy = list_1.copy()
for m in range(no_of_classes):
n = random.choice(list_2_copy)
a = random.choice(list_1_copy)
list_1_copy.remove(a)
list_2_copy.remove(n)
subject_list.insert((a-1), n)
final_list.append(subject_list)
(I also made a copy of class_name_list because I suspect it is the source of another undiscovered bug)
#ADD STRING MATRIX AND NUM MATRIX Fraction(3).limit_denominator(10)from fractions import Fraction
#ONLY WORKS FOR SQUARE ONES RIGHT NOW!
from fractions import Fraction
def make1(nm,x):
if nm[x][x]!=1:
print("Divide R1 by ",Fraction(nm[x][x]).limit_denominator(10))
tempr = multiply(nm[x],1/nm[x][x])
nm[x] = tempr
return nm
def convert(n):
try:
return float(n)
except ValueError:
num, denom = n.split('/')
return float(num) / float(denom)
def convertm(m):
lm = len(m)
lx = len(m[0])
tempn = [0]*lx
temps = [[]]*lm
print(temps)
cnt = 0
for x in m:
tempn = x
for n in x:
temps[cnt].append(str(Fraction(n).limit_denominator(10)))
print(n)
cnt+=1
print(temps)
def mprint(matrix):
s = [[str(e) for e in row] for row in matrix]
lens = [max(map(len, col)) for col in zip(*s)]
fmt = '\t'.join('{{:{}}}'.format(x) for x in lens)
table = [fmt.format(*row) for row in s]
print('\n'.join(table))
def subtract(r1,r2): #r1-r2
tempr = [0]*len(r1)
for x in range (0,len(r1)):
tempr[x] = r1[x]-r2[x]
return tempr
def multiply(r1,n):
tempr = [0]*len(r1)
for x in range (0,len(r1)):
tempr[x] = r1[x]*n
return tempr
def ans(nm):
end = len(nm[0])
cnt = 0
for x in nm:
cnt+=1
print("X",cnt,"=",x[end-1])
equ = int(input("How many equasions are in the linear system? "))
#unk = int(input("How many unkowns are in the linear system? "))
nm = [0] * equ
sm = [0] * equ
for x in range (0,equ):
tempinput = input("Please enter line "+str(x+1)+" of the matrix: ")
templist = [convert(n) for n in tempinput.split()]
nm[x] = templist
sm[x] = tempinput.split()
mprint(nm)
nm = make1(nm,0)
mprint(nm)
for p in range (0,equ-1):
for x in range (p,equ-1):
print("Subtract ",Fraction(nm[x+1][p]).limit_denominator(10),"*",p+1,"by",p+2)
tempr = multiply(nm[p],nm[x+1][p])
nm[x+1] = subtract(tempr,nm[x+1])
print("FIRST X: ",x,"P",x)
mprint(nm)
nm = make1(nm,p+1)
mprint(nm)
#GOIN BACK
for p in range (0,equ-1):
for x in range (0,equ-(p+1)):
print("Subtract ",x,"by",Fraction(nm[x][2-p]).limit_denominator(10),"*",3)
tempr = multiply(nm[2-p],nm[x][2-p])
nm[x]= subtract(nm[x],tempr)
print("SECOND X: ",x,"P",x)
mprint(nm)
ans(nm)
##or x in range (0,equ):
# print()
#g = nm[1][0]-1
#print("")
#tempr = multiply(nm[0],g/nm[0][0])
#nm[0]=tempr
#tempr = subtract(nm[1],nm[0])
#nm[0] = tempr
Pastebin of my code
Ok so where my actual problem is in the unimplemented (because I couldn't get it working) def convertm. What this is supposed to do is take the matrix with numbers (nm) and take every value and convert it into a string as fractions (x/x) if needed and store it in the matrix of strings (sm).
Here is that segment of code I am referencing...
def convertm(m):
lm = len(m)
lx = len(m[0])
tempn = [0]*lx
temps = [[]]*lm
print(temps)
cnt = 0
for x in m:
tempn = x
for n in x:
temps[cnt].append(str(Fraction(n).limit_denominator(10)))
print(n)
cnt+=1
print(temps)
I added some prints in order to try and test what the heck was going on during it. I am getting an output of just the last row being repeated through all rows. I think I don't have a return statement currently just because I have been trying get this to work. Ok so for an example if an array is imported that is...
[ [1,2,3],
[4,5,6],
[7,8,9] ]
It will output (set temps to)
[ ['7','8','9'],
['7','8','9'],
['7','8','9'] ]
I want it to output (set temps to)
[ ['1','2','3'],
['4','5','6'],
['7','8','9'] ]
Also I am using Python 3.3.1
(probably should upgrade to 3.3.3 but that is not what we are discussing!)
I have absolutely no idea why it is doing this and any little bit of help would very appreciated!
THANK YOU
I also apologize if this formatting is horrible I am new to this and I copy/pasted this from another forum I am very desperate to know what is going on here.
The line
temps = [[]]*lm
makes a list of list, where each sublist points to the same list in memory. So, if you modify one, you modify them all. This is why you are seeing the behavior you are seeing.
Change it to
temps = [[] for _ in range(lm)] # xrange on python2
to get different sublists.
Right now I am attempting to code the knapsack problem in Python 3.2. I am trying to do this dynamically with a matrix. The algorithm that I am trying to use is as follows
Implements the memoryfunction method for the knapsack problem
Input: A nonnegative integer i indicating the number of the first
items being considered and a nonnegative integer j indicating the knapsack's capacity
Output: The value of an optimal feasible subset of the first i items
Note: Uses as global variables input arrays Weights[1..n], Values[1...n]
and table V[0...n, 0...W] whose entries are initialized with -1's except for
row 0 and column 0 initialized with 0's
if V[i, j] < 0
if j < Weights[i]
value <-- MFKnapsack(i - 1, j)
else
value <-- max(MFKnapsack(i -1, j),
Values[i] + MFKnapsack(i -1, j - Weights[i]))
V[i, j} <-- value
return V[i, j]
If you run the code below that I have you can see that it tries to insert the weight into the the list. Since this is using the recursion I am having a hard time spotting the problem. Also I get the error: can not add an integer with a list using the '+'. I have the matrix initialized to start with all 0's for the first row and first column everything else is initialized to -1. Any help will be much appreciated.
#Knapsack Problem
def knapsack(weight,value,capacity):
weight.insert(0,0)
value.insert(0,0)
print("Weights: ",weight)
print("Values: ",value)
capacityJ = capacity+1
## ------ initialize matrix F ---- ##
dimension = len(weight)+1
F = [[-1]*capacityJ]*dimension
#first column zeroed
for i in range(dimension):
F[i][0] = 0
#first row zeroed
F[0] = [0]*capacityJ
#-------------------------------- ##
d_index = dimension-2
print(matrixFormat(F))
return recKnap(F,weight,value,d_index,capacity)
def recKnap(matrix, weight,value,index, capacity):
print("index:",index,"capacity:",capacity)
if matrix[index][capacity] < 0:
if capacity < weight[index]:
value = recKnap(matrix,weight,value,index-1,capacity)
else:
value = max(recKnap(matrix,weight,value,index-1,capacity),
value[index] +
recKnap(matrix,weight,value,index-1,capacity-(weight[index]))
matrix[index][capacity] = value
print("matrix:",matrix)
return matrix[index][capacity]
def matrixFormat(*doubleLst):
matrix = str(list(doubleLst)[0])
length = len(matrix)-1
temp = '|'
currChar = ''
nextChar = ''
i = 0
while i < length:
if matrix[i] == ']':
temp = temp + '|\n|'
#double digit
elif matrix[i].isdigit() and matrix[i+1].isdigit():
temp = temp + (matrix[i]+matrix[i+1]).center(4)
i = i+2
continue
#negative double digit
elif matrix[i] == '-' and matrix[i+1].isdigit() and matrix[i+2].isdigit():
temp = temp + (matrix[i]+matrix[i+1]+matrix[i+2]).center(4)
i = i + 2
continue
#negative single digit
elif matrix[i] == '-' and matrix[i+1].isdigit():
temp = temp + (matrix[i]+matrix[i+1]).center(4)
i = i + 2
continue
elif matrix[i].isdigit():
temp = temp + matrix[i].center(4)
#updates next round
currChar = matrix[i]
nextChar = matrix[i+1]
i = i + 1
return temp[:-1]
def main():
print("Knapsack Program")
#num = input("Enter the weights you have for objects you would like to have:")
#weightlst = []
#valuelst = []
## for i in range(int(num)):
## value , weight = eval(input("What is the " + str(i) + " object value, weight you wish to put in the knapsack? ex. 2,3: "))
## weightlst.append(weight)
## valuelst.append(value)
weightLst = [2,1,3,2]
valueLst = [12,10,20,15]
capacity = 5
value = knapsack(weightLst,valueLst,5)
print("\n Max Matrix")
print(matrixFormat(value))
main()
F = [[-1]*capacityJ]*dimension
does not properly initialize the matrix. [-1]*capacityJ is fine, but [...]*dimension creates dimension references to the exact same list. So modifying one list modifies them all.
Try instead
F = [[-1]*capacityJ for _ in range(dimension)]
This is a common Python pitfall. See this post for more explanation.
for the purpose of cache illustration, I generally use a default dict as follows:
from collections import defaultdict
CS = defaultdict(lambda: defaultdict(int)) #if i want to make default vals as 0
###or
CACHE_1 = defaultdict(lambda: defaultdict(lambda: int(-1))) #if i want to make default vals as -1 (or something else)
This keeps me from making the 2d arrays in python on the fly...
To see an answer to z1knapsack using this approach:
http://ideone.com/fUKZmq
def zeroes(n,m):
v=[['-' for i in range(0,n)]for j in range(0,m)]
return v
value=[0,12,10,20,15]
w=[0,2,1,3,2]
v=zeroes(6,5)
def knap(i,j):
global v
if i==0 or j==0:
v[i][j]= 0
elif j<w[i] :
v[i][j]=knap(i-1,j)
else:
v[i][j]=max(knap(i-1,j),value[i]+knap(i-1,j-w[i]))
return v[i][j]
x=knap(4,5)
print (x)
for i in range (0,len(v)):
for j in range(0,len(v[0])):
print(v[i][j],end="\t\t")
print()
print()
#now these calls are for filling all the boxes in the matrix as in the above call only few v[i][j]were called and returned
knap(4,1)
knap(4,2)
knap(4,3)
knap(4,4)
for i in range (0,len(v)):
for j in range(0,len(v[0])):
print(v[i][j],end="\t\t")
print()
print()
I'm trying to figure out what's wrong with my code. Could anyone fix it?
def main():
fname = input("Enter filename:")
infile = open(fname, "r")
SD()
def SD():
b= []
a = 5.0
r = len(b)
for n in range(r-1):
b.append((r[n] -a)**2)
m = (float(b)/r)**0.5
print("The standard deviation is", m)
main()
You have a handful of errors:
def SD():
# b is empty
b= []
a = 5.0
#this will always be 0
r = len(b)
# range(r-1) == [] because it is range(-1)
# whole loop is skipped
for n in range(r-1):
b.append((r[n] -a)**2)
# float(b) should throw an error, maybe sum(b) ?
m = (float(b)/r)**0.5
print("The standard deviation is", m)
main()
b is a list; you can't cast a list into a float.
perhaps you want to pass an array to SD()? You should read() the files contents and then perhaps split() that into an array and pass it to SD() as an argument (where you'll call int() on them.)
For a sample:
def SD(numList):
cntN=len(numList)
sumN=0
for i in numList:
sumN+=i
avgVal=float(sumN)/float(cntN)
sumVar=0.0
for i in range(cntN):
sumVar+=float((numList[i]-avgVal)**2)
return ((float(sumVar)/float((cntN-1)))**0.5)