Thursday 17 October 2013

Write short codes in Python - Part 2


1) Check membership of an element in a set :
      for e in S                       vs                     {e}<S

2) To check if n is odd or even
         print "odd" if n&1 else "even"
                            or
         print "odd" if n%2 else "even"
                             vs
         print "odd" if n%2==1 else "even"

3) Remove duplicates from a List
    A=[1,2,3,3,2,3,4,2,5]
    list(set(A))
  
    output: [1, 2, 3, 4, 5]

4) Read multiple inputs in one line in python
    A= "1 2 3                  4"
    [int(x) for x in A.split()]

    output: [1, 2, 3, 4]

5) Shortest gcd code in Python
     
    #if gcd is only once in the code
     from fractions import*
           gcd(8,4)

                or
    #if gcd is used multiple times in the code
    from fractions import gcd as g
           g(8,4)

6) Python built-in factorial function
     
     # if factorial function is used multiple times
     import math
     def f(x): return math.factorial(x)
     print f(3)

     #if factorial function is used only once
     import math
     print math.factorial(3)


7) Initialize a list in Python
    A=[0]*8      #initialize list A of size 8 to 0

8) Initialize a list of lists in Python
     A= [[0] * 3 for i in[1]*2]

     output: [[0, 0, 0], [0, 0, 0]]

     A[0][1]=7

     output: [[0, 7, 0], [0, 0, 0]]

9) Access indexes of elements of a List in Python

    A = ['X', 'Y', 'Z']
    for index, value in enumerate(A): print index, value

    output:
             0 X
             1 Y
             2 Z

10) Flatten a list of lists in Python
      A = [[1,2,3], [4,5,6]]
      print sum(A, [])

       output: [1, 2, 3, 4, 5, 6