python判断是否连续数字组合_检查具有特定条件的连续数字 – Python

请尝试以下方法.它适用于所有测试用例,并且我将单行保持在最低限度:

def check_consecutive(lst):

# Check for the number of non-"a" entries in the list:

if len([x for x in lst if x != "a"]) < 2:

return False

# Get the first non-a value (ASSUMPTION: this is a number)

first_number = next((e for e in lst if e != "a"),None)

# Find the index of the first number

first_index = lst.index(first_number)

# Find the difference between the first number and its index

diff = first_number - first_index

# Based on the final example - false if negative values would be used:

if diff < 0:

return False

# Create a new list - replace a's with their index plus the difference we found

# If the list is consecutive,this difference will be consistent for all values

all_numbers = []

for i,x in enumerate(lst):

if x == "a":

all_numbers.append(i + diff)

else:

all_numbers.append(x)

# Check if the values are now consecutive or not!

if all(all_numbers[i+1] == all_numbers[i] + 1 for i in range(len(all_numbers) - 1)):

return True

else:

return False

print check_consecutive([1,"a"])

#True

print check_consecutive(["a",10])

#True

print check_consecutive(["a",5])

#False #Need at least 2 elements to be numbers

print check_consecutive([3,7])

#False

print check_consecutive(["a",3])

#False

如果您想了解一些单行程序的工作方式,可以将功能略微降低,如下所示:

def check_consecutive(lst):

# Check for the number of non-"a" entries in the list:

if len([x for x in lst if x != "a"]) < 2:

return False

# Get the first non-a value (ASSUMPTION: this is a number)

first_number = next((e for e in lst if e != "a"),None)

# Find the index of the first number

first_index = lst.index(first_number)

# Find the difference between the first number and its index

diff = first_number - first_index

# Based on the final example - false if negative values would be used:

if diff < 0:

return False

if all(x == "a" or x == i + diff for i,x in enumerate(lst)):

return True

else:

return False

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值