2

Let's say I'd like to split some data into 60-character parts and store them in a hash. I've got the following solution, but it seems a bit dirty to me: (because of iteration and constant reassigning)

i = 0
while signature != '':
   header_hash['Some-Authorization-' + i] = signature[:60]
   signature = signature[60:]
   i += 1

Can you come up with a better way of handling this?

Adam Lear
  • 38,111
  • 12
  • 81
  • 101
viraptor
  • 33,322
  • 10
  • 107
  • 191
  • I believe this is identical to http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python/312644 – larsks Dec 07 '11 at 02:46
  • I was going to suggest solving this with the `grouper()` recipe. Also, the term "hash" in Python is used to refer to a hash function, rather than a hash map. It is less confusing to call it a `dict`. Also, since your keys are all constant transformations of `int`s, you should probably use a `list` instead of a `dict`. – Michael Hoffman Dec 07 '11 at 02:57
  • @Michael this actually makes sense since header_hash is actually cryptographic hash split into http header fields (renamed later since it wasn't clear actually :) ). I'm not going for broken hungarian python notation ;) – viraptor Dec 07 '11 at 14:44

1 Answers1

3

Although fairly similar to how to evenly split a list into chunks I believe this to still be a valid problem, but will contain part of the answer to that previous question:

def hashing(header_hash, signature, hash_size):
     for index, i in enumerate(xrange(len(signature), hash_size)):
          header_hash['Some-Authorization-%s' % index] = signature[i:i+hash_size]

This would be my answer, Looking over the itertools functions provided I suspect rejoining them after the grouping would negate any benefit from using itertools.

Community
  • 1
  • 1
Serdalis
  • 10,296
  • 2
  • 38
  • 58
  • I do like this... enumerate(xrange(...)) still looks like it could be simplier in some way, but it's better than my while :) – viraptor Dec 07 '11 at 14:42