简体   繁体   English

确定输入是否具有3个连续整数

[英]Dertermine if the inputs have 3 consecutive integers

How to determine if in the 5 inputs(integer) there are 3 consecutive numbers example: 如何确定5个输入(整数)中是否有3个连续数字示例:

if my input is: 1 2 3 4 5 如果我的输入是:1 2 3 4 5

it will print out True or if my inputs are 1,2,3,9,8 or 5,6,7,2,1 or 8,9,1,2,3 will print out True 它将打印出True或者如果我的输入是1,2,3,9,85,6,7,2,18,9,1,2,3将打印出True

this is my current code: 这是我当前的代码:

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

is there an easier way that i can cover all the possible combinations? 有没有更简单的方法可以涵盖所有可能的组合?

You can try this: (this will work if list contains more than 3 numbers) 您可以尝试以下操作:(如果列表包含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

You only need to test first three letter you enter, since you are looking for consecutive numbers. 您只需要测试输入的前三个字母,因为您要查找连续的数字。 Try this: 尝试这个:

#!/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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM