I am trying to write a function that has only one argument, a list of positive integers.
It has to be recursive and find whether you can get from the start to the end while avoiding landing on 0s. It has to start at first value list[0]
but you can jump by either the full amount or less.
For example
list1 = [3,1,2,0,4,0,1] list2 = [3,2,1,0,2,0,2]
List 1 should return True
as you can jump from 3 to 2 to 4 to 1.
List 2 should return False
as it does not matter how you jump, you will land at the first 0.
Here is my attempt so far:
def check_level(level): jump = level[0] if level[-1] == 0: return False elif jump == 0: return False elif jump == 0: return False elif len(level) > 1: if level[jump] > len(level): return True elif level[-1] == 0: return False elif level[0] != 0: if level[jump] == 0: level[0] -= 1 return check_level(level) else: jump_index = level.index(level[jump]) new_level = level[jump_index:] return check_level(new_level) else: return True
It does not work with all examples and with others it comes up with an error:
if level[jump] > len(level): TypeError: '>' not supported between instances of 'list' and 'int'``` I am out of ideas on how to approach this and whether my approach is failed from the start... I hate recursion, hence I need to practice it.
https://stackoverflow.com/questions/65743198/python-recursively-jumping-through-a-list-by-a-given-index-jump-or-less-while-av January 16, 2021 at 04:34AM
没有评论:
发表评论