Skip to content
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

Saksham Jain| url_shortener| Added a URL shortener #368

Open
wants to merge 1 commit into
base: master
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
14 changes: 14 additions & 0 deletions url_shortener/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
### URL Shortener
Project Description

URL Shortener is a simple Python program that generates short URLs for long URLs. It uses the MD5 hash of the long URL to create a unique short identifier, allowing users to convert long URLs into shorter, more manageable links.
Idea

Usage

To use the URL Shortener, simply create an instance of the URLShortener class and call the shorten_url() method to generate a short URL for a long URL. You can also use the expand_url() method to retrieve the original long URL from a short URL.

Contributors

saksham-jain177
https://github.com/saksham-jain177
36 changes: 36 additions & 0 deletions url_shortener/url_shortener.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import hashlib

class URLShortener:
def __init__(self):
self.url_map = {}

def generate_short_url(self, long_url):
hash_object = hashlib.md5(long_url.encode())
short_url = hash_object.hexdigest()[:8]
return short_url

def shorten_url(self, long_url):
if long_url in self.url_map:
return self.url_map[long_url]
else:
short_url = self.generate_short_url(long_url)
self.url_map[long_url] = short_url
return short_url

def expand_url(self, short_url):
for long_url, url_hash in self.url_map.items():
if url_hash == short_url:
return long_url
return "Short URL not found"

if __name__ == "__main__":
shortener = URLShortener()
long_url = "https://www.example.com/this/is/a/long/url"


short_url = shortener.shorten_url(long_url)
print("Shortened URL:", short_url)


original_url = shortener.expand_url(short_url)
print("Original URL:", original_url)