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)

















No comments:

Post a Comment