Reputation: 127
I am building a function that uses another function I've already defined. The first completed function is get_value_at_location, which tells me the value at the location (a tuple,) inside a list (puzzle.)
Here is the code for that function:
def get_value_at_location(puzzle,loc):
val_loc= puzzle[loc[0]][loc[1]]
return val_loc
Now I am trying to build a function called is_valid_solution, which accepts the parameters puzzle (given list,) op (operation to be done ex: + - *,) expected total (outcome we want,) and locations (tuple) to determine if the operation yields the expected outcome and then returns True or False.
Here is the code I've got so you can see what I'm thinking:
def is_valid_solution(puzzle, op, expected_total, locations):
loc=location
if (get_value_at_location(puzzle,loc)) +(op) ==expected_total:
return True
else:
return False
example input/output:
([[1]], '+', 1, [(0,0)]) → True
([[1,2],[2,1]], '-', 1, [(0,0),(1,0)]) → True
([[1,2],[2,1]], '+', 4, [(0,0),(0,1)]) → False
Obviously this is in correct, I just don't know the method of doing what I want to do? How can I implement this?
Upvotes: 0
Views: 383
Reputation: 76919
Option A
Instead of attempting to use "+"
or "*"
as strings, use the operator
module.
> import operator
> operator.add(2, 3)
5
> operator.mul(2, 3)
6
You can pass operator.add
as the op
parameter, then call in your function:
def apply(a, b, op):
return op(a, b)
apply(2, 3, operator.add) # 5
Option B
Use if
to choose the operation by its string name:
def apply(a, b, op):
if op == '+':
return a + b
if op == '*':
return a * b
apply(2, 3, '*') # 6
Upvotes: 1