Given an array, return
True
if the array contains consecutive values:has22([1, 2, 2]) - True has22([1, 2, 1, 2]) -False has22([2, 1, 2]) - False
I do aware of a quick solution by iterating the list in a for
loop and comparing current and next items for equality until it reaches the end, also using modules like itertools as pointed out by @syb0rg. However, I am asking this to learn algorithmic approach
Current Solution:
def has22(nums):
total_occurrences = nums.count(2)
if total_occurrences >= 2:
forward_start = 0
backward_start = 0
reversed_nums = nums[::-1]
last_item_index = len(nums) - 1
for _ in xrange(total_occurrences/2 ):
next_forward_occurrence = nums.index(2,forward_start)
next_backward_occurrence= last_item_index - reversed_nums.index(2, backward_start)
if nums[next_forward_occurrence] == nums[next_forward_occurrence+1]:
return True
elif nums[next_backward_occurrence] == nums[next_backward_occurrence - 1]:
return True
forward_start = next_forward_occurrence
backward_start = next_backward_occurrence
return False
I would like to know if there is any other efficient algorithm (using only built-in methods, no modules/lib please)
itertools
is part of the Python standard library, similar toxrange()
in your code. \$\endgroup\$