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.
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
>>>
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With