Saturday 19 October 2013

Write short codes in Python - Part 5

1) Best way to take 2 integer inputs in one line in Python

      n,k=map(int,raw_input().split())

                        vs

      n,k=raw_input().split()
      n=int(n)
      k=int(k)

2) ~-x&x                  vs              (x-1)&x 

Friday 18 October 2013

Why my python code is not working

"""Note: This code may not work, but worth a try""" """Program to print "print this line" 10 times in the most creative way""";i="print this line"
scissor_is ="print this line"
cut_paper_ = "scissor_is"
trash="";"""will this code work?"""

while scissor_is:
    cut_paper_=cut_paper_[:-1:];"""to cut paper """;
    print trash                                                                                                 ,i
    scissor_is=cut_paper_

Shortest Code to Detect Rotated Strings in Python

a,b=raw_input().split()
print ['No','Yes'][a==(2*a).replace(b,"")]

Thursday 17 October 2013

Shortest Magic Square Generator code in Python


127 bytes code                     #Works for odd numbers only

n=3
j,A=n/2,[[0]*n for i in[0]*n]
i=c=0
while c<n*n:c=A[i][j]=c+1;i,j=[i+1,[n,i][i>0]-1][c%n>0],[j,[n,j][j>0]-1][c%n>0]
print A



106 bytes code                     #Works for odd numbers only
n=5
print [[(i+j-1+n/2)%n*n+(i+2*j-2)%n+1for j in range(n)]for i in range(n)] 

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)









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


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


Wednesday 16 October 2013

Write short codes in Python - Part 1

Following approaches can be used to shorten python codes :

1) Use Ternary conditions:

Example :
a=1
b=3
if a>b:
    c=4
else:
    c=5
print c

can be shortened into:

a=1
b=3
c= 4 if a>b else 5
print c

2) Use map function wherever possible. Suppose, a=["12", "10"] then to find sum of the int equivalents of the elements of a can be written in short as:

print sum(map(int,a))                    #output:22



3) If a for loop is run till a particular condition is met, then it can be shorted easily.

Example :

for elem in [1,2,3,4]:
    if elem == 4:
        compositeFound = True
        break
print compositeFound       

can be shortened into:
print any(d==4 for d in [1,2,3,4])

4) If there is no use of iterating variable i in:
     for i in range(n):
        s+=input()

    can be shortened to :
      exec 's+=input();'*x


5) Multiple range() or input() keywords in the code.

Example:

for i in range(input()):
    for j in range(input()):
        a=("learn erlang","ajs code blog", "handling problems in python") #tuple
        a=list(a)     #convert tuple to list
        a.insert(4, input())   #insert user input element into 4 position
        a=tuple(a)   #convert list back to tuple
        print a

 can be shortened into:

r=range
i=input
for i in r(i()):
    for j in r(i()):
        a=("learn erlang","ajs code blog", "handling problems in python")
        a=list(a)
        a.insert(4, i())
        a=tuple(a)
        print a


6) Make list of tuples using ith element of each tuple

7) Tab and space characters are treated as different indenting levels in Python.

Example: If at a certain level, indentation is 2 space characters(say), then at the next level one will generally use an indentation of 3 space characters (at least). So, total 5 bytes are used. Instead, one can use 1 tab character in place of 3 space characters. This will save at least 2 bytes !!!!

8) Instead of p,q,r = '7', '8', '9' use  p,q,r='789'

9) Use * operator instead of range(n), if the value of iterating index is not going to be used. So,
  for i in range(n):

can be shortened to:
  for i in[1]*8:
 

10)Use x*1. to convert integer x to float instead of float(x)