Basement Dweller2
Basement Dweller2

Reputation: 61

Python for loops and if statements

I am trying to write a function which uses a for loop to iterate through a list of integers and return True if there are two 2's next to each other on the list, and False otherwise. For example, when I call it with print(has22([1, 2, 2])), it should return True . I am new to Python so here is what I have so far, I am unsure of what to put after and to specify that I want it to check the next iteration to see if it is a 2 as well. Any help is appreciated.

    def has22(nums):
    """Checks a list for two 2's"""
    for num in nums:
        if num == 2 and 
        return(True)
    else: return(False)

Upvotes: 1

Views: 87

Answers (4)

whackamadoodle3000
whackamadoodle3000

Reputation: 6748

def has22(nums):
    for count,num in enumerate(nums):
       try:
          if num == 2 and nums[count+1]==2:
             return(True)
       except IndexError: pass
    return(False)

Try enumerate.

Upvotes: 1

Mohd
Mohd

Reputation: 5613

You can use built in any() to check for two consecutive twos as the following:

def has22(nums):
    return True if any(nums[i] == 2 and nums[i+1] == 2 for i in range(len(nums)-1) else False

Alternatively, you can modify your for loop to the following:

def has22(nums):
    for i in range(len(nums)-1):
        if nums[i] == 2 and nums[i+1] == 2:
            return True
    return False

Upvotes: 1

WhatsYourIdea
WhatsYourIdea

Reputation: 351

First, set two variables(one for recording the last num and another for recording the current num) to something that is not 2. Then, loop through all numbers and first set the current number to num. Then, compare the last number variable(last_num) and the current number variable(current_num) to 2. If both returns True, then, return True. Then, set last_num to the number. Finally, if nothing was found, return False.

def has22(nums):
    last_num = -1
    current_num = -1
    for num in nums:
        current_num = num
        if (current_num == 2) and (last_num == 2):
            return True
        last_num = num
    return False

Upvotes: 0

doraemon
doraemon

Reputation: 2502

def has22(nums):
    """Checks a list for two 2's"""
    gotone = False
    for num in nums:
        if num == 2:
            if gotone:
                return True
            else:
                gotone = True
        else:
            gotone = False
    return(False)

Upvotes: 0

Related Questions