-2

I've got a question that is to take a list of one or more ints 'nums' and returns True if the sequence [2, 4, 6] appears in the list somewhere and False otherwise. Here's my function so far:

def has246(nums):
    num = ""
    for i in nums:
        num += str(i)
    if "2" "4" "6" in num:
        return True
    else:
        return False

For the following tests i get the expected result:

print(has246(\[2, 2, 4, 6, 2\]))
True
print(has246(\[2, 2, 4, 8, 2\]))
False
print(has246(\[2, 4\]))
False

But I get True for the following when the expected is False:

print(has246(\[24, 6\]))
False
Anshumaan Mishra
  • 1,349
  • 1
  • 4
  • 19
Hugo Smith
  • 15
  • 4
  • Already answered here: https://stackoverflow.com/questions/3847386/how-to-test-if-a-list-contains-another-list-as-a-contiguous-subsequence – Jenny Apr 04 '22 at 12:06

2 Answers2

1

Maybe try searching for actual numbers instead of converting to strings

def has246(nums):
    for i in range(len(nums) - 2):
        if nums[i:i+3] == [2, 4, 6]:
            return True
    return False
matszwecja
  • 6,357
  • 2
  • 10
  • 17
0

The reason for this is that you are joining the elements directly. So [24, 6] when joined becomes '246' returning True. The best solution would be to join the code with a delimiter as:

def has246(nums):
    num = ""
    for i in nums:
        num += str(i) +' ' # I have used space, you can use a '-' as well
    if "2 " "4 " "6 " in num:
        return True
        
    else:
        return False
print(has246([2, 2, 4, 6, 2]))
print(has246([2, 2, 4, 8, 2]))
print(has246([2, 4]))
print(has246([24, 6]))

This way joining the values gives you '24 6' instead of '246' and prevents the mistake by searching for '2 4 6 ' Output:

True
False
False
False
Anshumaan Mishra
  • 1,349
  • 1
  • 4
  • 19