Thursday 17 October 2013

Write short codes in Python - Part 3

1) Flatten a list of nested lists in Python

    from compiler.ast import*
    L=[0, [1, 2], [3, 4, [5, 6]], 7]
    print flatten(L)

    output: [0, 1, 2, 3, 4, 5, 6, 7]

2) Filter a list in Python

    M=[1,2,3,4]
    [x for x in M if x%2]

    output: [1,3]

3) Shortest conditional statement in Python
    [2,3][a>b]

    output: 3 if a>b else 2

4) Shortest Prime Number Checker in Python

      x,y=7,2
      while x%y:y+=1
      print x==y

    # Replace 7 by any number to be checked for prime


5) Nth Fibonacci number in Python
    f=lambda x:x>1and f(x-1)+f(x-2)or x

    f(5)
    output: 5

6) Traverse only some part of a list with a fixed step size in Python

     >>> A=[1,2,3,4,5,6,7,8,9,10]
     >>> A[2:8:2]                 # A[start:stop:step]
     [3, 5, 7]

7) Reverse a list in Python
     >>> A=[1,2,3,4,5,6,7,8,9,10]
     >>> A[::-1]
     [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

8) Round a floating number to an integer in Python
     int(round(2.3))
             vs
     int(.5+2.3)


9) Absolute value of a number in Python

     -8*-1             vs            abs(-8)

10) Import modules in Python

      from fractions import*               vs             from fractions import gcd

     >>> gcd(8,4)
     4