如何检查列表中的连续数字? [英] How to check consecutive number in list?

查看:58
本文介绍了如何检查列表中的连续数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的作业.

问题是找到一种方法来检查列表中的项目是否连续.

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

以下是我写的代码:

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)

如果我输入像 1, 2, 3, 4, 5 这样的数字,那么我会得到 True

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

如果我输入像 2, 6, 3, 9, 7, 1, 4 这样的数字,我会得到 False

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

在这里,我成功地分别返回了 True 或 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?

你愿意帮我吗?

推荐答案

根据评论中讨论的数学约定,将空列表和具有单个元素的列表视为连续是标准的em>,不应该在您的作业中更准确地指定它.

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.

根据虚实的逻辑,如果列表没有连续顺序,则需要足够的元素 (2) 来打破这种排序条件.要在现有代码中处理此问题,您只需在主检查之前执行检查,以确保空列表和具有一个元素的列表的基本情况返回 True.

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.

这篇关于如何检查列表中的连续数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆