简体   繁体   中英

Dertermine if the inputs have 3 consecutive integers

How to determine if in the 5 inputs(integer) there are 3 consecutive numbers example:

if my input is: 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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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