Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning True if a sequence appears in a list

I need to write a function that takes a list of ints nums and returns True if the sequence 1, 2, 3, .. appears in the list somewhere.

My approach:

def list123(nums):
    num = ""
    for i in nums:
        num += i
    if "1,2,3" in num:
        return True
    else:
        return False

it fails to work indicating: builtins.TypeError: Can't convert 'int' object to str implicitly

I would also like to know if there is a more simpler way, rather that converting the list to a string like i've done.

like image 903
Moh'd H Avatar asked Nov 30 '25 12:11

Moh'd H


2 Answers

You will get an error on num += i, because you are trying to add 1 to "". Instead, try the following:

def list123(nums, desired=[1, 2, 3]):
    return str(desired)[1:-1] in str(nums)

>>> list123([1, 2, 3, 4, 5])
True
>>> list123([1, 2, 4, 3, 5])
False
>>> list123([1, 2, 4, 3, 5], desired=[2, 4, 3])
True
>>> list123([5, 1, 2, 7, 3, 1, 2, 3])
True
>>> 
like image 112
A.J. Uppal Avatar answered Dec 02 '25 05:12

A.J. Uppal


def list123(nums):
    for i in range(0,len(nums)-1):
        if nums[i]==1:
            if nums[i+1]==2:
                if nums[i+2]==3:
                    return True

    return False       


nums=[1, 2, 1, 3, 1, 2, 1]
print(list123(nums))
like image 29
nilesh vernekar Avatar answered Dec 02 '25 04:12

nilesh vernekar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!