The title is a little weird, but I don't know exactly how this is called, so plz forgive me with the abstract title....
I've found a code like this online:
def lcs(xstr, ystr):
"""
>>> lcs('thisisatest', 'testing123testing')
'tsitest'
"""
if not xstr or not ystr:
return ""
x, xs, y, ys = xstr[0], xstr[1:], ystr[0], ystr[1:]
if x == y:
return x + lcs(xs, ys)
else:
return max(lcs(xstr, ys), lcs(xs, ystr), key=len)
I am new to python, and I don't understand how you can call lcs(xs, ys) in
return x + lcs(xs, ys)
To my understanding, lcs() is not yet fully defined, and I'm confused how you can call a function of itself inside itself....
Also, I don't know what key = len is doing in
max(lcs(xstr, ys), lcs(xs, ystr), key=len)
I know how max( 1st, 2nd ) works, but I don't know what the third parameter is doing. What does "key" mean, and why is "len" used as a value of "key"?
This is called recursion. The body of the function isn't evaluated at all until you call it. Think of lcs in the body as just a name; when you call the function, Python will apply the same lookup rules it applies to any name to see what it refers to; typically* it refers to the same function.
*Typically, because you can break a recursive function by playing some games with the names.
def foo():
print("hi")
foo()
g = foo
def foo():
print("new function")
If you call g(), it will output
hi
new function
instead of print an infinite stream of lines containing hi. (Well, almost infinite; eventually you'll get a RuntimeError because Python caps the size of the call stack.)
Related
def square(x):
return lambda x: x**2
object = (1,2,3)
print (object[0])
print (square(object[0]))
output =
1,
<function square.. at 0x03494F10>
Why did the square not work for the tuple element?
Square is returning a pointer to a function, if you want to actually execute the function, you should write:
print (square(object[0])())
lambda is the syntax to create an anonymous function.
square = lambda x: x**2
is equivalent to...
def square(x):
return x**2
The latter is preferred for clarity and is how your code ought to have looked. You aren't usually supposed to assign your lambda expressions to names like square - they are a convenience for those times when you're supposed to pass a function as an input to something else and want to define one in-place - but nothing actually prevents you from doing so.
If you check the printed output you'll see that it is in fact telling you that it's returned a function.
EXAMPLE: Why dictuse1 return value but dictuse2 return address as specified below
def dictuse1(operator,x,y):
return{
'add':lambda:x + y,
'sub':lambda:x - y,
'mul':lambda:x * y,
'div':lambda:x / y,
}.get(operator,lambda:None)()
def dictuse2(operator,x,y):
return{
'add':lambda:x + y,
'sub':lambda:x - y,
'mul':lambda:x * y,
'div':lambda:x / y,
}.get(operator,lambda:None) #No parentheses here compared to previous function
d = dictuse1('add',8,9)
print(d) #return 17
a = dictuse2('a',5,4)
print(a) #returns:<function dictuse.<locals>.<lambda> at 0x7f30d23f3ea0>
The parentheses have nothing to do with the return; they’re there to call a function, the same way you always call a function.
Let’s break this down into a more readable form:
function_table = {
'add': lambda: x + y,
'sub': lambda: x - y,
'mul': lambda: x * y,
'div': lambda: x / y,
}
So far, so good: this is just a dictionary that maps strings to functions, so you can look the functions up by name.
default_function = lambda: None
This is just a function that you can call and get back None.
function = function_table.get(operator, default_function)
This is just looking up a value in a dict. d.get(key, default) gives you d[key] if there is a value with that key, or default if there isn’t.
So, now function is that add function lambda: x+y, or the default lambda: None, or any of the other three , but whichever one it is, it’s a function that takes no parameters. So we can call It. This is where the parentheses come in:
value = function()
And now we just return that value:
return value
If you left the parentheses off, you wouldn’t be calling the function and returning the value it gives you, you’d just be returning it. So, instead of getting back 5 or None, you’d get back a function object. If you try to print that out, maybe it’ll say something like <function '<lambda>' at 0x12345788>, but it doesn’t really matter what it says; all it’s telling you is that the thing you’re printing is some function, and it has no name because you defined it with lambda instead of def.
Try splitting such one-liners on some meaningful parts.
def dictuse1(operator, x, y):
# Stores mapping from operator names (strings)
# to op implementations (functions == lambdas)
optable = {
'add': lambda: x + y,
'sub': lambda: x - y,
'mul': lambda: x * y,
'div': lambda: x / y,
}
# Define a default op
noop = lambda: None
# Take the function by op name
op = optable.get(operator, noop)
# Exectute it and return a returning value of that function.
return op() # remove () and you have a dictuse2 here.
The only difference between dictuse1 and dictuse2 that the last one returns the function instead of the result of the invocation of that function.
Because in Python everything is an object. This includes integers, floating-point numbers, strings, instances of other classes, classes themselves and functions.
The first function retrieves a function from the dictionary or uses the default value and calls it, returning the result of the call (a number in your case).
The second one returns the function itself.
The parentheses are notation for function call: (lambda x, y: x + y)(1, 2), for example, calls the function and returns 1 + 2 == 3. If you remove the parentheses, you'll get a function object.
Because get method on dictionary return a default value if the key you are looking for is not in the dictionary, When you passed a which is not in the dictionary it returned lambda:None which is a anonymous function and to execute the function you have to call with paranthesis
I have functions that use returned variables.
How do I call them in a main function like this:
text = 'a'
def a(text):
text = x
return x
def b(x):
x = z
return z
def main():
# What do I put here to call function a and b?
main()
How do I call them
You already know how to call them ;)
def main():
...
main()
So I assume you are bewildered by:
def a(text):
text = x
return x
That x is not defined in a nor is it passed by argument to it. But that's OK. In python, all variables defined outside function are still visible inside it. Only exception is if argument of function have the same name as one of those variables. Then argument will take precedence.
This mechanism is called closure. Function close over some variable that already exists in scope when function is defined.
You can learn about it some more here:
https://www.learnpython.org/en/Closures
text = 'a'
def a(text):
text = x
return x
def b(x):
x = z
return z
def main():
x = a(text)
z = b(x)
main()
This might be what you want
It is not clear what are you trying to achieve. You are using variable x in the function a and variable z in function b without defining these two variables.
Moreover, you are setting variable text in function a without capturing it using statement global, look here for more information.
And global variables are considered to be bad practice.
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.
I'm new to programming.
def start():
x = 4
def addition():
n = 3
def exponential():
z = 2
def multiplication():
l = 2
print(x + n ** z * l)
return multiplication
equals = start()
equals()
why am I getting a "Nonetype" object is not callable error?
You're confusing a bunch of programming concepts:
Don't declare a function whenever you only need a statement
You're confusing function declaration with function call (invocation), and also the nesting is pointless. Declaring nested fn2 inside of fn1 doesn't magically also call fn2 and also transmit its return-value back to fn1. You still have to use an explicit return-statement from each fn.(If you forget that, you're implicitly returning None, which is almost surely not what you want)
For now, just don't ever nest functions at all.
Functions with no arguments are essentially useless, they can't take inputs and compute a result. Figure out what their arguments should be.
Specifically for the code you posted, addition(), multiplication() don't have any return value at all, i.e. None. exponential() returns multiplication, i.e. a function which only returns None. But then, both addition() and start() ignore that anyway, since they don't have a return-statement either, hence they implicitly return None.
Calling start() just gives you None, so you're just assigning equals = None. Not the result of some mathematical expression like you intended.
So:
reduce every unnecessary function to just a statement
declare each of your functions separately (non-nested)
each fn must have args (in this case at least two args, to make any sense)
each fn must have a return statement returning some value
only declaring a function and never calling it means it never gets run.
put an empty line in between function declarations (Then it's obvious if you forgot the return-statement)
Credits goes to #BrenBarn for being first to answer this. But I wanna post the code to make it more clear, and point out to some ways to make it better.
def start():
x = 4
def addition():
n = 3
def exponential():
z = 2
def multiplication():
l = 2
print (x + n ** z * l)
return multiplication()
return exponential()
return addition()
equals = start()
print equals #Output: 22
However, this is not the best way to list different methods. You should learn how to use a class in your python code.
I am going to define a class called "mathOperations". I will define three methods (functions): addition,exponential, multiplication. These functions are reusable.
class mathOperations():
def addition(self,x,y):
return x+y
def exponential(self,x,y):
return x**y
def multiplication(self,x,y):
return x*y
m= mathOperations()
z=2
l=2
x=4
n=3
result= m.addition(x,m.multiplication(m.exponential(n,z),l))
print result #Output:22
You should learn how to make your code reusable, try to google "procedural programming"; "Oriented Object Programming", or check "Learn Python the hard way" book. These are first and most used approach to make your code reusable. Think of it like a generic mathematical function to solve problems.