[Python] single line solution


  • 0
    E

    Python: 3.5
    Test Runtime: 4476 ms

    using from itertools import combinations as combine



    Single line solution:

    return next(([nums.index(x), nums.index(y, nums.index(x)+1)] for (x,y) in combine(nums, 2) if(x + y == target)), None)
    

    Slightly expanded:

    for x, y in combine(nums, 2):
    	if x + y == target:
    		return([nums.index(x), nums.index(y,nums.index(x)+1)])
    

    What I'd actually use for readability:

    for x, y in combine( nums, 2 ):
    	if x + y == target:
    		index1 = nums.index( x )
    		index2 = nums.index( y, index1 + 1 )
    		return( [ index1, index2 ] )
    

  • 0

    What do you mean with "Python: 3.5"? (LeetCode runs Python 2.7.9)


  • 1

    Oh and challenge accepted :-). Efficient (but ugly) oneliners:

    Accepted in 52 ms:

    return reduce(lambda (r,I,i),n: (r or target-n in I and [I[target-n],i], I.__setitem__(n,i) or I, i+1), nums, (0,{},0))[0]
    

    Accepted in 60 ms:

    return reduce(lambda (r,I,i),n: (r or target-n in I and [I[target-n],i], I.update({n:i}) or I, i+1), nums, (0,{},0))[0]
    

  • 0
    E

    @StefanPochmann said in [Python] single line solution:

    What do you mean with "Python: 3.5"? (LeetCode runs Python 2.7.9)

    Oh... wasn't aware & didn't even think about the online compiler lol. Just posted what I wrote + tested with in SublimeText.
     


     
    @StefanPochmann said in [Python] single line solution:

    Oh and challenge accepted :-). Efficient (but ugly) oneliners:
    Accepted in 52 ms:

    Nice!  I have like zero knowledge of CS-related efficiency stuff, and also no idea what's happening in your code lol.  I'll look into reduce & your lambda implementation when I have a few. :grin:


  • 0

    Mine is pretty much the standard solution, just abusing reduce to make it a one-liner. I feel like that's the only use I ever have for reduce, lol.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.