Thursday 17 October 2013

Write short codes in Python - Part 4

1) All python code of a particular block in one line:

    while 1:
       if x>5:x+=2;print x

               vs

    while 1:
      if x>5:
        x+=2
        print x


 2) Find a to the power b in Python
      a**b                           vs              pow(a,b)

3) Alternative to append and extend methods in Python
     A=[1,2,3]
     B=[4,5,6]

    If one wants to append list B at the end of A, then:
    A+=[B]                        vs             A.append(B)

   If one wants to extend A using elements of B, then:
    A+=B                          vs              A.extend(B)

4) Increment by n if a certain condition is true in Python
    m+=(Condition)*n        vs              if Condition:m+=n

5) Find power of the Largest power of 2 number <=given number

     N&-N

6) Unset the rightmost set bit in Python
     N&(N-1)

7) Check for substring in Python
     X in Y

     Example: "hllf" in "hello"
     Output: False

8) Remove all characters of one string from another string in Python

     a.translate(None,b)

    Example:
    >>> a="sexy girl"
    >>> b="girl"
    >>> a.translate(None,b)
 
    Output:
    'sexyi'

9) Print Yes/No trick in Python

   print 'YNeos'[x::2]

            vs

    if x==0:
         print 'Yes'
    else
          print 'No'

10) Another trick to check if a number is even in Python
      if(~n&1)                       vs                  if(n%2==0)