Mostly Linux & Python syntax notes and hyperlinks.

Tuesday, November 29, 2011

python: note the non-intuitive behavior of range(start,end+1)


range(a,b) starts at a and ends at b-1

>>> for n in range(1,3):
...    print str(n)
...
1
2
>>>

You could introduce bugs in your code by not being careful of this.

Monday, November 28, 2011

python: 2-D dictionary, somewhat dynamically filled

counts=dict(A=dict(),B=dict())
for n in range(0,6): 

    Fn='F'+str(n)
    counts['A'][Fn]=n
    counts['B'][Fn]=-n



Then counts = {'A': {'F0': 0, 'F1': 1, 'F2': 2, 'F3': 3, 'F4': 4, 'F5': 5}, 'B': {'F0': 0, 'F1': -1, 'F2': -2, 'F3': -3, 'F4': -4, 'F5': -5}} 

That is:
for t in ('A','B'):
     for n in range(0,6):
         Fn='F'+str(n)
         print("counts[%s][%s]=%d" % (t,Fn,counts[t][Fn]))
will print


counts[A][F0]=0
counts[A][F1]=1
counts[A][F2]=2
counts[A][F3]=3
counts[A][F4]=4
counts[A][F5]=5
counts[B][F0]=0
counts[B][F1]=-1
counts[B][F2]=-2
counts[B][F3]=-3
counts[B][F4]=-4
counts[B][F5]=-5