Skip to content

Commit 5c01b3a

Browse files
authored
Update Python Program to Sort Words in Alphabetic Order.py
Changes: >Removes punctuation >Sorts all words alphabetically by using consistent case (.lower()) >Ignores duplicate words >Output is a dictionary which assigns each alphabetized word (value) a respective number (key)
1 parent b2f8509 commit 5c01b3a

File tree

1 file changed

+31
-7
lines changed

1 file changed

+31
-7
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,42 @@
1-
# Program to sort alphabetically the words form a string provided by the user
1+
# Program to sort words alphabetically and put them in a dictionary with corresponding numbered keys
2+
# We are also removing punctuation to ensure the desired output, without importing a library for assistance.
23

3-
my_str = "Hello this Is an Example With cased letters"
4+
# Declare base variables
5+
word_Dict = {}
6+
count = 0
7+
my_str = "Hello this Is an Example With cased letters. Hello, this is a good string"
8+
#Initialize punctuation
9+
punctuations = '''!()-[]{};:'",<>./?@#$%^&*_~'''
410

511
# To take input from the user
612
#my_str = input("Enter a string: ")
713

14+
# remove punctuation from the string and use an empty variable to put the alphabetic characters into
15+
no_punct = ""
16+
for char in my_str:
17+
if char not in punctuations:
18+
no_punct = no_punct + char
19+
20+
# Make all words in string lowercase. my_str now equals the original string without the punctuation
21+
my_str = no_punct.lower()
22+
823
# breakdown the string into a list of words
924
words = my_str.split()
1025

11-
# sort the list
26+
# sort the list and remove duplicate words
1227
words.sort()
1328

14-
# display the sorted words
15-
16-
print("The sorted words are:")
29+
new_Word_List = []
1730
for word in words:
18-
print(word)
31+
if word not in new_Word_List:
32+
new_Word_List.append(word)
33+
else:
34+
continue
35+
36+
# insert sorted words into dictionary with key
37+
38+
for word in new_Word_List:
39+
count+=1
40+
word_Dict[count] = word
41+
42+
print(word_Dict)

0 commit comments

Comments
 (0)