I have to create a dictionary using only capital letters and I need to store the bit value too. The capital letters however are in groupings of 3 and 2 letters (i.e., AA or ZZZ). Now, my code works fine but I would like to neaten it up (because I'm sure I've took a few naughty routes) and I'd appreciate any help!

a = 65
b = 65
c = 65
ab = {}

#This range size gives the perfect AA-ZZZ range of numbers I need.
for i in range(17576):
    byt1 = a << 16
    byt2 = b << 8
    byt3 = c

#This is creating my 3-byte key/value pair
    threeByte = (byt1 + byt2 + byt3)
    ab["%s%s%s" % (chr(a),chr(b),chr(c))] = threeByte

#This is the 2-byte variant
    twoByte = (byt2 + byt3)
    ab["%s%s" % (chr(b),chr(c))] = twoByte

#This section iterates from 65 (Capital 'A') to 90 (Capital 'Z') for all
#3 bytes, and the print is just so I could see it working
    if c < 90:
        c = c+1  
    elif b < 90:
        b = b+1
        c = 65
    else:
        a = a+1
        c = 65
        b = 65
    #print "%s %s %s %s" %(i,a,b,c)

My take:

# pyTonyc version
from pprint import pprint
import string

def az_ord():
    return range(ord('A'), ord('Z')+1)

codes = dict(('%c%c%c' % (a,b,c), (a<<16) + (b<<8) + c)
                for a in az_ord()
                for b in az_ord()
                for c in az_ord())
# make only once the two letter pairs
codes.update(dict(('%c%c' % (a,b), ((a<<8) + b))
                for a in az_ord()
                for b in az_ord()))

pprint(codes.items())

For fancier generic letter range check for example http://stackoverflow.com/questions/5526678/starting-value-for-pythonic-generator-over-possible-letter-combinations (I coded this also sometimes, but I do not find the code at the moment)

Edited 5 Years Ago by pyTony: n/a

I found my generic letter range, it is in thread http://stackoverflow.com/questions/5526678/starting-value-for-pythonic-generator-over-possible-letter-combinations

I updated it though, to use accepted strategy and generalized it. Here my updated version:

from string import ascii_lowercase, ascii_uppercase
from itertools import product

def letter_range(first, last, letters=ascii_lowercase):
    for k in range(len(first), len(last)):
        for x in product(letters, repeat=k+1):
            result = ''.join(x)
            if len(x) != len(first) or result >= first:
                yield result
                if result == last:
                    return
print list(letter_range('a', 'zzz'))
print list(letter_range('BA', 'DZA', ascii_uppercase))

Edited 5 Years Ago by pyTony: n/a

This article has been dead for over six months. Start a new discussion instead.