A more straightforward solution wanted

Terry Reedy tjreedy at udel.edu
Sat Sep 25 01:20:55 EDT 1999


jblake at stamp-coin.com says...
        
>        I'm bashing my head trying to think of a more straightforward
>        way to do the following:
...
>        Is there a more straightforward method of doing this, other
>        than using yet another database, for the lookup functions, etc?

One possibility: use Python dictionaries
        
For instance, after 

>           if scott_number = 1:
>               return_list[44] = " "

mentally replace 

>               if scott_suffix = " ":
>                   return_list[45] = 1
>                   return_list[46] = "Type A"
>                   return_list[51] = " "
>                   return_list[52] = 1
>                   return_list[53] = " "
>               elif scott_suffix = "a":
>                   return_list[45] = 1
>                   return_list[46] = "Type B"
>                   return_list[51] = " "
>                   return_list[52] = 1
>                   return_list[53] = "b"
>               else:
>                  return_list[45] = 1
>                  return_list[46] = "Type A/Italic Z"
>                  return_list[51] = " "
>                  return_list[52] = 1
>                  return_list[53] = "a"

with
                 (return_list[45],
                  return_list[46], 
                  return_list[51],
                  return_list[52],
                  return_list[53]) = {" ":(1,"Type A"," ",1," "),
                                      "a":(1,"Type B"," ",1,"b")}.get(
                  scott_suffix, (1,"TypeA/Italic Z"," ",1,"a"))


Now, the dictionary and default each depend on the scott_number 1 to 5, 
so each can be replaced by a list of choices indexed by scott_number.

IE, (untested)

#before loop, so execute only once
list_of_dicts = [
  "dummy list item for unused index 0",
  {" ":(1,"Type A"," ",1," "),"a":(1,"Type B"," ",1,"b")},
  {#dict for scott_number 2},
  #etc for 3, 4, and 5
]
list_of_default_tuples = [
  "dummy for 0",
  (1,"TypeA/Italic Z"," ",1,"a),
  #etc for 2,3,4,5
]
...

Then, within loop (or func called for each line),
possible after checking scott_number in range 1...5,

  (return_list[45], return_list[46], return_list[51],
   return_list[52], return_list[53]) =\
  list_of_dicts[scott_number].get(
    scott_suffix, list_of_default_tuples[scott_number])

This compresses about 100 lines to less than 20.

Terry J. Reedy





More information about the Python-list mailing list