Aug-26-2019, 07:15 AM
I suggest to follow naming conventions set in PEP8 - Function and Variable Names.
Alternative approach could be using zip, set method .difference and built-in function any. This way in process of writing code one can learn much more of Python .
zip is for creating pairs of consecutive numbers without need to worry about IndexError:
any() is built-in function with short circuiting behaviour.
Therefore function could be written (keyword argument is for cases when we need check numbers other than 9):
Alternative approach could be using zip, set method .difference and built-in function any. This way in process of writing code one can learn much more of Python .
zip is for creating pairs of consecutive numbers without need to worry about IndexError:
>>> nums = [1, 9, 9, 2] >>> list(zip(nums, nums[1:])) [(1, 9), (9, 9), (9, 2)]set method .difference can be used for determining whether elements in pair are equal and match desired value:
>>> set((1, 9)).difference((9,)) {1} >>> set((9, 9)).difference((9,)) set()In Python empty means False, so to get True if there is empty set one will use 'not'.
any() is built-in function with short circuiting behaviour.
Therefore function could be written (keyword argument is for cases when we need check numbers other than 9):
>>> def check_list(nums, sentinel=9): ... return any(not set(pair).difference((sentinel,)) for pair in zip(nums, nums[1:])) ... >>> check_list([1, 2, 3]) False >>> check_list([1, 9, 9]) True >>> check_list([1, 2, 2], sentinel=2) TrueOne can use built-in help in interactive interpreter to learn about functions and methods used above (
help(zip)
, help(set.difference)
, help(any)
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.