繁体   English   中英

python中最长的相等数序列

[英]Longest sequence of equal numbers in python

我试图在python中生成最长的相等数序列,但它不起作用

def lista_egale(lst1 = input("numbers go here ")):
    l = 0
    lst1 = []
    maxi = -9999
    prev_one = None
    lmax = -9999
    for current in lst1:
        if prev_one == current:
            l += 1
        else:
            l = 1
        if l > lmax:
            lmax = l
            maxi = current
        prev_one = current
    print("longest sequence is ", lmax, " and ", maxi)

lista_egale()

输入:

1 2 2 2 2 3 4 5 6 2 2 2

预期输出:

longest sequence is  4  and  2

我打算对您的默认参数写下同样的担忧,但这至少在第一次被调用时会正常工作。 这个功能没有。 每个人都跳到了那个常见的问题上,而没有注意到下一行。 让我们再看一下这段代码的删减版本:

irrelevant = input("numbers go here ")

def lista_egale(lst1 = irrelevant):
    # while it is true that your default argument is bad,
    # that doesn't matter because of this next line:
    lst1 = []
    for current in lst1:
        # unreachable code
        pass

澄清一下,由于您的回复表明这还不够清楚,如果您立即用空列表覆盖它,传递给 lst1 的值并不重要。

(对于其他阅读此内容的人:)将我标记为“不相关”的内容分开并不完全相同,但我试图指出输入已被覆盖。

我认为这个函数根本不应该接受用户输入或有一个默认参数。 让它成为一个只有一项工作的函数,只需将数据传递给它即可。 用户输入可以在别处收集。

根据 Barmar 的说明以及仅使用不可变默认值的原则,您的代码应该看起来更像这样:

def lista_egale(inp1 = None):
    if not inp1:
        inp1 = input("numbers go here ")
    # optionally do some error checking for nonnumerical characters here
    lst1 = [int(i) for i in inp1.split(" ")]

    # rest of your code here

lista_egale()

基本上, input返回一个字符串值,您需要先将其转换为整数列表,然后再开始处理。

  • 您可以将列表map(int, inp1.split(" "))map(int, inp1.split(" "))因为它会做同样的事情(但您不能多次遍历map ,除非您首先将其包装在list()函数中)。

其次,避免设置可变默认参数,因为(简而言之)在多次重新运行同一个函数时会导致奇怪的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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