![](/img/trans.png)
[英]How to filter for rows that have greater than a specified count of consecutive integers
[英]Dertermine if the inputs have 3 consecutive integers
如何確定5個輸入(整數)中是否有3個連續數字示例:
如果我的輸入是:1 2 3 4 5
它將打印出True
或者如果我的輸入是1,2,3,9,8
或5,6,7,2,1
或8,9,1,2,3
將打印出True
這是我當前的代碼:
print 'Entering Values into a list:'
a = int(raw_input (""))
b = int(raw_input (""))
c = int(raw_input (""))
d = int(raw_input (""))
e = int(raw_input (""))
a = int(a)
b = int(b)
c = int(c)
d = int(d)
e = int(e)
list_a = [a,b,c,d,e]
if list_a[0] < list_a[1] and \
list_a[1] < list_a[2] and \
list_a[2] < list_a[3] and \
list_a[3] < list_a[4]:
print True
else:
print False
有沒有更簡單的方法可以涵蓋所有可能的組合?
您可以嘗試以下操作:(如果列表包含3個以上的數字,則可以使用此功能)
from itertools import combinations
list_a.sort()
trio = False
for nums in combinations(list_a,3):
if nums[0] + nums[2] == 2 * nums[1] and nums[2]-nums[0] == 2:
trio = True
break
print trio
您只需要測試輸入的前三個字母,因為您要查找連續的數字。 嘗試這個:
#!/usr/bin/python
#-*- coding:utf-8 -*-
print 'Entering Values into a list:'
a = int(raw_input (""))
b = int(raw_input (""))
c = int(raw_input (""))
d = int(raw_input (""))
e = int(raw_input (""))
if (b - a == 1 and c - b ==1) or\
(c - b == 1 and d - c == 1) or\
(d - c == 1 and e - d == 1):
print True
exit()
print False
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.