Call Function of inside function in Python - python

I have some Python code in below written in Python 2.7 and I have problem with calling a function form inside another function.
class CSP:
def __init__(self, matrix):
self.X = []
self.D = []
self.C = []
self.matrix = util.copyMatrix(matrix)
self.counter = 0
# Matrix to Vector
vector = [item for line in self.matrix for item in line]
chars = map(str, vector)
result = ['*' if item == '0' else item for item in chars]
def solve(self):
""" Returns the result matrix.
The sudoku matrix is self.matrix.
Use util.printMatrix in purpose of debugging if needed. """
"*** YOUR CODE HERE ***"
def init(self,result):
for i in range(9):
for j in range(1,10):
var = var_char[i]+str(j)
self.X.append(var)
domain = set([1,2,3,4,5,6,7,8,9])
self.D.append(domain)
gamelist = result
for i in range(len(gamelist)):
if(re.match("\d+",gamelist[i])):
self.D[i] = set([int(gamelist[i])])
self.set_constraints()
#########################################################################
def set_constraints(self):
for x in self.X:
for y in self.X:
if((x[0] == y[0] and x[1] != y[1]) or (x[1] == y[1] and x[0] != y[0])):
flag = True
for c in self.C:
if(x in c and y in c):
flag = False
if(flag):
self.C.append(set([x,y]))
for a in [0,3,6]:
for b in [0,3,6]:
self.set_cube_constraints(a,b)
How to call init() function in solve() and also call self.set_constraint() inside init() function?

Within function solve(), init() is a function, not a method. Therefore it can only be called in the same manner that any other unbound function can be called: by passing the correct number of arguments to it. This would work:
init(self, results)
Note that you need to explicitly pass a reference to the object in self because init() is not a method. Within solve() self refers to the CSP instance, so this should work.
However, set_constraints() is also a normal function, so you can not call it from init() with self.set_constraints(), but set_constraints(self) should work. Note that you need to declare function set_constraints() before init() otherwise you will get a "referenced before assignment" error.
Having said all that, this is just awful. Why not make init() and set_constraints() proper methods of the class?

set_constraints is not a part of the class and therefore cannot be called with self.
If you put it one level up (remove one indentation level of it) then your code should work better.
I can see that this is some kind of coding exercise and you are told to write code in one particular place. I think you may be overcomplicating the answer because what you are coding here looks very messy by design and you should probably split out your functionality a lot more if this should be considerered clean code.

Related

Example of how to properly define a class in python

I have defined a function as such:
def quicksort(points):
if len(points) < 2: return points
smaller,equal,larger = [], [], []
pivot_angle = find_polar_angle(random.randint(0, len(points) - 1))
for pt in points:
pt_angle = find_polar_angle(pt)
if pt_angle < pivot_angle:
smaller.append(pt)
elif pt_angle == pivot_angle:
equal.append(pt)
else:
larger.append(pt)
return quicksort(smaller) + sorted(equal, key = find_dist) + quicksort(larger)
Now, I want to change my code - which btw is an implementation of the Graham Scan Algorithm - into an object oriented code. So I went ahead and declared a class in a file MyClasses.py:
from MyFunctions import find_anchor, find_polar_angle, find_dist, find_det, quicksort, graham_scan
class Cluster:
def __init__(self):
self.members = []
self.hull = []
self.anchor = None
self.find_anchor = find_anchor
self.find_polar_angle = find_polar_angle
self.find_dist = find_dist
self.find_det = find_det
self.quicksort = quicksort
self.graham_scan = graham_scan
But of course I have to change my functions as well. I don't want to list all the functions here, that's why I stay with the quicksort function as an example. This is where I struggle a lot, since I don't know the python syntax well enough to be sure about what I am doing here. This is my revised form of quicksort:
def quicksort(self, points):
if len(points) < 2: return points
smaller,equal,larger = [], [], []
pivot_angle = self.find_polar_angle(self, random.randint(0, len(self.members) - 1))
for pt in points:
pt_angle = self.find_polar_angle(self, pt)
if pt_angle < pivot_angle:
smaller.append(pt)
elif pt_angle == pivot_angle:
equal.append(pt)
else:
larger.append(pt)
return self.quicksort(self, smaller) + sorted(self, equal, key = self.find_dist) + self.quicksort(self, larger)
Here's the thing: This function is recursive! So I need it to take smaller, equal and larger as arguments. Later, another function graham_scan is going to call this function as such:
self.members = self.quicksort(self, self.members)
I know there are probably many mistakes in here. That's why I'm asking: Is this last expression a valid expression? I mean I am changing a class-variable (self.members) but I do so not by directly changing it, but by assigning it the return value of quicksort.
Anyways, help is very much appreciated!
To make an existing function as a new property of a new class, try this:
def quicksort():
pass # your custom logic
class Cluster:
def __init__(self):
self.members = []
self.quicksort = quicksort
# more properties
Python has quite a different syntax to C++ or Java.
To say about the second question, all the variables used in quicksort function body are only available in that function only.
About second question. All members of classes are PUBLIC in python. By convention you can add "_" and "__" in front of the names for protected and private respectfully. BUT this does NOT prevent you from accessing them, it just means that you (or whoever reading the code) should not misuse them.
Although, __variable must be accessed with following syntax outside of class:
class Square:
def __init__(self, x):
self.__x = x
def get_surface(self):
return self.__x **2
>>> square1 = Square(5)
>>> print(square1.get_surface())
>>> 25
>>> square1._Square__x = 10
>>> print(square1.get_surface())
>>> 100
>>> square1.__x
>>> **AttributeError: 'Square' object has no attribute '__x'**
Or it will raise AttributeError. Hope this helps

Why am I getting this error "NameError:name 'self' is not defined."

As a way of practicing python I'm trying to write a little program that creates sudoku puzzles. I've found multiple questions similar to my issue but none seem to exactly relate.
#!usr/bin/python3
from random import randint
class Puzzle :
def __init__(self, **puzzle):
puzzle = [[0 for x in range(9)]for y in range(9)]
def createEasy(self):
count = 0
while(count < 32):
i = randint(0,8)
j = randint(8,9)
k = randint(1,9)
if (self.puzzle[i][j] != 0):
self.puzzle[i][j] = k
count += 1
def createMedium(self):
count = 0
while(count < 30):
i = randint(0,8)
j = randint(8,9)
k = randint(1,9)
if (self.puzzle[i][j] != 0):
self.puzzle[i][j] = k
count += 1
def createHard(self):
count = 0
while(count < 26):
i = randint(0,8)
j = randint(8,9)
k = randint(1,9)
if (self.puzzle[i][j] != 0):
self.puzzle[i][j] = k
count += 1
def main():
print("Welcome to sudoku!!!")
answer = input( "what level of difficultly do you want today?")
if (answer == "easy"):
self.createEasy()
for x in Puzzle.puzzle:
for y in x:
print(y)
print('\n')
Puzzle.main()
Most answers I found either had to do with functions not being defined in the right order or not putting "self" in the parameter list of all the functions. One answer even said to get rid of "self" parameter in the init function but that didn't help either. I also found this answer though I don't think it relates either. NameError: name 'self' is not defined The only thing I can think of is that I need to declare the list called puzzle elsewhere since it's suppose to be a class variable but from python code I've I don't think that's true not to I'm not sure since it's 2d and writing puzzle = [][] is wrong.
Sorry here's the whole output with error.
Welcome to sudoku!!!
what level of difficultly do you want today?easy
Traceback (most recent call last):
File "sudoku_maker.py", line 49, in <module>
Puzzle.main()
File "sudoku_maker.py", line 43, in main
self.createEasy(self)
NameError: name 'self' is not defined
It seems like you want main() to be a class method or a static method rather than an instance method. Class methods are methods that are not bound to an object but to a class. In that case, you need to define it clearly.
https://docs.python.org/3.5/library/functions.html#classmethod
https://docs.python.org/3.5/library/functions.html#staticmethod
This answer clearly explains the difference between class methods and static methods.
What is the difference between #staticmethod and #classmethod in Python?
One more way of solving your problem is :
Make main() as an instance method by passing self as an argument.
main(self)
Create an object of Puzzle.
puzzle = Puzzle()
Call the object's main method.
puzzle.main()
The error disappears if you make the following changes:
Add self as a parameter of the main() function.
Create an instance of the class: p = Puzzle() and call p.main() then.
Write self.puzzle in the __init__ function instead of just puzzle.
(Then there are different errors though not related to this one)
First of all, in __init__ method when you declare puzzle attribute, you forgot the self, so it is not declared:
def __init__(self, **puzzle):
self.puzzle = [[0 for x in range(9)] for y in range(9)]
You also forgot de self when declaring the main function. And, inside of this one you got an error too, when you call Puzzle.puzzle, it should be with the self instance:
def main(self):
print("Welcome to sudoku!!!")
answer = input( "what level of difficultly do you want today? ")
if (answer == "easy"):
self.createEasy()
for x in self.puzzle:
for y in x:
print(y)
print('\n')
And finally, when you call the function. You need to create the instance of Puzzle first, but you are using Puzzle.main, so your not initializing the object, so the self instance will not exist.
You have to do it like this:
Puzzle().main()
However, there's another error when using randint(a, b), because this function generate a random int between a and b, but including the limits, so when you call it in createEasy, the 9 should not be in the limits.

List of objects function not working

Sorry for the title, I hope it reflects correctly my problem :
In the following code, I was expecting the result to be result 0 1 2 but instead I have 2 2 2. The code inside my_function seems to be interpreted with the last instance of obj. What is wrong ?
class Example:
def __init__(self, x):
self.x = x
def get(self):
return self.x
a_list = []
for index in range(3):
obj = Example(index)
def my_function(x):
#some stuff with x like obj.another_function(x)
return obj.get()
a_list.append(my_function)
for c in a_list:
print(c())
When you define this
def my_function():
return obj.get()
Python will understand that my_function should run the get() method of an object called obj and return the value. It won't know the value of obj and what the get() method does until you attempt to call it.
So, you are actually defining three different functions that will eventually do the same thing. And, in the end, running the same code thrice.
But why is the return 2 2 2?
Because after the last iteration, the value of obj is Example(2)* because you redefine its value at every iteration, and the last one remains.
*
because of this line obj = Example(index)
Understanding a few things about how python works will help you understand what's happening here. Here obj is a closure, closures are evaluated at call time, not when the function is defined so if I do this:
x = "hello"
def printX():
print x
x = "goodbye"
printX() # goodbye
I get "goodbye" because printX is referencing a global variable in my module, which changes after I create printX.
What you want to do is create a function with a closure that references a specific object. The functional way to do this is to create a function that returns another function:
x = "hello"
def makePrintX(a):
def printX():
# We print a, the object passed to `makePrintX`
print a
return printX
# x is evaluated here when it is still "hello"
myPrintX = makePrintX(x)
x = "goodbye"
myPrintX() # "hello"
If you're having trouble understanding the above example I would recommend reading up on python's scoping rules. For your example, you could do something like this:
class Example:
def __init__(self, x):
self.x = x
def get(self):
return self.x
def makeObjFunction(obj):
def objFunction(x):
return obj.get()
return objFunction
a_list = []
for index in range(3):
obj = Example(index)
my_function = makeObjFunction(obj)
a_list.append(my_function)
for c in a_list:
print(c("some value"))
You are appending three my_functions to the a_list which are all closures over the same Example object. Try:
def my_function():
return obj
<__main__.Example object at 0x0054EDF0>
<__main__.Example object at 0x0054EDF0>
<__main__.Example object at 0x0054EDF0>
You can see they have the same id so calling get() on each should give the same answer.
If you just append the obj.get function (and drop the my_function) it'll work fine.
a_list.append(obj.get)
....
0
1
2
Edit: You've updated your question so to let you do more stuff in my_function(). It's still basically a scoping problem.
def my_func_factory(p_obj):
def my_function(x):
#some stuff with x like obj.another_function(x)
return p_obj.get()
return my_function
for index in range(3):
obj = Example(index)
a_list.append(my_func_factory(obj))
Since my_function can't see obj being reassigned, each instance doesn't pick up the change.
I think append() during the for just append the function address in a_list[]. After for iteration, the a_list is really given the number. Then it discovers the address of my_function, and they get the number in my_function, this is, 2. That's why you get [2,2,2].
Or maybe, in my_function, function give the method of "obj". But for iteration change the "obj" memory address each time, so the symbol "obj" always aim to the newest object Example. Due to my_function always get "obj", you get the same number from the last object.

Static variable in Python?

In C++ we have static keyword which in loops is something like this:
for(int x=0; x<10; x++)
{
for(int y=0; y<10; y++)
{
static int number_of_times = 0;
number_of_times++;
}
}
static here makes number_of_times initialized once. How can I do same thing in python 3.x?
EDIT: Since most of the people got confused I would like to point out that the code I gave is just example of static usage in C++. My real problem is that I want to initialize only ONE time variable in function since I dont want it to be global(blah!) or default parameter..
Assuming what you want is "a variable that is initialised only once on first function call", there's no such thing in Python syntax. But there are ways to get a similar result:
1 - Use a global. Note that in Python, 'global' really means 'global to the module', not 'global to the process':
_number_of_times = 0
def yourfunc(x, y):
global _number_of_times
for i in range(x):
for j in range(y):
_number_of_times += 1
2 - Wrap you code in a class and use a class attribute (ie: an attribute that is shared by all instances). :
class Foo(object):
_number_of_times = 0
#classmethod
def yourfunc(cls, x, y):
for i in range(x):
for j in range(y):
cls._number_of_times += 1
Note that I used a classmethod since this code snippet doesn't need anything from an instance
3 - Wrap you code in a class, use an instance attribute and provide a shortcut for the method:
class Foo(object):
def __init__(self):
self._number_of_times = 0
def yourfunc(self, x, y):
for i in range(x):
for j in range(y):
self._number_of_times += 1
yourfunc = Foo().yourfunc
4 - Write a callable class and provide a shortcut:
class Foo(object):
def __init__(self):
self._number_of_times = 0
def __call__(self, x, y):
for i in range(x):
for j in range(y):
self._number_of_times += 1
yourfunc = Foo()
4 bis - use a class attribute and a metaclass
class Callable(type):
def __call__(self, *args, **kw):
return self._call(*args, **kw)
class yourfunc(object):
__metaclass__ = Callable
_numer_of_times = 0
#classmethod
def _call(cls, x, y):
for i in range(x):
for j in range(y):
cls._number_of_time += 1
5 - Make a "creative" use of function's default arguments being instantiated only once on module import:
def yourfunc(x, y, _hack=[0]):
for i in range(x):
for j in range(y):
_hack[0] += 1
There are still some other possible solutions / hacks, but I think you get the big picture now.
EDIT: given the op's clarifications, ie "Lets say you have a recursive function with default parameter but if someone actually tries to give one more argument to your function it could be catastrophic", it looks like what the OP really wants is something like:
# private recursive function using a default param the caller shouldn't set
def _walk(tree, callback, level=0):
callback(tree, level)
for child in tree.children:
_walk(child, callback, level+1):
# public wrapper without the default param
def walk(tree, callback):
_walk(tree, callback)
Which, BTW, prove we really had Yet Another XY Problem...
You can create a closure with nonlocal to make them editable (python 3.x only). Here's an example of a recursive function to calculate the length of a list.
def recursive_len(l):
res = 0
def inner(l2):
nonlocal res
if l2:
res += 1
inner(l2[1:])
inner(l)
return res
Or, you can assign an attribute to the function itself. Using the trick from here:
def fn(self):
self.number_of_times += 1
fn.func_defaults = (fn,)
fn.number_of_times = 0
fn()
fn()
fn()
print (fn.number_of_times)
Python doesn't have static variables by design. For your example, and use within loop blocks etc. in general, you just use a variable in an outer scope; if that makes it too long-lived, it might be time to consider breaking up that function into smaller ones.
For a variable that continues to exist between calls to a function, that's just reimplementing the basic idea of an object and a method on that object, so you should make one of those instead.
The another function-based way of doing this in python is:
def f(arg, static_var=[0]):
static_var[0] += arg
As the static_var object is initialised at the function definition, and then reused for all the calls, it will act like a static variable. Note that you can't just use an int, as they are immutable.
>>> def f(arg, static_var=[0]):
... static_var[0] += arg
... print(static_var[0])
...
>>> f(1)
1
>>> f(2)
3
>>> f(3)
6
You can also use the global keyword:
def main(args):
for i in xrange(10):
print i
global tmp
tmp = i
But be careful... I most cases it will add more issues than it solves.
Use defaultdict:
from collections import defaultdict
static = defaultdict(lambda: 0)
def myfunc():
for x in range(10):
for y in range(10):
static['number_of_times'] += 1

Use output of one function and average it in another function

please keep in mind that while I showcase my code, that I am fairly new to programming. So please forgive any problems. I am writing a piece of python code that uses the output of one function and then averages it in another function. I am having troubling proceeding on how to do that, this is what I have so far:
def avg(A):
if not A:
return 0
return sum(A) / len(A)
Using the function above, I have to use it to calculate the average of the function produced below:
def SampleFunction(): # Example Function
A = list(range(300))
for i in range(300):
if i%2:
A[i] = 3.1*(i+1)**1.2 - 7.9*i
else:
A[i] = 4.2*(i+2)**.8 - 6.8*i
return A
Below this is a function I have trying to tie the two together.
def average(SampleFunction):
if len(SampleFunction) == 0: return 0
return sum(SampleFunction) / len(SampleFunction)
def avg(A):
if not A:
return 0
return sum(A) / len(A)
def SampleFunction(): # Example Function
A = list(range(300))
for i in range(300):
if i%2:
A[i] = 3.1*(i+1)**1.2 - 7.9*i
else:
A[i] = 4.2*(i+2)**.8 - 6.8*i
return avg(A) #Return the avg of A instead of just A
You are right at the moment of passing SampleFunction as parameter, but it's a function, you have to call invoke it inside average():
def average(some_function):
result = some_function() # invoke
return avg(result) # use the already defined function 'avg'
When you call it, pass the function you want to average():
print average(SampleFunction)
Note:
I would recommend you to follow Python naming conventions. Names like SomeName are used for classes, whereas names like some_name are used for functions.

Categories

Resources