Hello again! I'm back with more questions on lists.
Question:
Given a list of integers, let's decide that two consecutive items in the list are neighbours if their difference is 1. So, items 1 and 2 would be neighbours, and so would items 56 and 55.Please write a function named longest_series_of_neighbours, which looks for the longest series of neighbours within the list, and returns its length.
For example, in the list [1, 2, 5, 4, 3, 4] the longest list of neighbours would be [5, 4, 3, 4], with a length of 4.
An example function call:
def longest_series_of_neighbors(my_list):
num_neighbors = []
num_neighbors_count = 0
for num in my_list:
i = 0
while i < len(my_list)-1:
if (my_list[i]-1 == my_list[i+1]) or (my_list[i]+1 == my_list[i+1]):
num_neighbors.append(num)
num_neighbors_count += 1
i += 1
else:
num_neighbors.clear()
i+=1
return num_neighbors_count
my_list = [1, 2, 5, 7, 6, 5, 6, 3, 4, 1, 0]
print(longest_series_of_neighbors(my_list))
Expected Output: 4
- I have a few holes when thinking about this, but overall here is my thought process.
- I am visualizing via https://pythontutor.com/render.html#mode=display
- For each number in the list check if the next value is +1 or -1 from it.
- If the next value is +1/-1 then count +1 to the number neighbor & add the number to the num_neighbor list.
---I wanted to use range(num_neighbor) but I think len(num_neighbor) works too. I don't understand the difference as I'd think range would apply to strings, but it seems important to not hit past the array limit. - If the value is not a number_neighbor then we need to clear the num_neighbor list & move to the next number.
Problems I've found:
- num gets trapped at 1 & outputs 1,1,1, but it should be going through the values at each index.
- maybe my counter is wrong. It comes out to 6, then I modify a few portions of code & it outputs to 1 at the last instance.
Tips to work through this?