[CentralOH] Python Problem for DoJo Tonight

mrehner mrehner at e-wrench.net
Fri Mar 15 15:01:08 EDT 2019


Since no one posted a solution here's one with a list of python tutorial links.

import random
import string

# a list of urls for testing
url_list = ["https://astro-pi.org/",

# the data store- a key,value pair
url_dict = {}

# if url is not in the url dictionary
# creates a random 6 character key
# updates url dictionary with key and url
def shorten(url):
    if not search_for_url(url):
        key = make_key()
        # Add new key value pair
        url_dict.update({key: url})

# returns a url value if key is in dictionary, if not returns None (null)
def restore(short):
    return url_dict.get(short, None)

# Create 6 char key using upper case, lower case and numerical digits
def make_key():
    # seed function automatically called with system current time value as the seed value.
    return ''.join(random.choice(string.ascii_letters + string.digits) for _i in range(6))

# returns true if a url is a value in the dictionary
def search_for_url(url):
    return url in url_dict.values()

if __name__ == '__main__':

    # fill the dictionary
    for item in url_list:

    # Verify results
    for k in url_dict:
        print(k, ": ",  url_dict[k])
        print("url for key: ", k, " is ", restore(k), "\n")

    print("Should return None: ", restore("1a2b3c"))

I'm sure it can be improved and some may worry about a collision with a 62^6 random character generator, but that's it for me.



From: CentralOH [centraloh-bounces+mrehner=e-wrench.net at python.org] on behalf of Travis Risner [deeppunster at gmail.com]
Sent: Thursday, March 14, 2019 3:22 PM
To: COhPy Mailing List
Subject: [CentralOH] Python Problem for DoJo Tonight

Hi folks,

Here is today’s problem for people who show up at the DoJo tonight.

Implement a URL shortener with the following methods:

shorten(URL), which shortens the URL into a six-character alphanumeric
string, such as zLg6wl.

restore(short), which expands the shortened string into the
original URL. If no such shortened string exists, return null.

Hint: What if we enter the same URL twice?

See you at the DoJo:

Smokehouse Brewing
1130 Dublin Road
Columbus, OH  43215
(614) 485-0227


More information about the CentralOH mailing list