Home > front end >  Longest sequence of equal numbers in python
Longest sequence of equal numbers in python

Time:10-13

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

CodePudding user response:

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

Separating out what I labeled "irrelevant" is not quite identical, but I'm trying to point out how it's overwritten. Personally, I don't think this function should take input or have a default argument at all. Let it be a function with one job -- take input separately.

CodePudding user response:

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.

  • Related