What's wrong with this?
Why is this always True no matter what I input?
def duplicates(s):
for c in s:
if s.count(c) > 1:
return False
else:
return True
print(duplicates("god"))
print(duplicates("goo"))
print(duplicates("good"))
The loop body never executes more than once, since no matter what, you are executing a return of either True or False on the very first iteration.
To fix it, only return False from within the loop. Don't return True until after the loop exits:
def duplicates(s):
for c in s:
if s.count(c) > 1:
return False
return True
The function name is a little misleading, since it returns True if there are no duplicates and False if there are duplicates.
Related
I want to creates a function that returns True if a list contains two consecutive 3 and false if not.
when using this code it doesn't work:
def has_33(x):
for i in range(len(x)-1):
if x[i:i+2] == [3,3]:
return True
else:
return False
But with this it works:
def has_33(x):
for i in range(len(x)-1):
if x[i:i+2] == [3,3]:
return True
return False
For me it's the same thing can you explain to me why plz
In the top code you only check the first 2 indices. In the bottom code you're checking the whole array. Here's why:
In the top code you have an else condition, which means that on the first iteration either the if-condition is true (i.e. the first and the second element of the list are 3) or you will go into the else condition. In either case, you're hitting a return statement after checking just the first 2 elements.
In the bottom code, you only return if you find something, or once you've finished the whole loop
I've added some print statements to both your functions. You can run this code and see the output to help you understand what's happening:
def has_33_incorrect(x):
print("\nRunning the incorrect function")
for i in range(len(x)-1):
print("Checking indices {} and {}".format(i, i+1))
if x[i:i+2] == [3,3]:
print("indices contain 2 consecutive 3's. Returning true")
return True
else:
print("indices don't contain 2 consecutive 3's. Returning false")
return False
def has_33_correct(x):
print("\nRunning the correct function")
for i in range(len(x)-1):
print("Checking indices {} and {}".format(i, i+1))
if x[i:i+2] == [3,3]:
print("indices contain 2 consecutive 3's. Returning true")
return True
print("Did not find consecutive 3's. Returning false")
return False
list = [1, 2, 4, 5, 6, 3, 3, 2, 5]
has_33_incorrect(list)
has_33_correct(list)
One more solution with any python builtin:
def has_33(l):
return any(l[i+1] == l[i] == 3 for i in range(len(l) - 1))
This code works since if the if condition is false it doesn't return anything, yet in the first function you showed it returns false and exits the function. You shouldn't return anything until you find that its true somewhere, only after you've iterate over the entire list then and only then should you return False
def has_33(x):
for i in range(len(x)-1):
if x[i:i+2] == [3,3]:
return True
return False
You can iterate over the list directly.
def has_33(x):
current = None
for item in x:
if current == item == 3:
return True
current = item
return False
If you ever find both current and item are equal to 3, you can return True immediately. Otherwise, you will return False when the loop exits naturally.
If you loop through adjacent entries at the same time, you can compare:
def adjacent_threes(x):
for a, b, in zip(x[:-1], x[1:]):
if a == b == 3:
return True
return False
Try this ,it's simple:
def has_33(nums):
for i,num in enumerate(nums):
if nums[i]==3 and nums[i+1]==3:
return True
return False
python code as follows :
def has_33(nums):
my_list = []
y =len(nums)-1
for x in range(0,y) :
if nums[x] == 3 and nums[x+1] == 3:
my_list.append(1)
else :
my_list.append(0)
print(my_list)
if 1 in my_list:
return True
else :
return False
I am really sorry about my python understanding and about my English.
I just started to learn Python and really dont understand difference between two next code:
def arrayCheck(nums):
"""
find nums
"""
for i in range(len(nums)-2):
if nums[i]==1 and nums[i+1]==2 and nums[i+2]==3:
return True
return False
result = arrayCheck([1, 1, 2, 3, 1])
print(result)
When run this code the result is True
And the next one:
def arrayCheck(nums):
"""
find nums
"""
for i in range(len(nums)-2):
if nums[i]==1 and nums[i+1]==2 and nums[i+2]==3:
return True
else:
return False
result = arrayCheck([1, 1, 2, 3, 1])
print(result)
The second code return False.
Why?
Thanks in advance.
The first code can return only True or None. After the return statement the function ends so the first code never reach the return False statement.
The second code will return False if the first 3 items are not 1, 2 and 3 since if the condition does not hold it returns False.
I would actually assume this is the code you are interested in -
def arrayCheck(nums):
"""
find nums
"""
for i in range(len(nums)-2):
if nums[i]==1 and nums[i+1]==2 and nums[i+2]==3:
return True
return False
See Python control flow here.
In the first code, if condition has no else part. While in the 2nd code, if condition has a else part.
So when if condition is false in the first code, it is going for second iteration and if condition getting True as per the input and it is returning True.
But in the second code, if condition is false and it is going to else part and returning False.
In python the indentation matters, and return will break out the function so, in the first codeblock you have
if nums[i]==1 and nums[i+1]==2 and nums[i+2]==3:
return True
return False
The two return are on the same indent level so if the condition is met It will go to first line, return True,
see return and break out of the function ignoring everything afterwards
but in the second codeblock
you have
if nums[i]==1 and nums[i+1]==2 and nums[i+2]==3:
return True
else:
return False
so if the condition is true it will return true and break out of the function
but if the condition is not true it will return false and break out of the function so it only does one of the iterations you are trying to do.
If I understand what you are trying to do correctly, this would be the solution :
def arrayCheck(nums):
"""
find nums
"""
found = False
for i in range(len(nums)-2):
if nums[i]==1 and nums[i+1]==2 and nums[i+2]==3:
found = True
return found
result = arrayCheck([1, 1, 2, 3, 1])
print(result)
This works because it allows the function to check over every iteration in the for loop and it will return true if the numbers were found
In first code return False will never execute because it is inside the if condition and before it another return statement return True. After returning the function execution will stop.
In the second code if condition fails for the first time the function execution will stop because of return False in else condition.
This question already has answers here:
How can I use `return` to get back multiple values from a loop? Can I put them in a list?
(2 answers)
Closed 3 years ago.
def check(str):
if(str.isalnum())==True:
return True
if(str.isalpha())==True:
return True
if(str.isdigit())==True:
return True
if(str.islower())==True:
return True
if(str.isupper())==True:
return True
if __name__ == '__main__':
s = input()
if(check(s)):
print('True')
else:
print('False')
It is showing only one condition's result. For example, if I type qA2 it is showing one True instead of
True
True
True
True
True
This is because you are "returning" from the function if one of the if conditions evaluates to true.
You can read more about the keyword return here.
The gist is, as the word says, it "returns" from the function with specified value(s).
If you want the other if conditions to get evaluated too, you will need to maintain a small data structure of all successful if conditions, eg:
def check(str):
# let's initialise a dictionary with all False values.
# If any if condition turns True, then we will set
# that value to True in the dictionary.
res = {
"isalnum":False,
"isalpha":False,
"isdigit":False,
"islower":False,
"isupper":False,
}
if(str.isalnum())==True:
res["isalnum"] = True
if(str.isalpha())==True:
res["isalpha"] = True
if(str.isdigit())==True:
res["isdigit"] = True
if(str.islower())==True:
res["islower"] = True
if(str.isupper())==True:
res["isupper"] = True
return res # This returns a dictionary with all values
if __name__ == '__main__':
s = input()
if(check(s)):
print('True')
else:
print('False')
return leaves the function immediately. The first condition which succeeds will cause the rest to be skipped, the way you defined your function.
If you want to check all the conditions every time, try something like
def check(str):
whether = True
if not str.isalnum():
whether = False
if not str.isalpha():
whether = False
if not str.isdigit():
whether = False
if not str.islower():
whether = False
if not str.isupper():
whether = False
return whether
Printing something in each branch seems excessive, but could certainly be added.
return stops the function's execution. Nothing after a return statement will be run, and a function can only have a single return value. If you want to see the result for all conditions, store them in a List or a Dict and return that instead, for example:
def check(str):
results = {}
results['isalnum'] = str.isalnum()
results['isalpha'] = str.isalpha()
results['isdigit'] = str.isdigit()
results['islower'] = str.islower()
results['isupper'] = str.isupper()
return results
I am trying to define 2 functions, but only has_33 is working and myfunction is not working.
I am trying this code in jupyter notebook:
def myfunction(num):
for i in range(0, len(num)-1):
if num[i:i+2] == [3,3]:
return True
return False
and this code:
def has_33(nums):
for i in range(0, len(nums)-1):
if nums[i:i+2] == [3,3]:
return True
return False
myfunction([1,2,4,3,3]) should give true but it is giving false result but has_33([1,2,4,3,3]) is giving the true result. Why is this happening?
Hi there is indent difference in both code:
in first function second return is inside of for loop where as in second function it is out of for loop:
So in first function when if condition is false and it is going on second return and returning false for first value 0
In second function if evaluation keep false till i is 3 and for loop is not executing return. Once if evaluation become true on i=0 it is executing return of if and returning true so control goes out of function and second return out of for is not getting executed:
corrected first function:
def myfunction(num):
for i in range(0,len(num)-1):
if num[i:i+2] == [3,3]:
return True
return False
Indentation error! Just needed to erase a whitespace from the last line of your first code. The for loop will return False now. Try like this:
def myfunction(num):
for i in range(0,len(num)-1):
if num[i:i+2] == [3,3]:
return True
return False
Posting my comment as an answer as suggested by #quamrana.
This behavior is because of indentation. In myfunction, if the condition nums[0:2] == [3,3] is not satisfied, then the function immediately returns False. Whereas in has_33, it iterates through entire list and then only will return False if there are no consecutive [3,3].
e.g.
nums = [1,2,3,3,5]
myfunction(nums)
False
Let's go step by step in the function
for i in range(0,len(num)-1)
i is initialized to 0, i.e. i = 0.
nums[i:i+2]
Since i is 0, becomes nums[0:2] i.e. [nums[0], nums[1]].
if num[i:i+2] == [3,3]
Becomes if num[0:2] == [3,3]. Since nums[0] = 1 and nums[1] = 2, [nums[0], nums[1]] != [3,3]. Thus, if block will not be executed.
Since return False is in the for loop and if condition was not satisfied, the next line is executed, which is return False. The function execution stops here.
Now, second function:
nums = [1,2,3,3,5]
has_33(nums)
True
Step by step
Same as myfunction.
Same as myfunction.
Same as myfunction.
Now here is the catch. Since return False is written outside for loop, i increases by 1.
i = 1
nums[i:i+2] is nums[1:3] which is [nums[1], nums[2]].
The loop continues until you get a [3,3] OR i = len(nums) - 1.
Hope this helps you understand what went wrong.
So the function should check if a list is symmetric; if the list is empty or has one integer, it is symmetric.
Otherwise the function should check if the first and last integers are the same and go on recursively. If not, return False.
The code seems right, but I can't figure out what's wrong and why it won't return False.
def symm(lst):
t = len(lst)
if t == 0 or 1:
return True
if t>1:
if lst[0] == lst[-1]:
return symm(lst[1:-2])
else:
return False
print symm([6,6,6,6,7])
if t == 0 or 1: is always true since this is read as if (t == 0) or (1): and 1 is always going to be true.
Change to: if t in [0,1]: or simply if len(lst) < 2: