#πŸ”’ List help (cont.) - Accessing next value issue

60 messages Β· Page 1 of 1 (latest)

hoary dagger
#

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

  1. For each number in the list check if the next value is +1 or -1 from it.
  2. 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.
  3. 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?

plucky rainBOT
#

@hoary dagger

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

sinful oyster
#

They don't seem to ask for the list of neighbors, just its length.

#

So what you care about is the counter.

#

range and len do different things. What were you proposing to use each for?

elder drift
#

I wanted to use range(num_neighbor) but I think len(num_neighbor) works too. I don't understand the difference
len only makes sense for sequences like strings or lists. numbers don't have a len.

#

num gets trapped at 1 & outputs 1,1,1, but it should be going through the values at each index.
you have a return in your for num in my_list loop, so when it hits that it exits the function -- it can't go to the next iteration

hoary dagger
#

I think I was having issues trying to get the next value without going over the limit, because if I do my_list[i+1] and the array isnt found, then it gives an error.

sinful oyster
#

you always go i += 1 in your loop. Which, of itself, is fine. But it means you can write the while loop as:

for i in range(len(my_list)-1):
#

That starts at 0 and ends with len(my_list)-2, so you can always compare i with i+1.

hoary dagger
#

oh something just isn't making sense at the moment with these lists & loops.

  • when I pull the return statement back as expected...the steps jump from 45 to 526 which makes me think this is not doing at all what im thinking.
  • result 66 lol
def longest_series_of_neighbors(my_list):
    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_count += 1
                i += 1
            else:
                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))
#

I had a num_neighbors_max that I would set the counter to when it wasn't true, but then if it detects another chain of num neighbors itll reset, so im still a bit confused

sinful oyster
hoary dagger
#

oh, right, im currently just counting wild

#

welp thats a weird twist, now my counter is 1 short but it looks like its hitting over every index

sinful oyster
#

What's the length of [1,2,3,4] for your function? 4?
And how many compares did you do?

hoary dagger
#

ahhh changing it to a smaller list made me wonder...
...it should be 4 but now its giving 12 as an answer...

  • I'm thinking I should avoid the for into a while?
sinful oyster
#

12?

#

How long is your input list?

hoary dagger
#

ah whoops, i pulled my return num_neighbors_max back one extra indent:
So I'm getting 3 but it should be 4...

def longest_series_of_neighbours(my_list):
    num_neighbors_count = 0
    num_neighbors_max = 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_count += 1
                if num_neighbors_count > num_neighbors_max:
                    num_neighbors_max = num_neighbors_count
                i += 1
            else:
                num_neighbors_count = 0
                i+=1 
      return num_neighbors_max


my_list = [1, 2, 3, 4]
print(longest_series_of_neighbours(my_list))
sinful oyster
#

Right. The list if 4 items long. How many comparisons are you making?

keen bison
#

I don't get why there's 2 loops. You aren't even using the for's num.

sinful oyster
keen bison
#

I think you're getting 12 because it's getting the answer 3, 4 times over.

#

It's the wrong answer as well

hoary dagger
sinful oyster
sinful oyster
hoary dagger
#

i will return in 20 minutes, just going to erase the code & start again to see if i come with something different. i keep getting pulled into "look at this value in the list & compare it to the next value in the list, if its +/- 1, count)

  • i also was initially trying to add the value to a "longest running num_neighbor" list but that seemed out of the question for the time being
sinful oyster
#

While you're gone, think about that "getting 3 for a 4 item run". How many pairs are you examining in that 4 item run?

hoary dagger
#

oh thats where my range idea came from. I thought I could add each item that was a num_neighbor to a list & then however long that was, I could just range or len(num_neighbor_running) on the return

keen bison
#

Or even. What result should you expect from [9, 99, 2] ?

#

||It's not 0||

hoary dagger
#

okay so the chapter mentioned zip & i figured, okay that would be dope,
a=1
b=2
1,2
if a+1==2 or a-1==2: counter+1

def longest_series_of_neighbours(my_list):
    num_neighbors_count = 0
    num_neighbors_max = 0
    for num1, num2 in zip(my_list, my_list[1:]):
        if num1+1==num2 or num1-1==num2:
            num_neighbors_count += 1
    return num_neighbors_count

It just doesn't hit the 4th place which is weird & if I modify the [1:] to an i, im pretty sure itll just overtick...

sinful oyster
#

zip stops short if one of the sequences is short, which is why you don't overrun.

#

!e

L=[1,2,3,4]
print(list(zip(L,L[1:])))
plucky rainBOT
hoary dagger
#

oh so maybe this is working as expected & i just need to implement the max portion

sinful oyster
#

Your if-test looks not right.

#

Sorry, it's fine.

hoary dagger
#

So my solution is technically always 1 short but I think its just a wording of the problem issue. I ended up doing this for the solution and it worked LOL.

def longest_series_of_neighbours(my_list):
    num_neighbors_count = 0
    num_neighbors_max = 0
    
    for num1, num2 in zip(my_list, my_list[1:]):
        if num1+1==num2 or num1-1==num2:
            num_neighbors_count += 1
            if num_neighbors_count >= num_neighbors_max:
                    num_neighbors_max = num_neighbors_count
        else:
            if num_neighbors_count >= num_neighbors_max:
                    num_neighbors_max = num_neighbors_count
            num_neighbors_count = 0
            
    return num_neighbors_max+1

Their test cases:

3 != 4 : The result 4 does not match with the model solution 3 when calling function with the parameter value (1, 2, 3, 5, 6, 9, 10).
6 != 7 : The result 7 does not match with the model solution 6 with the test input (0, 1, 2, 3, 4, 5, 9, 10, 11, 2, 3, 4)
4 != 5 : The result 5 does not match with the model solution 4 with the test input (0, 1, 2, 1, 5, 8, 7, 9, 2, 3, 2).
however if I modified the count & max +1 in start, it doesnt fit the solution. if I just add 1 at the return...it works...but their solution is...a bit obnoxious if you ask me LOL

  • didnt think to use absolute value on this at all....
  • didnt think to use max either, what the
def longest_series_of_neighbours(my_list: list):
    longest = 1
    result = 1
    for i in range(1, len(my_list)):
        # function abs calculates the absolute value
        if abs(my_list[i-1]-my_list[i]) == 1:
            result += 1
        else:
            result = 1
        # function max returns the highest of the parameters
        longest = max(longest, result)
    return longest
#

i normally try to take something away from the solutions but theirs is a bit...wonky to me

sinful oyster
#

Think about what you're counting: you're counting adjacent pairs which are neighbors. A 4 item list has only 3 pairs.

#

The length of the run in items will always be 1 more than the number of pairs in the run.

hoary dagger
#

ah thats why you mentioned the pairs before
...but I noticed that & i wasnt really sure how to capture that last item

sinful oyster
#

abs() is fine. It's the common suggestion.
But (my_list[i-1] - my_list[i]) in (-1, 1) is also valid.

sinful oyster
hoary dagger
#

oh i see what you are saying, but I dont really see how abs works to this

#

OH

#

its how it determines the difference is 1

sinful oyster
hoary dagger
#

oh that makes a lot more sense now...

#

instead my 2 ors

sinful oyster
hoary dagger
#

oh I get this line more now...

    for i in range(1, len(my_list)):

but for some reason im still not following the counting logic of the question, but i have a feeling itll inevitably come to haunt me on another exercise down the line & I can recall these moments of suffering

#

im going to close this for now but ill be in the regular python discussion to ~~harass ~~ inspire others with my new found wisdom.
thank you!

#

!close

plucky rainBOT
#
Python help channel closed with !close

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.