How to make it run through my whole range? - python

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')

Related

binary search for list in 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))

How to return a boolean value and print a message in python

for example, I want to return a Boolean value False and print a message ("It did not pass the test") at same time in python, how to do that?
Are you looking for this?
def this_returns_false(<arguments>):
"""
Do stuff here
"""
return False
if not this_returns_false(<args>): # not accesses the function for False statement now
print "It did not pass the test"
a possible shorthand:
print "It did not pass the test" if not this_returns_false else ""
OP's code:
def password_check(password):
upper_letter = str.upper(lower_letter)
if ((count_digit(password) == 0) or (count_Lletter(password) == 0) or (count_Uletter(password) == 0)):
return False and print("it did not pass the test")
Edit after OP's code:
def password_check(password):
upper_letter = str.upper(lower_letter)
if (not count_digit(password)) or (not count_Lletter(password)) or (not count_Uletter(password)):
# not is the same as !
print("it did not pass the test")
return False
The print statement is executed before the return statement here btw.

Print all in once

The code that I provided below prints the output one line at a time. However, I want to rewrite the code to print all the content all together at once.
def filters():
for LogLine in Log:
flag = True
for key,ConfLine in Conf.items():
for patterns in ConfLine:
print patterns
if re.match((DateString + patterns), LogLine):
flag = False
break
if(flag == False):
break
if(flag):
print LogLine
Thanks
Here's the general technique:
lines = []
for ...
lines.append(<whatever you were going to print>)
print '\n'.join(lines)
There is one thing that I would do. I would initialize an empty dictionary or empty list and then append all the items to the empty dictionary or empty list. Finally print the output all together at once.
def filters():
mypatterns=[]
for LogLine in Log:
flag = True
for key,ConfLine in Conf.items():
for patterns in ConfLine:
print patterns
mypatterns.append(patterns)
if re.match((DateString + patterns), LogLine):
flag = False
break
if(flag == False):
break
if(flag):
print LogLine
print mypatterns

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