No result returned during recursion - python

So I was creating a simple recursive function which essentially compares two strings, 'string' and 'target', and if they're the same, the function replaces the 'target' with 'rep', much like the function of find and replace you would see in a text editor. My issue is, is that the function returns nothing. Is that because it hasn't hit my base case or am I missing an extra return somewhere?
def helperfn(string,target,rep,x): # x is always initially set to zero
if x==len(string): #base case
target=rep
return target
if len(string)==len(target):
if string[x]==target[x]:
helperfn(string,target,rep,(x+1))
else:
return "string and target are not the same"
A few examples of what the expected output should be:
helperfn("noway","noway","yes",0)=>"yes"
helperfn("ok","ok","never",0)=>"never"

When you call the function recursively, you want to return that value.
return helperfn(string,target,rep,(x+1))

It's because you never returned anything explicitly in one branch. Change
if len(string)==len(target):
if string[x]==target[x]:
helperfn(string,target,rep,(x+1))
to
if len(string)==len(target):
if string[x]==target[x]:
return helperfn(string,target,rep,(x+1))

Related

Passing return value to function

I'm having difficulty understanding how to use return values.
def grab_name(string):
return grab("users/self/profile", string)
def print_user_info(arg):
print(grab("users/self/profile", "janice"))
I need to consume the result of passing the first function in order to print the user info. But I'm not sure how to do that...the second function is not supposed to consume a string or call the function directly. I understand the return value doesn't exist outside the scope of the first function so I don't understand how to get the value into the second function without just calling it directly as I have above.
The first function is basically returning a dictionary and the second function needs to consume the result of calling the first function.
I think this small modification is what you are seeking.
def grab_name(string):
return grab("users/self/profile", string)
def print_user_info(arg):
print(grab_name("janice"))
def grab_name(string):
return grab("users/self/profile", string)
def print_user_info(arg):
return "janice"
print(print_user_info(grab_name))
result :
janice

can't do return function in condewrite

I'm trying to understand the difference between returning and printing (I get the theory behind it, but when actually designing the code, I'm a bit lost as to how they're different from each other). I'm trying to repeat the middle character in an inputted string coupled with a repetition (int).
Why doesn't this work? Either in python idle or ion codewrite?
def mid_repeated (st, rep):
if len(st)%2==0:
middle = (len(st)/2)
center = (st[middle])*rep
rep = "!"*rep
return center + " " + str(rep)
else:
middle = (len(st)/2)
center = (st[middle])*rep
rep = "!"*rep
return center + " " + str(rep)
return mid_repeated
As soon as a function returns something, it breaks. This is probably what you're wondering about.
However, I'm not exactly sure what you're trying to accomplish by returning the function itself. You may want to look at that again.
I'm not sure if this helps at all, but return, returns something that can then be used outside of the function, where as print, just prints something...
The difference between
def a(x):
print x
and
def b(x):
return x
is that they do different things. (No. Really?)
a() outputs the "thing" given as x and (implicitly) returns None.
b() does nothing but returning x.
The difference becomes clearer if you do
def examine(function):
print "Calling:"
ret = function(42)
print "Call done."
print "Function returned", ret
if I use this function to examine my functions,
examine(a)
prints
Calling:
42
Call done.
Function returned None
so you clearly see that the 42 is printed while the function runs and the function's return value is None.
OTOH,
examine(b)
prints
Calling:
Call done.
Function returned 42
which proves that the function prints nothing but giving the value provided back to the caller (as a return value), who is able to print it whenever appropriate, or do anything else with it.
Other point of view: print prints the given value immediately, return just gives it to the caller to do whatever is desired.

Unit test for the 'none' type in Python

How would I go about testing for a function that does not return anything?
For example, say I have this function:
def is_in(char):
my_list = []
my_list.append(char)
and then if I were to test it:
class TestIsIn(unittest.TestCase):
def test_one(self):
''' Test if one character was added to the list'''
self.assertEqual(self.is_in('a'), # And this is where I am lost)
I don't know what to assert the function is equal to, since there isn't any return value that I could compare it to.
Would assertIn work?
All Python functions return something. If you don't specify a return value, None is returned. So if your goal really is to make sure that something doesn't return a value, you can just say
self.assertIsNone(self.is_in('a'))
(However, this can't distinguish between a function without an explicit return value and one which does return None.)
The point of a unit test is to test something that the function does. If it's not returning a value, then what is it actually doing? In this case, it doesn't appear to be doing anything, since my_list is a local variable, but if your function actually looked something like this:
def is_in(char, my_list):
my_list.append(char)
Then you would want to test if char is actually appended to the list. Your test would be:
def test_one(self):
my_list = []
is_in('a', my_list)
self.assertEqual(my_list, ['a'])
Since the function does not return a value, there isn't any point testing for it (unless you need make sure that it doesn't return a value).

2 inputs to a function?

So Ive been giving the following code in a kind of sort of python class. Its really a discrete math class but he uses python to demonstrate everything. This code is supposed to demonstate a multiplexer and building a xor gate with it.
def mux41(i0,i1,i2,i3):
return lambda s1,s0:{(0,0):i0,(0,1):i1,(1,0):i2,(1,1):i3}[(s1,s0)]
def xor2(a,b):
return mux41(0,1,1,0)(a,b)
In the xor2 function I dont understand the syntax behind return mux41(0,1,1,0)(a,b) the 1's and 0's are the input to the mux function, but what is the (a,b) doing?
The (a, b) is actually the input to the lambda function that you return in the mux41 function.
Your mux41 function returns a lambda function which looks like it returns a value in a dictionary based on the input to the mux41 function. You need the second input to say which value you want to return.
It is directly equivalent to:
def xor2(a,b):
f = mux41(0,1,1,0)
return f(a,b)
That is fairly advanced code to throw at Python beginners, so don't feel bad it wasn't obvious to you. I also think it is rather trickier than it needs to be.
def mux41(i0,i1,i2,i3):
return lambda s1,s0:{(0,0):i0,(0,1):i1,(1,0):i2,(1,1):i3}[(s1,s0)]
This defines a function object that returns a value based on two inputs. The two inputs are s1 and s0. The function object builds a dictionary that is pre-populated with the four values passed int to mux41(), and it uses s0 and s1 to select one of those four values.
Dictionaries use keys to look up values. In this case, the keys are Python tuples: (0, 0), (0, 1), (1, 0), and (1,1). The expression (s1,s0) is building a tuple from the arguments s0 and s1. This tuple is used as the key to lookup a value from the dictionary.
def xor2(a,b):
return mux41(0,1,1,0)(a,b)
So, mux41() returns a function object that does the stuff I just discussed. xor2() calls mux41() and gets a function object; then it immediately calls that returned function object, passing in a and b as arguments. Finally it returns the answer.
The function object created by mux41() is not saved anywhere. So, every single time you call xor2(), you are creating a function object, which is then garbage collected. When the function object runs, it builds a dictionary object, and this too is garbage collected after each single use. This is possibly the most complicated XOR function I have ever seen.
Here is a rewrite that might make this a bit clearer. Instead of using lambda to create an un-named function object, I'll just use def to create a named function.
def mux41(i0,i1,i2,i3):
def mux_fn(s1, s0):
d = {
(0,0):i0,
(0,1):i1,
(1,0):i2,
(1,1):i3
}
tup = (s1, s0)
return d[tup]
return mux_fn
def xor2(a,b):
mux_fn = mux41(0,1,1,0)
return mux_fn(a,b)
EDIT: Here is what I would have written if I wanted to make a table-lookup XOR in Python.
_d_xor2 = {
(0,0) : 0,
(0,1) : 1,
(1,0) : 1,
(1,1) : 0
}
def xor2(a,b):
tup = (a, b)
return _d_xor2[tup]
We build the lookup dictionary once, then use it directly from xor2(). It's not really necessary to make an explicit temp variable in xor2() but it might be a bit clearer. You could just do this:
def xor2(a,b):
return _d_xor2[(a, b)]
Which do you prefer?
And of course, since Python has an XOR operator built-in, you could write it like this:
def xor2(a,b):
return a ^ b
If I were writing this for real I would probably add error handling and/or make it operate on bool values.
def xor2(a,b):
return bool(a) ^ bool(b)
EDIT: One more thing just occurred to me. In Python, the rule is "the comma makes the tuple". The parentheses around a tuple are sometimes optional. I just checked, and it works just fine to leave off the parentheses in a dictionary lookup. So you can do this:
def xor2(a,b):
return _d_xor2[a, b]
And it works fine. This is perhaps a bit too tricky? If I saw this in someone else's code, it would surprise me.

Why is this displaying None?

def characterLine(firstChar,secondChar,phrase):
'\n' + ((str(firstChar)+str(secondChar))*(len(phrase)/2)+len(phrase)%2* firstChar)
So the second part of the code will display but when I try to concatenate it with a line skip, it displays "None."
Can someone explain to me as to why this is happening?
if you are trying to print the return value of characterLine(..), i.e.
print characterLine(...)
this will print None because you are not using the return keyword in front of your expression. Setting
def characterLine(firstChar,secondChar,phrase):
return '\n' + ((str(firstChar)+str(secondChar))*(len(phrase)/2)+len(phrase)%2* firstChar)
should return a value other than None (which you then can print).
Be default, functions have an implied return None as the end.
An empty return-statement also returns None.
So, you just need to add the return-statement to your function. Otherwis, the rest of it looks okay. Good luck :-)

Categories