简体   繁体   中英

Longest sequence of equal numbers in python

I tried to generate the longest sequence of equal numbers in python, but it doesn't work

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()

Input:

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

Expected Output:

longest sequence is  4  and  2

I was going to write up the same concern about your default argument, but that would at least work correctly the first time it is called. This function does not. Everyone jumped on that common problem, and failed to notice the next line. Let's look another look at this abridged version of your code:

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

To clarify, since your reply indicates this is not clear enough, it doesn't matter what value was passed in to lst1 if you immediately overwrite it with an empty list.

(for others reading this:) Separating out what I labeled "irrelevant" is not quite identical, but I'm trying to point out that the input was overwritten.

I don't think this function should take user input or have a default argument at all. Let it be a function with one job, and just pass it the data to work on. User input can be collected elsewhere.

Based on Barmar's note, and the principle of using only unmutable default values, your code should look something more like this:

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()

Basically, input returns a string value, and you need to convert it into a list of integers first before you start working on it.

  • You can swap out the list comprehension for map(int, inp1.split(" ")) as it will do the same (but you can't iterate through a map more than once unless you wrap it in a list() function first).

Secondly, avoid setting mutable default arguments as (in short) can lead to weird results when rerunning the same function multiple times.

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