009.完美列表:一个完美列表是指,在这个列表中的每个数字n,其n-1或者n+1也存在于列表中。请编写一个函数,判断给定的列表是否是完美列表。
题目来源:codcwars
"""
完美列表:一个完美列表是指,在这个列表中的每个数字n,其n-1或者n+1也存在于列表中。请编写一个函数,判断给定的列表是否是完美列表。
示例:
输入:[2, 10, 9, 3],输出:True
解析:因为2=3-1,10=9+1,9=10-1,3=2+1,因此它是完美列表。
题目难度:简单
"""
def is_nice(nums: list) -> bool:
for item in nums:
if item + 1 not in nums and item - 1 not in nums:
return False
return True
if __name__ == '__main__':
assert is_nice([2, 10, 9, 3]) is True
assert is_nice([3, 4, 5, 7]) is False