I am an absolute beginner in python so please guide me where wrong. I have a nested list of scores for which I need to calculate the sum of all positive integers and the [-1] index. I have converted the nested loop into flatlist and now tried the sum but I seem to be getting the total as 0. Answer should be 3150.
Can you please tell me where I am wrong?
#Create a 2D matrix with scores
#matrix (Column, Row) is a list of lists
matrix = [[0,-1000,0,0,0], [0,0,150,0,-1000], [0,-1000,1000,-1000,0], [-1000,1000,-1000,-150,0], [1000,150,0,0,-150]]
#convert nested list into flatlist
matrix_flatList = [ item for elem in matrix for item in elem]
print(matrix_flatList)
def dream_score(matrix_flatlist):
"""
A function that returns the max possible score
"""
total = 0
#Iterate each positive element in list and add them in variable total
n = len(matrix_flatList)
for i in range(0,n):
if i > 0 and i == -150:
total == total matrix_flatList[i]
#printing dream score
print("Dream score is: ", total)
#make sure to get the last variable in total even if its negative
#return final score
CodePudding user response:
You have to change your for loop to get the exact output.
for i in matrix_flatList:
if i > 0 and i == 150:
total = i
But, what do you mean by i == -150
exactly?
CodePudding user response:
The problem happens in
if i > 0 and i == -150:
i
can not be a positive value and -150 at the same time.
Maybe you want to use or
instead.
Also if you want to find the element with index -1, it would be better to use the list indexing instead of using -150 explicitly.