Skip to content

Commit 8e1840b

Browse files
authored
Merge pull request #3 from charan-s108/charan-s108-shortner-1
Create URL Shortner.py
2 parents 7bbde1f + b9b9c39 commit 8e1840b

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

Coding/URL Shortner.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# URL Shortener Program
2+
# This program generates short URLs for long URLs and provides redirection to the original URL.
3+
4+
import hashlib
5+
6+
# Dictionary to store URL mappings (short URL to long URL)
7+
url_mapping = {}
8+
9+
def generate_short_url(long_url):
10+
# Hash the long URL to generate a unique identifier
11+
hash_object = hashlib.md5(long_url.encode())
12+
hash_hex = hash_object.hexdigest()
13+
14+
# Take the first 8 characters of the hash as the short URL
15+
short_url = hash_hex[:8]
16+
17+
return short_url
18+
19+
def shorten_url():
20+
print("Welcome to the URL Shortener!")
21+
long_url = input("Enter the long URL to shorten: ")
22+
23+
# Check if the long URL is already in the mapping
24+
if long_url in url_mapping:
25+
print("Short URL: " + url_mapping[long_url])
26+
else:
27+
# Generate a new short URL and add it to the mapping
28+
short_url = generate_short_url(long_url)
29+
url_mapping[long_url] = short_url
30+
print("Short URL: " + short_url)
31+
32+
def redirect_url():
33+
short_url = input("Enter the short URL to redirect: ")
34+
35+
# Check if the short URL exists in the mapping
36+
if short_url in url_mapping.values():
37+
# Find the corresponding long URL
38+
long_url = next(key for key, value in url_mapping.items() if value == short_url)
39+
print("Redirecting to the original URL: " + long_url)
40+
else:
41+
print("Short URL not found. Please enter a valid short URL.")
42+
43+
if __name__ == "__main__":
44+
while True:
45+
print("\nMenu:")
46+
print("1. Shorten a URL")
47+
print("2. Redirect a URL")
48+
print("3. Exit")
49+
50+
choice = input("Select an option (1/2/3): ")
51+
52+
if choice == "1":
53+
shorten_url()
54+
elif choice == "2":
55+
redirect_url()
56+
elif choice == "3":
57+
break
58+
else:
59+
print("Invalid choice. Please select a valid option.")

0 commit comments

Comments
 (0)