I currently have defined my object (is_matched) that contains a while loop and also the checking of a string. I am trying to pull out the while loop into it's own object but am having trouble completing the coding. I also need the while loop to continue running until a user enters 'q' into the input.
def is_matched():
while True:
expr = input("Enter string (q to quit): ")
if expr == "q":
break
stack = Stack()
for i in expr:
if i == '{' or i == '(' or i == '[':
stack.push(i)
elif i == '}':
if len(expr) != 0:
c = stack.top()
if c == '{':
stack.pop()
else:
return "Unbalanced"
elif i == ')':
if len(expr) != 0:
c = stack.top()
if c == '(':
stack.pop()
else:
return "Unbalanced"
elif i == ']':
if len(expr) != 0:
c = stack.top()
if c == '[':
stack.pop()
else:
return "Unbalanced"
else:
return "Unbalanced"
if len(stack) != 0:
return "Unblanced"
return "Balanced"
result = is_matched()
print(result)
I am trying to pull out the while loop from above and enter into its own object as follows:
def main():
while True:
expr = input("Enter string (q to quit): ")
if expr == "q":
break
else:
return is_matched()
your is_matched function will take one argument which will be the expression to evaluate.
def is_matched(expr):
stack = Stack()
for i in expr:
if i == '{' or i == '(' or i == '[':
stack.push(i)
elif i == '}':
if len(expr) != 0:
c = stack.top()
if c == '{':
stack.pop()
else:
return "Unbalanced"
elif i == ')':
if len(expr) != 0:
c = stack.top()
if c == '(':
stack.pop()
else:
return "Unbalanced"
elif i == ']':
if len(expr) != 0:
c = stack.top()
if c == '[':
stack.pop()
else:
return "Unbalanced"
else:
return "Unbalanced"
if len(stack) != 0:
return "Unblanced"
return "Balanced"
main function.
def main():
while True:
expr = input("Enter string (q to quit): ")
if expr == "q":
break
else:
print(is_matched(expr))
Related
I looked at the other answers but they didn't seem to work for me, or I could just be doing something wrong, or not understanding what I am supposed to do in the context of this code. On line 78, it talks about how there is a Nonetype value, even though I assigned a value to both variables no matter what.
Here is a link to a similar problem (I think):
[https://stackoverflow.com/questions/53680913/typeerror-cannot-unpack-non-iterable-nonetype-object][1]
Here is where I think the faulty code lies:
def check_win(turn, gamestate):
if turn == 1:
if gamestate[0] == gamestate[1] == gamestate[2] != '-' or gamestate[3] == gamestate[4] == gamestate[5] != '-' or gamestate[6] == gamestate[7] == gamestate[8] != '-':
winner = 1
win = True
return winner, win
elif gamestate[0] == gamestate[3] == gamestate[6] != '-' or gamestate[1] == gamestate[4] == gamestate[7] != '-' or gamestate[2] == gamestate[5] == gamestate[8] != '-':
winner = 1
win = True
return winner, win
elif gamestate[0] == gamestate[4] == gamestate[8] != '-' or gamestate[2] == gamestate[4] == gamestate[6] != '-':
winner = 1
win = True
return winner, win
elif turn == 2:
if gamestate[0] == gamestate[1] == gamestate[2] or gamestate[3] == gamestate[4] == gamestate[5] or gamestate[6] == gamestate[7] == gamestate[8]:
winner = 2
win = True
return winner, win
elif gamestate[0] == gamestate[3] == gamestate[6] or gamestate[1] == gamestate[4] == gamestate[7] or gamestate[2] == gamestate[5] == gamestate[8]:
winner = 2
win = True
return winner, win
elif gamestate[0] == gamestate[4] == gamestate[8] or gamestate[2] == gamestate[4] == gamestate[6]:
winner = 2
win = True
return winner, win
else:
winner = 'None'
win = False
return winner, win
Later on when I try to alter those values in another function:
winner, win = check_win(turn, gamestate) <--- Where error was found
Here is the code in its entirety :
print('Tic Tac Toe:')
pos = 0
turn = 1
gamestate = ['-', '-', '-', '-', '-', '-', '-', '-', '-']
def display_board(gamestate):
print(gamestate[0:3])
print(gamestate[3:6])
print(gamestate[6:9])
def move_validity(pos, gamestate):
if str(gamestate[int(pos)]) != '-':
print('Invalid move.')
valid = False
return valid
else:
valid = True
return valid
def update(gamestate, pos):
if turn == 1:
gamestate[int(pos)] = 'X'
if turn == 2:
gamestate[int(pos)] = 'O'
else:
print('ERROR')
def check_win(turn, gamestate):
if turn == 1:
if gamestate[0] == gamestate[1] == gamestate[2] != '-' or gamestate[3] == gamestate[4] == gamestate[5] != '-' or gamestate[6] == gamestate[7] == gamestate[8] != '-':
winner = 1
win = True
return winner, win
elif gamestate[0] == gamestate[3] == gamestate[6] != '-' or gamestate[1] == gamestate[4] == gamestate[7] != '-' or gamestate[2] == gamestate[5] == gamestate[8] != '-':
winner = 1
win = True
return winner, win
elif gamestate[0] == gamestate[4] == gamestate[8] != '-' or gamestate[2] == gamestate[4] == gamestate[6] != '-':
winner = 1
win = True
return winner, win
elif turn == 2:
if gamestate[0] == gamestate[1] == gamestate[2] or gamestate[3] == gamestate[4] == gamestate[5] or gamestate[6] == gamestate[7] == gamestate[8]:
winner = 2
win = True
return winner, win
elif gamestate[0] == gamestate[3] == gamestate[6] or gamestate[1] == gamestate[4] == gamestate[7] or gamestate[2] == gamestate[5] == gamestate[8]:
winner = 2
win = True
return winner, win
elif gamestate[0] == gamestate[4] == gamestate[8] or gamestate[2] == gamestate[4] == gamestate[6]:
winner = 2
win = True
return winner, win
else:
winner = 'None'
win = False
return winner, win
def restart():
gamestate = ['-', '-', '-', '-', '-', '-', '-', '-', '-']
turn = 1
win = False
return gamestate, turn, win
def choose_position():
pos = input('Player ' + str(turn) + ': ')
if int(pos) < 0 or int(pos) > 8:
print('Invalid move')
else:
return pos
def Tic_Tac_Toe():
while True:
global pos
global turn
if turn == 1:
pos = choose_position()
valid = move_validity(pos, gamestate)
if valid == True:
update(gamestate, pos)
if valid == False:
break
winner, win = check_win(turn, gamestate)
if win == True:
print(str(winner) + ' wins!')
break
if '-' not in gamestate:
print('Tie game.')
break
if turn == 2:
pos = choose_position()
if move_validity(pos, gamestate) == True:
continue
if move_validity(pos, gamestate) == False:
break
update(gamestate, pos)
winner, win = check_win(turn, gamestate)
if win == True:
print(str(winner) + ' wins!')
break
turn = 1
if '-' not in gamestate:
print('Tie game.')
break
display_board(gamestate)
display_board(gamestate)
Tic_Tac_Toe()
restart_case = input('y/n Would you like to play? ')
if restart_case == 'y':
gameboard, turn, win = restart()
Thank you so much, and sorry if the solution was a small typo, I am really new to this and have spent way too much time on this. :D
There are certain cases where you don't return anything in the function check_win.
For example, when turn == 1, you have an if, elif, elif block within that, but nothing for else. So, when turn == 1, if none of the if statements within the block for that are true, your function will return nothing. There is a similar problem for turn == 2. You may want to add the code you have in the else block for that function as an else block for both turn == 1 and turn == 2, as this will fix your problem.
start = input('Enter quadratic equation: ')
w = start.split()
while len(w) != 7:
start = input('Enter quadratic equation correctly: ')
w = start.split()
while x < len(w):
if "x" in w[x] and '^2' in w[x]:
a = w[x]
if a == "x^2":
a = 1
else:
a = a.replace('x^2', '')
a = int(a)
if w[x-1] == '-':
a = a * (-1)
else:
a = a
elif 'x' in w[x] and '^' not in w[x]:
b = w[x]
if b == 'x':
b = 1
else:
b = b.replace('x', '')
b = int(b)
if w[x-1] == '-':
b = b * (-1)
else:
b = b
elif w[x].isdigit() and 'x' not in w[x] and w[x] != '0':
c = w[x]
elif w[x] == '-' or '+' or '=':
s = 0
elif not w[x].isdigit() and 'x' not in w[x] and w[x] != '-' or '+' or '=':
print('Mistake')
break #Would not this code here work?
x += 1
I have tried just doing 'else' block, but still it wouldn't work. What I am trying to do is to check whether the input is actually a quadratic equation.
The wrong condition is elif not w[x].isdigit() and 'x' not in w[x] and w[x] != '-' or '+' or '=':, it doesn't do what you want/need
The w[x] != '-' or '+' or '=': part :
is like (w[x]!='-') or ('+') or ('='):
not like w[x] != ('-' or '+' or '='):
What you want is w[x] not in '-+=': and same for the previous one
elif w[x] in '-+=':
s = 0
elif not w[x].isdigit() and 'x' not in w[x] and w[x] not in '-+=':
print('Mistake')
break
I tried to work out a simple python calculator using stacks and it works only on situations where a negative number is first and when there isn't a negative number but when a situation arises such as 4*-2 for example, it gives an error (my eyes are on getNextNumber and isNumber and findNextOpr. Is there a way to fix this? Here's the code:
import pdb
class Stack:
def __init__(self):
self.container = []
def isEmpty(self):
return self.size() == 0
def push(self, item):
self.container.append(item)
def pop(self):
return self.container.pop()
def size(self):
return len(self.container)
class stack:
class node:
def __init__(self, value, nextNode):
self.value = value
self.nextNode = nextNode
def __init__(self):
self.top = None
self.last = None
self.size = 0
def __len__(self):
return self.size
def isEmpty(self):
return self.size == 0
def push(self, value):
if self.size == 0:
self.top = self.last = self.node(value, None)
else:
newNode = self.node(value, None)
newNode.nextNode = self.top
self.top = newNode
self.size += 1
def pop(self):
if self.size == 0:
return 'Error: stack.pop'
elif self.size == 1:
value = self.top.value
self.top = self.last = None
self.size -= 1
return value
else:
value = self.top.value
self.top = self.top.nextNode
self.size -= 1
return value
def findNextOpr(s):
if len(s) <= 0 or not isinstance(s, str):
print('Type mismatch error: findNextOpr')
return 'Type mismatch error: findNextOpr'
for n in range(len(s)):
if ord(s[n]) == 42 or ord(s[n]) == 43 or ord(s[n]) == 45 or ord(s[n]) == 47 or ord(s[n]) == 94:
return n
else:
continue
return -1
def isNumber(s):
if len(s) == 0 or not isinstance(s, str):
print('Type mismatch error: isNumber')
return 'Type mismatch error: isNumber'
try:
float(s)
return True
except:
return False
def getNextNumber(expr, pos):
#pdb.set_trace()
if len(expr) == 0 or not isinstance(expr, str) or pos < 0 or pos >= len(expr) or not isinstance(pos, int):
print('Type mismatch error: getNextNumber')
return None, None, 'Type mismatch error: getNextNumber'
m = findNextOpr(expr[pos:])
if m != -1:
opr = expr[m]
if isNumber(expr[pos: m + pos]) is True:
return float(expr[pos: m + pos]), expr[pos + m], m
elif isNumber(expr[pos:m+pos]) is False:
if expr[m+1] == '-':
pos = m+1
num=getNextNumber(expr,pos)
return -float(num),None,None
else:
return None, None, None
elif m == -1:
if isNumber(expr[pos:]) is True:
return float(expr[pos:]), None, None
else:
return None, None, None
def exeOpr(num1, opr, num2):
if opr == '+':
return num1 + num2
elif opr == '-':
return num1 - num2
elif opr == '*':
return num1 * num2
elif opr == '/':
if num2 == 0:
print('Zero division error: exeOpr')
return 'Zero division error: exeOpr'
else:
return num1 / num2
elif opr == '^':
return num1 ** num2
else:
print('Fatal internal error in exeOpr')
return 'Fatal internal error in exeOpr'
def _calc(expr):
if not isinstance(expr, str) or len(expr) <= 0:
print('Argument error: Line A in eval_expr')
return 'Argument error: Line A in eval_expr'
newNumber, newOpr, oprPos = getNextNumber(expr, 0)
if newNumber is None:
print('Input formula error: Line B in eval_expr')
return 'Input formula error: Line B in eval_expr'
elif newOpr is None:
return newNumber
elif newOpr == '+' or newOpr == '-':
mode = 'add'
addResult = newNumber
mulResult = 1
expResult = 0
elif newOpr == '*' or newOpr == '/':
mode = 'mul'
addResult = 0
mulResult = newNumber
expResult = 1
elif newOpr == '^':
mode = 'exp'
addResult = 0
mulResult = 1
expResult = newNumber
pos = oprPos + 1
opr = newOpr
while True:
nextNumber, newOpr, oprPos = getNextNumber(expr, pos)
if nextNumber is None or pos >= len(expr):
print('Input formula error: Line C in calc')
return 'Input formula error: Line C in calc'
elif newOpr is None:
if mode == 'add':
return exeOpr(addResult, opr, nextNumber)
elif mode == 'mul':
return exeOpr(mulResult, opr, nextNumber) + addResult
elif mode == 'exp':
return exeOpr(expResult, opr, nextNumber) * mulResult + addResult
oprPos += pos
pos = oprPos + 1
if mode == 'add':
if newOpr == '+' or newOpr == '-':
addResult = exeOpr(addResult, opr, nextNumber)
mode = 'add'
elif newOpr == '*' or newOpr == '/':
if opr == '+':
mulResult = nextNumber
elif opr == '-':
mulResult = -nextNumber
mode = 'mul'
elif newOpr == '^':
if opr == '+':
expResult = nextNumber
elif opr == '-':
expResult = - nextNumber
mode = 'exp'
elif mode == 'mul':
if newOpr == '*' or newOpr == '/':
mulResult = exeOpr(mulResult, opr, nextNumber)
mode = 'mul'
elif newOpr == '+' or newOpr == '-':
addResult += exeOpr(mulResult, opr, nextNumber)
elif newOpr == '^':
if opr == '*':
expResult = 1 / nextNumber
mode = 'exp'
elif mode == 'exp':
if newOpr == '^':
expResult = exeOpr(expResult, opr, nextNumber)
mode = 'exp'
elif newOpr == '+' or newOpr == '-':
addResult = exeOpr(expResult, opr, nextNumber) * mulResult + addResult
mode = 'add'
elif newOpr == '*' or newOpr == '/':
mulResult = exeOpr(expResult, opr, nextNumber) * mulResult
mode = 'mul'
opr = newOpr
def icheck(expr):
d = None
if expr[0] == '-':
expr = '0' + expr
for i in range(len(expr)):
if expr[i] == '(':
d = i
elif expr[i] == '':
continue
elif d is not None and expr[i] == '-':
for j in range(i + 1, len(expr)):
if expr[j] == '':
continue
else:
expr = expr[0: d + 1] + '0' + expr[d+1:]
d = None
break
else:
d = None
return expr
def pcheck(expr):
expr = expr.replace(' ', '')
per = Stack()
for i in range(len(expr)):
if expr[i] == '(':
if i != 0 and isNumber(expr[i - 1]) == True:
print('Omitting Operator')
return False
per.push(i)
elif expr[i] == ')':
if i != (len(expr) - 1) and isNumber(expr[i + 1]) == True:
print('Omitting Operator')
return False
try:
per.pop()
except IndexError:
print('Parenthesis are unbalanced')
return False
return per.isEmpty()
def calc(e, u=None):
if len(e) == 0:
return 'Empty String'
e = e.replace(' ', '')
if u is None:
e = icheck(e)
tf = pcheck(e)
if tf is False:
return IndexError
st = Stack()
b = None
for i in range(len(e)):
pos = i
if e[i] == '(':
st.push(i)
elif e[i] == ')':
b = st.pop()
c = i
break
if b is None:
return _calc(e)
if st.size() == 0 and (pos == len(e) - 1):
res = _calc(e[b+1:c])
if len(e) > c:
e = e[:b] + str(res) + e[c + 1:]
else:
e = e[:b] + str(res)
return _calc(e)
else:
res = _calc(e[b + 1: c])
e = e[:b] + str(res) + e[c + 1:]
return calc(e, u=1)
print(calc('2.0*-2+5'))
print(calc('-2.0+1'))
print(calc('4*-2'))
print(calc('2+3*(-2 +(-3)*(5^2-2*3^(-2))*(-4))*(2/8+2*(3–1/3))-2/3^2'))
print(calc('1+3-2/30^2/5-1*5*3*4/3-1^2/6/7/8+3-1/2^2*3/2+3+1^2^2+3/3^2'))
This is an expected issue. To overcome this, electronic calculators usually use minus and negative signs seperately (which are the same in Python, causing your problem). You can apply this by creating an operator classes for these, assign them spesific purposes.
Alternatively, you can enforce the correct usage of paranthesis when the input is taken, or pre-check the input and convert it without bothering the user, make it a computer usable format (add paranthesis or whatsoever).
In spite of seeing a lot of posts about the python indentation error and trying out a lot of solutions, I still get this error:
import random
import copy
import sys
the_board = [" "]*10
def printboard(board):
print(board[7] + " " + "|" + board[8] + " " + "|" + board[9])
print("--------")
print(board[4] + " " + "|" + board[5] + " " + "|" + board[6])
print("--------")
print(board[1] + " " + "|" + board[2] + " " + "|" + board[3])
def choose_player():
while True:
player = input("What do you want to be; X or O?")
if player == "X":
print("You chose X")
comp = "O"
break
elif player == "O":
print("You chose O")
comp = "X"
break
else:
print("Invalid Selection")
continue
return [player, comp]
def virtual_toss():
print("Tossing to see who goes first.....")
x = random.randint(0,1)
if x== 0:
print("AI goes first")
move = "comp"
if x == 1:
print("Human goes first")
move = "hum"
return move
def win(board,le):
if (board[7] == le and board[8] == le and board[9]==le) or (board[4] == le and board[5]==le and board[6] == le)or (board[1] == le and board[2]==le and board[3] == le)or (board[7] == le and board[5]==le and board[3] == le)or (board[9] == le and board[5]==le and board[1] == le)or (board[7] == le and board[4]==le and board[1] == le)or (board[8] == le and board[5]==le and board[2] == le)or (board[9] == le and board[6]==le and board[3] == le):
return True
else:
return False
def make_move(board,number,symbol):
board[number] = symbol
def board_full(board):
count = 0
for item in board:
if item in ["X","O"]:
count+= 1
if count ==9 :
return True
else:
return False
def valid_move(board,num):
if board[num] == " ":
return True
else:
return False
def player_move(board):
number = int(input("Enter the number"))
return number
def copy_board(board):
copied_board = copy.copy(board)
return copied_board
def check_corner(board):
if (board[7] == " ") or (board[9] == " ") or (board[1] == " ") or (board[3] == " "):
return True
else:
return False
def check_center(board):
if (board[5] == " "):
return True
else:
return False
while True:
count = 0
loop_break = 0
print("welcome to TIC TAC TOE")
pla,comp = choose_player()
turn = virtual_toss()
while True:
printboard(the_board)
if turn == "hum":
if board_full() == True:
again = input ("Game is a tie. Want to try again? Y for yes and N for No")
if again == "Y":
loop_break = 6
break
else:
system.exit()
if loop_break == 6:
continue
while True:
number = player_move(the_board)
if (valid_move(the_board,number) == True) and not(board_full == False):
make_move(the_board,number,pla)
break
else:
print("Invalid Move, try again!")
continue
if (win(the_board,pla) == True):
print ("Yay, you won!!!")
printboard(the_board)
count = 1
break
else:
turn = "comp"
printboard(the_board)
continue
else:
if board_full() == True:
again = input ("Game is a tie. Want to try again? Y for yes and N for No")
if again == "Y":
loop_break = 6
break
else:
system.exit()
if loop_break = 6:
continue
copy_board(the_board)
for i in range(0,9):
make_move(copied_board,i,pla)
if(win(copied_board,pla) == True):
make_move(the_board,comp)
turn = "hum"
loop_break = 1
break
else:
continue
if loop_break = 1:
continue
if (check_corner(the_board) == True) or (check_center(the_board)==True):
for i in [7,9,1,3,5]:
if(valid_move(copied_board,i)==True):
make_move(copied_board,i,comp)
if(win(copied_board,comp)==True):
make_move(the_board,i,comp)
print("The AI beat you")
loop_break = 2
count = 1
break
else:
make_move(the_board,i,comp)
turn = "hum"
loop_break = 3
break
if loop_break == 2:
break
elif loop_break == 3:
continue
else:
for i in [8,4,6,2]:
if(valid_move(copied_board,i)==True):
make_move(copied_board,i,comp)
if(win(copied_board,comp)):
make_move(the_board,i,comp)
print("The AI beat you")
count = 1
loop_break = 4
break
else:
make_move(the_board,i,comp)
turn = "hum"
loop_break = 5
break
if loop_break == 4:
break
elif loop_break == 5:
continue
if count == 1:
again = input("Would you like to play again? y/n")
if again == "y":
continue
else:
system.exit()
I know that this is quite a long code, but I will point out the particular area where the error lies. You see, I am getting the following error message:
Traceback (most recent call last):
File "python", line 106
if (win(the_board,pla) == True):
^
IndentationError: unindent does not match any outer indentation level
More specifically, this part of the code:
while True:
number = player_move(the_board)
if (valid_move(the_board,number) == True) and not(board_full == False):
make_move(the_board,number,pla)
break
else:
print("Invalid Move, try again!")
continue
if (win(the_board,pla) == True):
print ("Yay, you won!!!")
printboard(the_board)
count = 1
break
Any help? I cannot get the code to work by any means!!
Try unindenting the previous seven lines of code by one level (the code in that while loop). This should make the indents work correctly. Also, it seems that there is an extra space before the if statement that is causing you errors. Remove this space as well. This would make that part of the code like this:
while True:
number = player_move(the_board)
if (valid_move(the_board,number) == True) and not(board_full == False):
make_move(the_board,number,pla)
break
else:
print("Invalid Move, try again!")
continue
if (win(the_board,pla) == True):
print ("Yay, you won!!!")
printboard(the_board)
count = 1
break
You need to indent the block under while (True): consistently. E.g.:
while True:
number = player_move(the_board)
if (valid_move(the_board,number) == True) and not(board_full == False):
make_move(the_board,number,pla)
break
else:
print("Invalid Move, try again!")
continue
if (win(the_board,pla) == True):
print ("Yay, you won!!!")
printboard(the_board)
count = 1
break
else:
turn = "comp"
printboard(the_board)
continue
The problem is, the if statement is one indentation back from the rest of the code. You want to align all the code and the error should go away.
while True:
number = player_move(the_board)
if (valid_move(the_board,number) == True) and not(board_full == False):
make_move(the_board,number,pla)
break
else:
print("Invalid Move, try again!")
continue
if (win(the_board,pla) == True):
print ("Yay, you won!!!")
printboard(the_board)
count = 1
break
I'm currently trying to solve problem 22 on Project Euler...which is as follows:
**Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.
For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.
What is the total of all the name scores in the file?**
Here's the code that I wrote to solve this problem:
f = open("F:\gnames.txt", "r")
strr = f.read()
w = strr.replace('"', "")
li = w.split(',')
dic = {}
sum = 0
for ee in li:
for e in ee:
if (e == "A"):
sum+=1
elif (e == "B"):
sum+=2
elif (e == "C"):
sum+=3
elif (e == "D"):
sum+=4
elif (e == "E"):
sum+=5
elif (e == "F"):
sum+=6
elif (e == "G"):
sum+=7
elif (e == "H"):
sum+=8
elif (e == "I"):
sum+=9
elif (e == "J"):
sum+=10
elif (e == "K"):
sum+=11
elif (e == "L"):
sum+=12
elif (e == "M"):
sum+=13
elif (e == "N"):
sum+=14
elif (e == "O"):
sum+=15
elif (e == "P"):
sum+=16
elif (e == "Q"):
sum+=17
elif (e == "R"):
sum+=18
elif (e == "S"):
sum+=19
elif (e == "T"):
sum+=20
elif (e == "U"):
sum+=21
elif (e == "V"):
sum+=22
elif (e == "W"):
sum+=23
elif (e == "X"):
sum+=24
elif (e == "Y"):
sum+=25
else:
sum+=26
dic[ee] = sum
sum = 0
x = sorted(dic.items(), key=lambda t: t[1])
main_sum = 0
index = 0
for c in x:
t = c[1]*index
main_sum = main_sum + t
index+=1
print main_sum
The actual answer is 871198282. However, my code gives the answer as 995996966, which is off by 124798684 compared to the actual answer. What seems to be the problem with my code?
I think your issue is in the line x = sorted(dic.items(), key=lambda t: t[1]). This sorts the dictionary items by the scores, not alphabetically by the names. Change t[1] to t[0] in the lambda and I suspect you'll get a better result.
Another possible issue (it's a little ambiguous) is your indexing when you go to add up the scores. You're starting index at zero, but the instructions suggest that the 938th name should be multiplied by 938, not by its zero-based index, which would be 937. You probably need to start with index = 1.