python return none instead of True/False - python

I have two programs for searching using binary search in Python
Program 1:
def bin(alist,x):
if len(alist)==0:
return False
else:
mid=len(alist)//2
if (alist[mid]==x):
return True
else:
if alist[mid] < x:
#print(alist[mid+1:],x)
bin(alist[mid+1:],x)
else:
#print(alist[:mid],x)
bin(alist[:mid],x)
print (bin([2,3,5,8,9],8))
print (bin([2,3,5,8,9],7))
Program output:
None
None
Program 2:
def bin(alist,x):
if len(alist)==0:
return False
else:
mid=len(alist)//2
if (alist[mid]==x):
return True
else:
if alist[mid]<x:
return bin(alist[mid+1:],x)
else:
return bin(alist[:mid],x)
print(bin([1,5,7,8,9],10))
print(bin([1,4,5,8,9],8))
Program output:
False
True
Why is it so?

In your program 1, only when the list is empty or the value you are searching for in the middle of the list, it would returns you boolean value, that's because you explicitly say return if len(alist)==0 and return True when it meets if (alist[mid]==x):, you have to do the same for the rest conditions as well
def bin(alist,x):
if len(alist)==0:
return False
else:
mid=len(alist)//2
if (alist[mid]==x):
return True
else:
if alist[mid] < x:
#print(alist[mid+1:],x)
bin(alist[mid+1:],x) # -------> return
else:
#print(alist[:mid],x)
bin(alist[:mid],x) # -------> return
When you invoke your bin() method recursively and expect a boolean value, you have to add return in the above highlighted lines.

Related

Why does one part of conditional statements in Python returns None while others are ok?

I need to write a code that prints out valid or invalid for an input of letters and numbers for a license plate. The conditions are: first two characters must be letters, characters have to be between 2 and 6, and if numbers are used, 0 should not be the first, nor should a number appear before a letter.
I put the code below on Thonny and cannot understand why len(l) == 4 part of the conditional statement for def valid_order() returns None and does not execute the next line of the code whereas others work fine. My code should return "Valid" for CSAA50, but it returns invalid. Why?
Also, is there an elegant way to write def valid_order()?
def main():
plate = input("Plate: ")
if is_valid(plate):
print("Valid")
else:
print("Invalid")
def is_valid(s):
if s[0:2].isalpha() and 6 >= len(s) >= 2 and s.isalnum() and valid_order(s):
return True
else:
return False
def valid_order(c):
n = []
l = list(c[2:len(c)])
for i in c:
if i.isdigit():
n += i
if n and n[0] == "0":
return False
if len(l) == 2:
if l[0].isdigit() and l[1].isalpha():
return False
if len(l) == 3:
if l[0].isdigit():
if l[1].isalpha() or l[2].isalpha():
return False
else:
if l[1].isdigit() and l[2].isalpha():
return False
if len(l) == 4:
if l[0].isdigit():
if l[1].isalpha() or l[2].isalpha() or l[3].isalpha():
return False
else:
if l[1].isdigit():
if l[2].isalpha() or l[3].isalpha():
return False
else:
if l[2].isdigit() and l[3].isalpha():
return False
else:
return True
main()

Using a recursive bisection search to check if a character is in a string

My code is here:
def isIn(char, aStr):
mid = len(aStr)//2
if len(aStr)==0:
return False
elif len(aStr)==1:
if char == aStr:
return True
elif aStr[mid] == char:
return True
if mid == 0 and len(aStr) != 1:
return False
else:
if char > aStr[mid]:
return isIn(char,aStr[mid:] )
else:
return isIn(char,aStr[0:mid])
my code works for when the character is present in the string, if the test case is such that if the character that I want to search in the string is not actually present in the string, then the code goes into an infinite loop.
For example in the test case isIn('m','iloruuyz') the code goes into an infinite loop.
On the if len(aStr) == 1: condition, you only return True if the condition is met, but not False if the condition is not, that is where the infinite loop is occuring :)
def isIn(char, aStr):
mid = len(aStr)//2
if len(aStr)==0:
return False
elif len(aStr)==1:
if char == aStr:
return True
else: # Else return false to stop the infinite loop
return False
elif aStr[mid] == char:
return True
if mid == 0 and len(aStr) != 1:
return False
else:
if char > aStr[mid]:
return isIn(char,aStr[mid:] )
else:
return isIn(char,aStr[0:mid])

Blank List, Return False

I'm looking to write a function definition named has_evens that takes in sequence of numbers and returns True if there are any even numbers in the sequence and returns False otherwise.
My code is correct, except when it receives something empty, like "([])". I need to account for that. Here's my code:
def has_evens(s):
for num in s:
if num % 2 == 0:
return True
elif num % 2 != 0:
return False
if ([]):
return False
The final part is a desperate attempt to account for blank lists. More formally, it needs to pass this assertion:
assert has_evens([]) == False
You should only return True when an even is found:
def has_evens(s):
for num in s:
if num % 2 == 0:
return True
return False
Python has an any function to make this simpler:
def has_evens(s):
return any(num % 2 == 0 for num in s)
I answered my own question. I just needed to un-indent my lines
def has_evens(s):
for num in s:
if num % 2 == 0:
return True
else:
return False

Incorrect return value, not getting a 'True' return, Python

I am expecting a return of True, but is getting a return of None.
I have put some print statement in the code to help debug. It shows that the 'print("Got True")' statement ran, so I know the code ended up in the right branch of the code just before 'return True' but for some reason I am getting 'None'. However 'return False' works perfectly when I put in a word that isn't a palindrome.
Thanks for the help.
def first(word):
return word[0]
def last(word):
return word[-1]
def middle(word):
return word[1:-1]
def is_palindrome(word):
print(word)
if len(word) <= 1:
print("Got True")
return True
else:
print(len(word))
if first(word) == last(word):
is_palindrome(middle(word))
else:
print("Got False")
return False
print(is_palindrome('allen'))
print("\n")
print(is_palindrome('redivider'))
Output:
allen
5
Got False
False
redivider
9
edivide
7
divid
5
ivi
3
v
Got True
None
You need to return in every branch of your function, e.g.:
def is_palindrome(word):
print(word)
if len(word) <= 1:
print("Got True")
return True
else:
print(len(word))
if first(word) == last(word):
return is_palindrome(middle(word)) # **Added return**
else:
print("Got False")
return False
But you can simplify the structure because if you return then you don't need the else: clause because it can't be reached, so this can be written:
def is_palindrome(word):
print(word)
if len(word) <= 1:
print("Got True")
return True
print(len(word))
if first(word) == last(word):
return is_palindrome(middle(word))
print("Got False")
return False
Even in a recursive function, you have to use a return statement to return a value:
if first(word) == last(word):
return is_palindrome(middle(word))
You should return the result in every possible conditional branches. You can use directly return statement or capture the result of the is_palindrome function in some variable and return that if it is confusing.

What is wrong with this python code?

I want to use recursion here but my code is wrong. Help me where I'm wrong. It is only return True. I have to return recursive statement as well as the condition in which the function return False. Basically, I want to expand my code.
def mypalindrome(l):
if l==[] or len(l) == 1:
return(True)
else:
return(mypalindrome(l[1:-1]))
You seem to have most of it right. You just need to call the arguments properly and fix the return value. Additionally, you are missing the check that checks the first and the last character, here's an example:
string = "reallear"
def mypalindrome(string):
if len(string) <= 1:
return True
elif string[0] == string[-1]:
return mypalindrome(string[1:-1])
else:
return False
print mypalindrome(string)
Few ways to check word palindrome
def mypalindrome(l):
if len(l) < 2:
return True
if l[0] != l[-1]:
return False
return mypalindrome(l[1:-1])
or more elegant way
def mypalindrome(l):
return l == l[::-1]
def mypalindrome(l):
if l==[] or len(l) == 1:
return(True)
else:
return(mypalindrome(l[1:-1]) and l[0] == l[-1])

Categories