if number is 1-2, 4 or 6-8 or 12-28, 30, 32...

Don Garrett garrett at bgb.cc
Mon Jun 10 17:58:57 EDT 2002


Gustaf Liljegren wrote:
> I'm making a function that takes one integer and returns a boolean that 
> says if the integer matches a number in a certain group of numbers. This 
> group consists of single numbers aswell as ranges spanning thousands of 
> numbers. I'm looking for an elegant way to write this function.
> 
> Thanks in advance!
> 
> Gustaf

   This very much depends on the group of numbers.

   If the numbers you are testing against are in a list named group, you can 
just do "k in group" to see if the number you are testing is anywhere in the 
list. This is possibly the simplest way to do this.

   If you are going to do many tests against the same group of numbers, put 
the group in a dictionary (using the numbers as keys, and None or 1 or some 
other filler value for the values). Then you can use "k in group" (where the 
dictionary is named group) to see if k is in the group of numbers.

   This is just like using the list, except that the tests will use the hash 
table of the dictionary to speed up the testing. However, you have to spend 
the CPU/memory to build the dictionary, so this mechanism is slower if you are 
only doing a couple of lookups against the same group of numbers.

   Both mechanisms leverage the built in strengths of the language, require a 
minimum of work, and should be easy to understand.

-- 
Don Garrett                             http://www.bgb.cc/garrett/
BGB Consulting                                      garrett at bgb.cc




More information about the Python-list mailing list