Wednesday, October 13, 2010

Python wisdom from stackoverflow #1

I had started participating in "stack overflow" in anticipation to improve my knowledge on topics of interest. What would be better than answering, working on problems posted by users and also look at the answers provided by various folks from the community.

In many posts, I could find some very elegant way of attacking the problem that I had never thought of. It was clear that there are nuggets of wisdom buried in "stack overflow" and mostly it would be difficult to go back and look at them. So I started by collecting weekly wisdoms on topic of my interest which usually is "Python programing". The good thing is that they are going to be unrelated snippets and bad thing is that their isn't any central theme to these posts.

Starting with this post, I will try to pull some neat solutions provided there for reference and later perusal.

#1 : round-up numbers to two decimal points

anFloat = 1234.55555
 print round(anFloat, 2)
# Output : 1234.5599999999999
rounded = "%.2f" % round(anFloat, 2)
print rounded
# Output: '1234.56'

#2: subprocess.Popen and shell nuances

The following gives an error, even if it looks like you are doing normal operation.

subprocess.Popen('export http_proxy=' + options)

The issue here is that the export is not truly an executable or command. It is a built-in command of shell like bash.
By default Popen does an os.execvp() to spawn a new process. If you want to use shell intrinsic commands then you should be doing the following

subprocess.Popen('export http_proxy=' + options, shell=True)

#3: Pair list elements
Consider a list : [1, 2, 3, 4, 5]. How do you work with successive pairs like (1,2), (2,3), (3,4) ....
A variation of zip which pairs two elements of a list.

def pairs(it):
    it = iter(it)
    prev = next(it)
    for v in it:
        yield prev, v
        prev = v
        
a = [1,2,3,4,5]
for prev, cur in pairs(a):
    print prev, cur


#4: Repeating elements in list comprehension
Try generating a list like [0, 0, 1, 1, 2, 2] using list comprehension

m = 3   #the list of integers
n = 2   # of repetitions
[x for x in range(m) for y in range(n)]


#5: Printing a stack trace without raising a exception

import traceback
def f():
    def g():
        traceback.print_stack()
    g()
    
f()

#6: Mixing global and local variable names
Consider the following :
def f():
    x = 12    #this is a local variable
    global x  #this is a global I declared before
    x = 14    #changes global x
    # How do you access the local x?
    
import dis
print dis.dis(f)

The global keyword isn't there at all. Assignment statement gets compiled as STORE_GLOBAL.
The local variable can not be accessed any more.

1 comment:

  1. Do You Want To Know What Is chf-usd? See The Latest Exchange Rate For CHF USD Here! We Will Keep You Updated With The Latest Rates.

    ReplyDelete