Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have md5 hash string, e.g:

_hash = '743a0e0c5c657d3295d347a1f0a66109'

I want to write function that splits passed string to path in nginx cache format:

print hash2path(_hash, [1, 2, 3])
# outputs '7/43/a0e/743a0e0c5c657d3295d347a1f0a66109'

This is my variant:

def hash2path(_hash, levels):
    hash_copy = _hash
    parts = []
    for level in levels:
        parts.append(_hash[:level])
        _hash = _hash[level:]
    parts.append(hash_copy)  
    return '/'.join(parts)

Can you suggest better variant?

share|improve this question

1 Answer

Why you can't just hardcode cache path calculation?

>>> _hash = '743a0e0c5c657d3295d347a1f0a66109'
>>> def hash2path(_hash):
...     return "%s/%s/%s/%s" % (_hash[0], _hash[1:3], _hash[3:6], _hash)
... 
>>> hash2path(_hash)
'7/43/a0e/743a0e0c5c657d3295d347a1f0a66109'

UPDATE: If you really need to pass level array there is a little bit faster version:

def hash2path(_hash, levels):
    prev = 0
    parts = []
    for level in levels:
        parts.append(_hash[prev:prev + level])
        prev += level
    parts.append(_hash)
    return "/".join(parts)
share|improve this answer
The point is to pass level array to function – San4ez Dec 30 '11 at 7:49
Thank you, Dmitry. But it doesn't work correct. – San4ez Dec 30 '11 at 18:30
Works if prev += level is in 6th line – San4ez Dec 30 '11 at 18:38
Ah, you're right. I didn't test it thoroughly. – hdima Dec 30 '11 at 22:21

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.