Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check consecutive number in list?

This is my homework.

The problem is to find a way to check whether the items in a list are consecutive or not.

The following is code I've written:

def consecutive(var):
for x in range(2, len(var)):
    forward = var[x] - var[x-1]
    backward = var[x-1] - var[x-2]
if forward == backward:
    return True
else:
    return False

var = []
print 'Enter your number:'
while True:
    num = raw_input()
    if num == '':
        break
    var += [int(num)]

print consecutive(var)

If I input numbers like 1, 2, 3, 4, 5 then I will get True

If I input numbers like 2, 6, 3, 9, 7, 1, 4 then I'll get False

Here, I succeeded returning True or False values respectively.

But there're two questions that make me upset because if I use my code to solve the questions, I don't get the value that I want (it gives me an error)

First question: Is an empty list considered a consecutive list or not?

Second: Is a list that involves a single value considered a consecutive list or not?

Would you like to help me?

like image 949
Bimantara Hanumpraja Avatar asked Oct 31 '22 05:10

Bimantara Hanumpraja


1 Answers

By mathematical convention as discussed in the comments, it would be standard to consider both an empty list and a list with a single element as consecutive, should it not be specified in your homework more precisely.

By the logic of vacuous truth, were a list to not have consecutive order it would require enough elements (2) to break this condition of ordering. To handle this in your existing code, you could simply perform a check before your main check to ensure the base cases of an empty list and a list with one element return True.

like image 95
miradulo Avatar answered Nov 02 '22 09:11

miradulo