Order by New Alphabet

New Alphabet Sort Challenge

 

Given a new alphabet of 26 letters with no duplicates and arranged in the following order:

ZRSTHIGMAUNOQEDPCKJYFWLVBX

Write a Python program that sorts the words of a given sentence based on this new alphabet order. The program should print the words of the next sentence, separated by spaces, in the new order using the first letter of each word.

“Python uses whitespace indentation, rather than curly brackets or keywords”

Steps

  1. Define the new alphabet: Create a dictionary where each letter in the new alphabet corresponds to its position in the alphabet.
  2. Split the sentence into words: Use the split() function to divide the sentence into a list of words.
  3. Sort the words: Use the sorted() function with a custom sorting key. The key should be a function that returns the position of the first letter of a word in the new alphabet.
  4. Print the sorted words: Join the sorted words into a sentence using the join() function and print the result

Expected ouput

rather than indentation uses or python curly keywords whitespace brackets

Solutions


# Define the new alphabet
new_alphabet = 'ZRSTHIGMAUNOQEDPCKJYFWLVBX'
alphabet_dict = {char: i for i, char in enumerate(new_alphabet)}

# Define the sentence
sentence = "Python uses whitespace indentation, rather than curly brackets or keywords"

# Remove punctuation and convert to lowercase
sentence = ''.join(e for e in sentence if e.isalnum() or e.isspace()).lower()

# Split the sentence into words
words = sentence.split()

# Sort the words based on the new alphabet order
sorted_words = sorted(words, key=lambda word: alphabet_dict[word[0].upper()])

# Print the sorted words
print(' '.join(sorted_words))


This program works by creating a dictionary that maps each character in the new alphabet to its position. Then, it splits the sentence into words and sorts them using the sorted() function. The key for sorting is a function that returns the position of the first letter of a word in the new alphabet. Finally, it joins the sorted words back into a sentence and prints the result. The sentence is also converted to lowercase and punctuation is removed to ensure accurate sorting. The upper() function is used when looking up the position of a letter in the dictionary because the new alphabet is in uppercase.

Please note that this program assumes that the sentence does not contain any characters that are not in the new alphabet. If the sentence can contain such characters, additional error checking should be added.

Bonus

The program does not handle ties when two words start with the same letter.  Extend the key function to consider more letters of the words.

We will be happy to hear your thoughts

Leave a reply

Python and Excel Projects for practice
Register New Account
Shopping cart