python 3.x - code not continuing to loop -


i need write function has22(nums) takes list of ints nums , returns true if list contains 2 next 2 somewhere.

my approach:

def has22(nums):     in range(len(nums)-1):         if nums[i] == 2 , nums[i+1] == 2:             return true         else:             return false  print(has22([1, 2, 2]))  **should** evaluate to: true #got: false  print(has22([1, 2, 21, 2])) evaluates to: false print(has22([2, 1, 2])) evaluates to: false print(has22([2, 2])) evaluates to: true print(has22([4, 3, 2, 1])) evaluates to: false 

what need function continues looping?

the problem return false after first pair! instead, should return false after have scanned entire list.

def has22(nums):     in range(len(nums)-1):         if nums[i] == 2 , nums[i+1] == 2:             return true     return false 

alternatively, use zip(nums, nums[1:]) generate pairs of consecutive numbers:

def has22(nums):     return (2, 2) in zip(nums, nums[1:]) 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -