[Tutor] Automatic generation of an "all possible combinations" array

Luke Paireepinart rabidpoobear at gmail.com
Fri Jun 15 20:57:08 CEST 2007


Andy Cheesman wrote:
> The code works great, Thanks for the speedy response. The only problem
> which I can see is that the code scales very bad with the size of n.
>   
You could also do this by iterating in base-16 instead of base-10...
given a string of hex,
like "59FDE", there is a direct correlation between the value of each 
digit and the value in binary representation.
In other words, every digit is 4 binary bits.
So if you have a dictionary or something mapping these values to their 
binary equivalents,
hexmap = {"0":"0000","1":"0001","2":"0010","3":"0011","4":"0100","5":"0101",
"6":"0110","7":"0111","8":"1000","9":"1001","a":"1010","b":"1011","c":"1100",
"d":"1101","e":"1110","f":"1111"}

then for any number n,
you simply do the following:
binary = ""
for x in hex(n)[2:]:
  binary += (hexmap[x])

this is very simple, but I am unsure how efficient it is.
You'd have to test it out.
But it might be faster for large n, compared to a repeated-division or 
recursive approach (I have no idea.)
I used strings for brevity of the code, but you could do the same with 
lists.
obviously you'd need another loop to generate your values (0 -> n) so 
that this can convert them to hex.
HTH,
-Luke


More information about the Tutor mailing list