Find the Runner-Up Score!

  • + 2 comments

    I think "pythonic" is an overused word :) Anyways I did a profile on those two implementations:

    from profilehooks import profile
    
    
    @profile
    def snd_largest_0():
        n, a = int(raw_input()), list(set([int(x) for x in raw_input().split()]))
        return sorted(a)[len(a)-2]
    
    
    @profile
    def snd_largest_1():
        n = int(raw_input())
        arr = map(int, raw_input().split())
        return max([x for x in arr if x != max(arr)])
    
    
    print snd_largest_0()
    print snd_largest_1()
    
    *** PROFILER RESULTS ***
    snd_largest_0 (E:/python_projects/hello_world/second_largest.py:6)
    function called 1 times
    
             7 function calls in 1.633 seconds
    
       Ordered by: cumulative time, internal time, call count
    
       ncalls  tottime  percall  cumtime  percall filename:lineno(function)
            1    0.000    0.000    1.633    1.633 second_largest.py:6(snd_largest_0)
            2    1.633    0.816    1.633    0.816 {raw_input}
            1    0.000    0.000    0.000    0.000 {sorted}
            1    0.000    0.000    0.000    0.000 {method 'split' of 'str' objects}
            1    0.000    0.000    0.000    0.000 {len}
            1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
            0    0.000             0.000          profile:0(profiler)
    
    
    *** PROFILER RESULTS ***
    snd_largest_1 (E:/python_projects/hello_world/second_largest.py:12)
    function called 1 times
    
             12 function calls in 1.862 seconds
    
       Ordered by: cumulative time, internal time, call count
    
       ncalls  tottime  percall  cumtime  percall filename:lineno(function)
            1    0.000    0.000    1.862    1.862 second_largest.py:12(snd_largest_1)
            2    1.862    0.931    1.862    0.931 {raw_input}
            1    0.000    0.000    0.000    0.000 {map}
            6    0.000    0.000    0.000    0.000 {max}
            1    0.000    0.000    0.000    0.000 {method 'split' of 'str' objects}
            1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
            0    0.000             0.000          profile:0(profiler)
    
    
    Process finished with exit code 0
    

    My code read everything in one go then just returns and every function or method is called only once (total of 7 function calls).

    Your code on the other hand has 12 function calls and calls max() for every element in the list. Also, according to PEP, variable names should start with lowercase, so N should be n.

    I suppose I could use map to change list elements to int, but in this case list comprehension is almost as fast.