binary search for list in python - python

My code for binary search function in a list returns true for a value in the list, but returns None (instead of false) for values not in the list.
Can someone please explain me what I'm doing wrong?
The program is:
def searchlist(x,alist):
end=int(len(alist)-1)
mid=int(len(alist)/2)
while len(alist)>2:
if x==alist[mid] or x==alist[0] or x==alist[end] :
return("true")
break
elif x>alist[mid]:
alist=alist[mid:]
mid=int(len(alist)/2)
end=int(len(alist)-1)
elif x<alist[mid]:
alist=alist[:mid]
mid=int(len(alist)/2)
end=int(len(alist)-1)
else:
return("false")
aList=[2,3,5,7,9,12,14,23,34,45,67,89,101]
xnum=int(input("enter a number:"))
searchlist(xnum,aList)
print(searchlist(xnum,aList))

You get None when your function does not return a value. This happens because the while loop terminates without going into the "else" branch.
A better practice would be to return True (not the string, but the Boolean value) when you find the value in the list, and return False after the loop.

Your while loop cannot catch the else statement. you don't need that else. try this :
def searchlist(x,alist):
end=int(len(alist)-1)
mid=int(len(alist)/2)
result = False
while len(alist)>2:
if x==alist[mid] or x==alist[0] or x==alist[end] :
result = True
elif x>alist[mid]:
alist=alist[mid:]
mid=int(len(alist)/2)
end=int(len(alist)-1)
elif x<alist[mid]:
alist=alist[:mid]
mid=int(len(alist)/2)
end=int(len(alist)-1)
return result
aList=[2,3,5,7,5,67,89,101]
xnum=int(input("enter a number:"))
print(searchlist(xnum,aList))

Related

How to make it run through my whole range?

def isprimelike(n):
for a in range(2,n-1):
if pow(a,n,n) == a%n:
return True
else:
return False
When I check n for a given value it just check 2, then decides if it is true or false and doesn't check the rest of the range. Not sure how to make it check the rest of the range.
That's because you're using a return inside the if-else block. You might want to change the return statement by a print one indicating if it is a prime number or not.
If you want it to return True if all are prime-like or False if at least one is not, then do the following:
def isprimelike(n):
for a in range(2,n-1):
if pow(a,n,n) != a%n:
print('One element is false')
return False
return True
The print statement is just to show something, but it's not relevant.
I would try making a list and allow your for loop to append the results of the range into the list then return the list as a whole so you can have access to all the results.
edit: Complely missed the point of your question. Here's the edit.
import sys
def isprimelike(n):
resultlist = []
for a in range(2,int(n)-1):
if pow(a,int(n),int(n)) == a%int(n):
result.append(True)
else:
result.append(False)
return resultlist
n = sys.argv[1]
resultlist = isprimelike(n)
if True in resultlist:
if False in resultlist:
print('List contains both True and False')
sys.exit(1)
else:
print('List is all True')
sys.exit(1)
if False in resultlist:
if True in resultlist:
print('List contains both True and False')
else:
print('List is all False')

Syntax error at second definition in Python

def specificChecker(someThing, checker):
if checker == None:
return someThing
elif checker == True:
return not someThing
else:
return None
def whatDoesTheCheckerSay(someThing):
if specificChecker(someThing) == someThing:
return 'The checker value was False on that one.'
elif specificChecker(someThing) == not someThing:
return 'The checker value was True on that one.'
elif specificChecker(someThing) == None:
return 'Something irregular happend. The checker value wasn\'t None or True.'
else:
return 'Something went really wrong. This doesn\'t even not work.'
reallySomeThing = input('Type in really some thing: ')
theChecker = input('Set the checker to something: ')
print(specificChecker(reallySomeThing, theChecker))
print(whatDoesTheCheckerSay(reallySomeThing)) # This can be made more efficient, right?
def one(someShit):
return someShit + ' AWWW YEAH!'
def two(someShit):
return one(someShit)
print(two(input('Type in some kind of stuff: ')))
I'm a self-taught beginner, so surely it's something awkwardly basic. I'm using the IDLE shell and have repeatedly gotten a syntax error at the second definition statement of my codes. Please help?
You cannot use the line:
elif specificChecker(someThing) == not someThing:
This must be written
elif specificChecker(someThing) != someThing:
to be valid Python.
This is also valid but is perhaps less readable:
elif (specificChecker(someThing)) == (not someThing):
After OP edit:
The new error is the mismatch in arguments (always 1) to a function that requires 2 arguments. You have to pass two arguments to specificChecker not one
Line 12: elif specificChecker(someThing) == not someThing:
If you want to check if some variable is not some variable, used is not for boolean or != for values and strings

Python if( ): vs if:

On Code Academy there is this course where in the example they show
def speak(message):
return message
if happy():
speak("I'm happy!")
elif sad():
speak("I'm sad.")
else:
speak("I don't know what I'm feeling.")
The above example will NOT be related to the rest of the code I show. That was just an example for the if statement. Now I was under the impression that when ever writing an if statement it had to end in an ():like the above example.
However when doing the assignments this does not work:
def shut_down(s):
if s == "yes"():
return "Shutting down"
elif s == "no"():
return "Shutdown aborted"
else:
return "Sorry"
However this works:
def shut_down(s):
if s == "yes":
return "Shutting down"
elif s == "no":
return "Shutdown aborted"
else:
return "Sorry"
My question is how come the () is not needed next to the "yes" and "no" but :is still needed. I thought whenever writing an if statement it will automatically have to end with ():. In that very first example, that's how it is shown. Do you understand my confusion.
In the example given, happy() and sad() are functions, and as such require parentheses. The if itself does not need parentheses at the end (and it shouldn't have them)
No, if has nothing to do with ()
happy is a function. happy() is a call to that function. So, if happy(): tests if the happy function returns true when called.
In other words, if happy(): speak("I'm happy!") is equivalent to
result_of_happy = happy()
if result_of_happy:
speak("I'm happy!")
As has been mentioned happy() / sad() are functions so they require (). In example two of your question you are comparing your value to the string "yes" because it is a string it does not require ().
Within an if statement you can use parentheses to make the code more readable and ensure certain operations are evaluated before others.
if (1+1)*2 == 4:
print 'here'
else:
print 'there'
Differs from:
if 1+1*2 == 4:
print 'here'
else:
print 'there'
Because string objects are not callable so what are you expecting then:
Then use lambda not that efficient tho:
def shut_down(s):
if (lambda: s == "yes")():
return "Shutting down"
elif (lambda: s == "no")():
return "Shutdown aborted"
else:
return "Sorry"

How to use a function as while loop condition?

I have the following code:
def funct():
print("beggining function")
a = int(input)
if a == 1:
return True
else:
return False
while funct():
#Rest of the code
Every time the while loop repeats it executes the function, so it prints "beggining function". I want to avoid this, what can I do?
A while <condition> loop works as follows:
it checks condition.
if condition evaluates to True, it executes the upcoming code one time. Then it goes back to 1.
if condition evaluates to False, it skips the upcoming code and goes through the rest of the code.
So what you are seeing here is the intended way for while to work.
To prevent this header from being printed every time, just move it out of the while:
def funct():
a = int(input)
if a == 1:
return True
return False # no need to check anymore
print("beggining function") # here
while funct():
#Rest of the code
Try to this
def funct():
print("beggining function")
a = int(input())
if a == 1:
return True
else:
return False
while funct() == 1:
funct()
you enter input 1 loop will continue...

Understanding True/False evaluations in the context of Python dictionaries

I am working through the EdEx 6.00.2x course online and am struggling with one portion of my code:
newResistances = copy.deepcopy(self.resistances)
for drugs in self.resistances:
resistancePicker = random.random()
if self.resistances[drugs] == True:
if resistancePicker < self.mutProb:
print self.mutProb
newResistances[drugs] = False
elif self.resistances[drugs] == False:
if resistancePicker < self.mutProb:
print self.mutProb
newResistances[drugs] = True
print newResistances
return ResistantVirus(self.maxBirthProb, self.clearProb, newResistances, self.mutProb)
self.resistances is a dictionary containing drug name keys, and True or False values {'a':True,'b':True}. My problem is that only the first element of the dictionary seems to be evaluated and changed in the newResistances dictionary. Please let me know if this question is too vague/needs more context.
This is because your return is the wrong location. If you move it to line up with the for, you will see the code iterate through all keys.
I have also updated the code to remove constructs like if predicate==True since you could just do if predicate: instead.
Here's how the code should look:
for drugs in self.resistances:
resistancePicker = random.random()
if self.resistances[drugs]:
if resistancePicker < self.mutProb:
print self.mutProb
newResistances[drugs] = False
elif not self.resistances[drugs]: # or else:
if resistancePicker < self.mutProb:
print self.mutProb
newResistances[drugs] = True
print newResistances
return ResistantVirus(self.maxBirthProb, self.clearProb, newResistances, self.mutProb)

Categories