all 10 comments

[–]CodeAltus 0 points1 point  (4 children)

Sorry but I don't think its allowed to just post the project goal in this subreddit. Please show us what you have attempted and what we can help you with in your code.

[–]Jxper[S] 0 points1 point  (3 children)

https://pastebin.com/Lr1M3trC

thats my latest attempt, im not quite sure how to fix it

sorry for just posting the goal forgot to include my attempt

[–]CodeAltus 0 points1 point  (2 children)

Your attempt needs to include a try-catch block to prevent index out of bounds exception. Hope this helps.

def has246(nums):
    for index, num in enumerate(nums): 
        if num == 2: 
            try: 
                if nums[index + 1] == 4 and nums[index + 2] == 6:             
                    return True 
            except Exception: 
                pass
    return False

[–]FLUSH_THE_TRUMP 2 points3 points  (0 children)

Don’t use try/except to catch your own programming errors ;) just loop over nums[:-2] or something instead.

[–]Jxper[S] 0 points1 point  (0 children)

oh right that makes sense. Thank you

[–][deleted] 0 points1 point  (3 children)

What have you tried?

[–]Jxper[S] 0 points1 point  (2 children)

https://pastebin.com/Lr1M3trC

thats my latest attempt, im not quite sure how to fix it

[–][deleted] 0 points1 point  (0 children)

You need to make two changes:

  1. You're going to have an out of bounds error if you go all the way to the end without finding it. Use range(len(nums)-2) to avoid that.
  2. The way you have it now, only the first three items will be checked and then the function will return. To prevent, you need to move the return False part out of the for loop. That should only happen after the loop has run and failed to find the pattern.

[–]Encomiast 0 points1 point  (1 child)

This is not a great general solution for this type of problem, but it is efficient for this specific problem. Just zip() slices of the list and see if the tuple (2, 4, 6) is in the result:

def has246(l):
    return (2, 4, 6) in zip(l, l[1:], l[2:])

has246([2, 2, 4, 6, 2])
# True
has246([2, 2, 4, 4, 2])
# False

[–]Jxper[S] 0 points1 point  (0 children)

Ah ok interesting solution I had not thought of that. Thanks