Skip to content

Instantly share code, notes, and snippets.

@asilachev
Created February 3, 2016 16:32
Show Gist options
  • Select an option

  • Save asilachev/91bd40b07bc40e3e2f2a to your computer and use it in GitHub Desktop.

Select an option

Save asilachev/91bd40b07bc40e3e2f2a to your computer and use it in GitHub Desktop.

Revisions

  1. asilachev created this gist Feb 3, 2016.
    35 changes: 35 additions & 0 deletions url_shortener.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@
    from django.conf import settings


    # Defining alphabet of custom base as [a-z] + [A-Z] + [0-9]
    alphabet = map(chr, range(97, 123) + range(65, 91)) + map(str, range(0, 10))
    base = len(alphabet)

    def encode(str):
    reversed_str = str[::-1]
    pow_num = 0
    result = 0

    for i in range(0, len(reversed_str)):
    char = reversed_str[i]
    char_value = alphabet.index(char)
    result += char_value * pow(base, pow_num)
    pow_num += 1

    return result

    def decode(i):
    result = ''

    if i < 0:
    raise ValueError('Must be a positive integer.')
    elif not i:
    result = alphabet[0]
    while i > 0:
    result = alphabet[i % base] + result
    i /= base

    return result

    def get_url(short_url):
    return "http://%s/%s" % (settings.PROXY_DOMAIN, short_url)