Skip to content

Added Link Shortener Tool #153

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions L/link-shortner/Readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
## link shortener in Python
URL shortener using the hashlib library to generate short URLs based on the MD5 hash of the original URL.
<br>

## Note
URLShortener is a class that generates short URLs from original URLs and maintains a mapping between them. It uses the MD5 hash of the original URL to create a short key.
35 changes: 35 additions & 0 deletions L/link-shortner/link_shortner.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import hashlib

class URLShortener:
def __init__(self):
self.url_mapping = {}
self.base_url = "https://short.url/"

def shorten_url(self, original_url):
# Generate a unique identifier for the URL using MD5 hash
md5_hash = hashlib.md5(original_url.encode()).hexdigest()

# Take the first 8 characters of the hash as the short URL
short_url = md5_hash[:8]

# Store the mapping between the short URL and the original URL
self.url_mapping[short_url] = original_url
return self.base_url + short_url

def expand_url(self, short_url):
# Extract short key from URL
short_key = short_url.split("/")[-1]

# Look up original URL from mapping
original_url = self.url_mapping.get(short_key, None)
return original_url

# Usage
if __name__ == "__main__":
url_shortener = URLShortener()
original_url = "https://www.example.com"
short_url = url_shortener.shorten_url(original_url)
print(f"Short URL: {short_url}")
expanded_url = url_shortener.expand_url(short_url)
print(f"Expanded URL: {expanded_url}")