What is the difference between the following two python methods? [duplicate] - python

This question already has answers here:
List index out of range error on simple python for loop
(3 answers)
Accessing the index in 'for' loops
(26 answers)
Closed 4 years ago.
What is the difference between these 2 fragments of python codes?
I want to check whether an array contains the integers 1,2,3 in sequence as its elements?
def arrayCheck(nums):
for i in nums:
if(i <= (len(nums)-3)):
if (nums[i] == 1 and nums[i+1] == 2 and nums[i+2] == 3):
return(True)
return(False)
def arrayCheck(nums):
for i in range(0,len(nums)-2):
if (nums[i] == 1 and nums[i+1] == 2 and nums[i+2] == 3):
return(True)
return(False)
The first one gives wrong answer for the array:
arrayCheck([1,1,2,1,1,1,1,2,3])
but the second one is correct.

The first block i is elements of the parameter. The second, it's only their indices.
If you wanted the first to iterate over indices rather than the elements, use this
def arrayCheck(nums):
for i, _ in enumerate(nums):
if i <= len(nums)-3:
You can also use list slicing, by the way
if nums[i:i+2] == [1,2,3]:
return True

Related

How does python's built-in 'all' function work under the hood? Specifically, will it exit after finding the first false? [duplicate]

This question already has answers here:
Is the shortcircuit behaviour of Python's any/all explicit? [duplicate]
(4 answers)
Closed 9 months ago.
Will python's all function exit as soon as it finds a False in the iterable? Or will it continue checking the rest?
For example, if i is not divisible by 20, will the below code continue checking if it is divisible by 19 and 18 and so on?
def min_divisible(target_n):
'''
Returns the smallest number that is divisible by all integers between 1 and n
'''
i = target_n
while not all((i%j == 0) for j in range(target_n,2,-1)):
i+=target_n
return f'{i:,}'
print(min_divisible(20))
all will stop the iteration as soon as it encounters a "falsey" object. You can see this with a simple example:
def produce_numbers():
for k in range(10):
yield k
print(k)
all(k < 3 for k in produce_numbers())
This prints
0
1
2
This is spelled out in Python's documentation. It states that the following is a functionally equivalent definition of all:
def all(iterable):
for element in iterable:
if not element:
return False
return True

How to remove even integers from a list in Python? My function is still returning even numbers [duplicate]

This question already has answers here:
How to remove even numbers from a list in Python? [duplicate]
(5 answers)
How to remove items from a list while iterating?
(25 answers)
Python: remove odd number from a list
(9 answers)
Strange result when removing item from a list while iterating over it
(8 answers)
Closed last year.
I am having some trouble while removing even integers from a list in Python. This is what I am trying to do but I can't figure out what am I doing wrong. Is the array skipping elements due to items being removed? I would really appreciate some help.
def removeEven(l):
for e in l:
if e % 2 == 0:
l.remove(e)
print(l)
Try filter:
def removeEvent(l):
return list(filter(lambda x: x % 2 == 0, l))
print(removeEvent(l))
Or even better:
print(list(filter(lambda x: x % 2 == 0, l)))

Python react differently based on how I declare loop conditions [duplicate]

This question already has answers here:
Python boolean evaluation order
(2 answers)
Does Python support short-circuiting?
(3 answers)
Closed 2 years ago.
please see comments, two different while loop conditions have different outcomes, is this because of and operator? I couldn't figure out why.
def longestPalindrome(s: str) -> str:
output = ""
for i in range(len(s)):
temp = check(s,i,i)
if len(output) < len(temp):
output = temp
temp = check(s,i,i+1)
if len(output) < len(temp):
output = temp
return output
def check(s: str, l: int, r: int) -> str:
while (l >= 0 and r < len(s) and s[l] == s[r]):
# while (s[l] == s[r] and l >= 0 and r < len(s)):
# above will result in 'string index out of range' error which I couldnt figure out why
l-=1;r+=1
return s[l+1:r]
print(longestPalindrome("adaa")) # this will return "ada"
Your while statement checks left to right. So when it goes to s[l] == s[r], if any of the index value is out of range, it will error out. By checking for l and r first, you are exiting before it reaches the s[l] == s[r] condition
This is because the and operator is a short-circuit operator. This means that the second argument of the and operator is only evaluated if the first one is true.
In your case, at some point during the loop, r is equal to the length of s, so s[r] doesn't exist. The first while loop works because r < len(s) is false and thus short-circuits the last part of the condition.
In the second loop, Python, tries to evaluate s[l] == s[r] first. As s[r] doesn't exist, an IndexError is raised.
You can check out the documentation here

How to check multiple occurrences of a character in a string [duplicate]

This question already has an answer here:
Identifying straight, flush and other categories (from Poker) using Python
(1 answer)
Closed 3 years ago.
If there is a string = '99888' it should print 'True'. How can you check pairs and threes of a character in a string
I tried using the count function but it only identifies a pair
string = '99888'
for c in '123456789':
if string.count(c) == 2 and string.count(c) == 3 :
print('True')
Edit:
The string is a always 5 character string and if there is a pair and three of a kind it prints True
For example '89899' and '75757' print True. '98726' prints False
Use the Counter class from the collections module
from collections import Counter
def check(inputString):
x = Counter(inputString)
list_of_counts = [x[i] for i in x.elements()]
if (2 in list_of_counts) and (3 in list_of_counts):
return(True)
else:
return(False)
print(check("99888"))
print(check("999888"))

When checking if an item does not exist in a list, why doesn't this code work - if item in list == False: [duplicate]

This question already has answers here:
python operator precedence of in and comparison [duplicate]
(3 answers)
Closed 9 years ago.
Consider this list:
list = [1,2,3,4,5]
I want to check if the number 9 is not present in this list. There are 2 ways to do this.
Method 1: This method works!
if not 9 in list: print "9 is not present in list"
Method 2: This method does not work.
if 9 in list == False: print "9 is not present in list"
Can someone please explain why method 2 does not work?
This is due to comparison operator chaining. From the documentation:
Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).
You are assuming that the 9 in list == False expression is executed as (9 in list) == False but that is not the case.
Instead, python evaluates that as (9 in list) and (list == False) instead, and the latter part is never True.
You really want to use the not in operator, and avoid naming your variables list:
if 9 not in lst:
It should be:
if (9 in list) == False: print "9 is not present in list"

Categories

Resources