I am having trouble when running a python program. The purpose is to determine whether the sequence 1, 2, 3 is within a given list of ints. When it runs two of the tests, the code works. However, the third test fails and I cannot figure out why.
My code is:
def has123(nums):
s = ''.join(str(i) for i in sorted(nums))
if '123' in s:
return True
else:
return False
When passed through the argument [1, 1, 2, 3, 1] and [1, 1, 2, 4, 1], it returns the correct output, but not for [1, 1, 2, 1, 2, 3].
CodePudding user response:
Remove sorted() from s = ''.join(str(i) for i in sorted(nums))
sorted() sorts the list and puts in ascending order
So in your case [1, 1, 2, 1, 2, 3] is converted to '111223' when used sorted(), therefore not able to find the pattern
CodePudding user response:
if order of numbers matters, which does in this case, so don't sort array. what you are doing, you are sorting array then making string of sorted array. So, position of array element changed, your pattern does not match in this case.
def has123(nums):
s = ''.join(str(i) for i in nums)
if '123' in s:
return True
else:
return False
