def sudoku_solver(sudoku):
l = [0, 0]
if not find_empty_location(sudoku, l):
return True
row = l[0]
col = l[1]
for num in range(1, 10):
if check_location_is_safe(sudoku, row, col, num):
sudoku[row][col] = num
if sudoku_solver(sudoku):
return True,sudoku
sudoku[row][col] = 0
return False
def P():
a = np.zeros((9,9))
if sudoku_solver(sudoku):
a = sudoku_solver(sudoku)[1]
else:
a = 1
return a
There are two returns, True and sudoku. How can I call sudoku only in function P? When I run the function P(), it will show
'bool' object is not subscriptable.
You could make your function return a single value that would be either None or the sudoku data.
Python treats None as false so your condition could then be:
...
if sudoku_solver(sudoku):
a = sudoku_solver(sudoku)
...
Note that if sudoku_solver() is a complex and time consuming function, you will want to place its result in a variable BEFORE testing the condition so that it is not executed twice (as would be the case in the above condition)
...
a = sudoku_solver(sudoku)
if a:
...
Another option would be to systematically return a tuple with the boolean and the sudoku data (or None).
Your return statements would have to be changed to return True,sudoku and return False,None
Then your condition could use indexing directly:
...
if sudoku_solver(sudoku)[0]:
a = sudoku_solver(sudoku)[1]
...
but again, you probably don't want to execute the function twice so :
...
ok,a = sudoku_solver(sudoku)
if ok :
...
Another thing is that, if you're passing sudoku as a parameter, you have to realize that your function will modify the content of the calling variable even when it returns False. That may not be what you want but if it is, then there is no point in returning a second value because the caller's instance of the sudoku variable will already be modified and available.
When you see
return True,sudoku
you can catch the returned values like so
result, sudoku = my_function()
or if you've no interest in result
_, sudoku = my_function()
---Edit---
It seems your question centers around the two returns. Namely
return True,sudoku
versus
return False
That's adds unnecessary complexity. Can I suggest you simplify by instead using
return sudoku
and then later
return None
That means you can check the returned value like so
sudoku = my_function()
if (sudoku):
// Do something here
else:
// Do something else
You can't return multiple objects from a function, but you can return a container object, such as a list or tuple, that contains multiple member objects. Try using
return [ True, sudoku ]
Related
def p3(x,y,ls2):
for i in ls2:
if abs(i[0]-x)==abs(i[1]-y):
c=0
break
else:
c=1
if c==0:
return False
else:
return True
Even I have assigned c in the same function, it still displays "local variable 'c' referenced before assignment"
As the comment by Suraj S says, the problem is if ls2 is an empty list (iterable). Even if that were not a problem, c is a local variable inside the for loop and even though Python allows accessing it outside its scope, it is not a good practice to do so. So it is correct to default initialize it first before running the loop. You can default it to 0 or 1 depending on your use case.
Also, practice Boolean Zen. Don't make redundant checks with booleans. It is better to use True and False instead of 0 and 1.
def p3(x,y,ls2):
c = True # default
for i in ls2:
if abs(i[0]-x)==abs(i[1]-y):
c = False
break
# no need for else at all
return c
Even better:
def p3(x,y,ls2):
for i in ls2:
if abs(i[0]-x)==abs(i[1]-y):
return False
# no need for else at all
return True
If I understand correctly your function, you could simplify it to the following:
def p3(x, y, ls2):
# if no list or list is empty
if not ls2: # the condition could be more convoluted if needed
return 'invalid input' # or return boolean depending on use case
for i in ls2:
# if condition is matched return immediately
if abs(i[0]-x)==abs(i[1]-y):
return False
# the condition was not matched in loop, return default True
return True
You could even simplify more using all that will stop prematurely if the condition is met:
def p3(x, y, ls2):
# if no list or list is empty
if not ls2: # the condition could be more convoluted if needed
return 'invalid input' # or return boolean depending on use case
return all(abs(i[0]-x)!=abs(i[1]-y) for i in ls2)
# or: return not any(abs(i[0]-x)==abs(i[1]-y) for i in ls2)
In general, if you instantiate a variable (namely c) inside of a for loop, it's best not to use that variable outside of that for loop.
The practical reason for this is that you can't be sure that for loop will run and so the variable might not get instantiated. The more high-level reason is to maintain a sense of scope in your code, or "what happens in the for loop, stays in the for loop", if you will.
So in your case, I would recommend instantiating c with a 'default' value (depending on what your logic is) before the for loop starts, so that even if the for loop runs 0 times, c still has a value.
Alternatively, this entire function could be implemented as
def p3(x, y, ls2):
return not any([abs(i[0]-x)==abs(i[1]-y) for i in ls2])
i have this situation: a list of variables initially set to none
A = [none, none, none, none]
and a very simple function that controls if 2 values (different to none) are different:
def notEqual(a, b):
if a is None and b is None:
return True
if a != b:
return True
return False
I want create a list named bigList that shows for each couple of element of A if they are equal or not. So i thought to do this:
for i in range(4):
for j in range(4):
if i != j:
c = ((i, j), (notEqual(A[i], A[j])))
bigList.append((c))
So at the beginning all the element of bigList are ((i,j), (True))
In a second moment i have this situation:
A[0]=10 A[1]=10
So the condition associated to (0,1) and (1,0) have to change to False.
Is there an easy way to do something like this? (Change some conditions when some variables change their values)
No, there is no way. In most languages, expression are evaluated with current values of the variables. You can't make an expression that works like not_equal(current_value_of_A, current_value_of_B) that will automatically change when values of A and/or B change. So, in one way or another, you have to re-run your code.
A common way of doing something similar is the observer pattern. That is, wrap your expression in a class and notify the class when the value of something changes.
Along with that, use a dict instead of a list, which has the form {(i,j): notEqual(A[i], A[j]), so you can update only the individual (i, j) pair without re-running your whole code
You, can use #propery of python. It works like getter similar to other languages like C# and JAVA.
In your case you can make a object similar to that of ((i, j), (notEqual(A[i], A[j]))) with a getter.
See sample implementation below
class bigListElement(object):
A = [] # this is static
def __init__(self, index_tuple, areEqual):
self.index_tuple = index_tuple
self._areEqual = areEqual
#staticmethod
def notEqual(a, b):
if a is None and b is None:
return True
if a != b:
return True
return False
#property
def areEqual(self):
return bigListElement.notEqual(bigListElement.A[self.index_tuple[0]], bigListElement.A[self.index_tuple[1]])
print("Hello World")
bigListElement.A = [10, 2, 10, 3, 4]
a = bigListElement((0, 1), False)
print(a.areEqual) # True
bigListElement.A[1] = 10
print(a.areEqual) # False
I want every element in l(which is a list) to be added to a.
When I run the function, it gives me '[]' every time. How can I fix this?
def sim(l):
a = []
if len(l)>0:
a = a.append(l.pop())
l.pop()
return sim(l)
return a
Several things are wrong:
You shouldn't use lowercase L for a variable name - it looks like one
At the top of the function you assign an empty list to a - ultimately sim will be called with an empty list, then a will be assigned an empty list, the conditional statement will fail and sim will return an empty list.
Inside the conditional statement you assign the return value of list.append() to a. The return value is None so whatever a was before, it gets wiped out.
Inside the conditional statement you pop() two items out of your control list
An empty list has a boolean value of false so there is no need to explicitly check its length,
def sim(el, a = None):
if el:
a.append(el.pop())
return sim(el, a)
return a
I was taught to write the base case of a recursive function as the first statement:
def sim(el, a = None):
if not el:
return a
a.append(el.pop())
return sim(el, a)
append() doesn't return anything but does update the existing list. In other words, by trying to assign the result of the append() method, you're setting a to nothing after you have already appended the item.
Your Code :def sim(l):
a = []
when you call Function recursively return sim(l) every time it is call sim(l) and a=[] is empty.
Try This :
def sim(l,a):
if len(l)>0:
a.append(l.pop())
print a
return sim(l,a)
return a
Is this a homework assignment where you're required to do it in a certain (overly complicated) way? Because if not, you can add one list to another in Python like so:
>>> l = [1, 2, 3]
>>> a = []
>>> a.extend(l)
>>> a
[1, 2, 3]
I'm working with this exercise:
Write a function is_member() that takes a value (i.e. a number, string, etc) x and a list of values a, and returns True if x is a member of a, False otherwise. (Note that this is exactly what the in operator does, but for the sake of the exercise you should pretend Python did not have this operator.)
I wrote this function:
def isMember(value, list):
for element in list:
if(element == value):
return True
else:
return False
myList = ["a","b","c",1,2,3]
print(isMember("a",myList)) #Returns True; correct
print(isMember(3,myList)) #Returns False; why the heck?
You need to take the return False out of the loop:
def isMember(value, list):
for element in list:
if(element == value):
return True
return False
The way you have it currently, isMember will return False if the value is not the first item in the list. Also, you should change the name of your list variable to something other than list, which is a built-in function in Python.
The problem is that your return False is within the loop, directly as the else case of your membership test. So as you loop through the list, you get to the first element and check if it is in the list or not. If it is in the list, you return true—that’s fine. If it’s not in the list, you return false, aborting the loop process and ending the function. So you never look at the other values inside the loop.
So to fix this, move the return False outside of the loop, at the end of the function. That way, only when all elements have been looked at, you return false.
def isMember (value, list):
for element in list:
if element == value:
return True
return False
Another way would be to simplify this using the any function to perform the check for every element in the list. any takes an iterable and looks at the values. As soon as it finds a true value, it returns true. Otherwise it keeps iterating until it finds a false value or hits the end of the iterator, both cases yielding a false. So you could rewrite it like this:
def isMember (value, list):
return any(value == element for element in list)
I am trying to write a function which is supposed to compare list structures (the values are indifferent). The problem is that I have two lists which are unequal but the function still returns True even though it actually goes into the else part. I don't understand why and what I did wrong. Here is my code:
def islist(p): #is p a list
return type(p)==type(list())
def ListeIsomorf(a,b):
if len(a)==len(b):
for i,j in zip(a,b):
if islist(i) and islist(j):
ListeIsomorf(i,j)
elif islist(i) or islist(j):
return(False)
return(True)
else:
print(a,"length from the list isn't equal",b)
return(False)
#example lists
ListeE = [[],[],[[]]]
ListeD = [[],[],[[]]]
ListeF = [[[],[],[[]]]]
ListeG = [[],[[]],[[]]]
ListeH = [1,[3]]
ListeI = [1,3]
#tests
print(ListeIsomorf(ListeD,ListeE)) # True
print(ListeIsomorf(ListeD,ListeF)) # False
print(ListeIsomorf(ListeD,ListeG)) # False
print(ListeIsomorf(ListeH,ListeI)) # False
So the problem only occurs with the third print(ListeIsomorf(ListeD,ListeG)) # False. It actually goes into the else part and does print the "length from the list isn't equal" but it doesn't stop and it doesn't give out the return(False). Am I missing something?
The problem is that when your function calls itself recursively:
ListeIsomorf(i,j)
it ignores the returned value.
Thus the comparisons that take place at the second level of recursion have no effect on what the top level returns.
Changing the above to:
if not ListeIsomorf(i,j):
return(False)
fixes the problem.