130k views
5 votes
Given a sequence of Words and the Order of the alphabet. The order of the alphabet is some permutation of lowercase letters. The task is to check whether the given words are sorted lexicographically according to order of alphabet. Return "True" if it is, otherwise "False".

1 Answer

3 votes

Answer:

def is_sorted(words, order):

# Create a dictionary to map each letter to its position in the order string

order_dict = {order[i]: i for i in range(len(order))}

# Check each pair of adjacent words in the sequence

for i in range(len(words) - 1):

word1 = words[i]

word2 = words[i + 1]

# Compare the two words letter by letter

for j in range(min(len(word1), len(word2))):

if word1[j] != word2[j]:

if order_dict[word1[j]] > order_dict[word2[j]]:

return False

break

else:

if len(word1) > len(word2):

return False

return True

Step-by-step explanation:

First, we create a dictionary order_dict that maps each letter in the order string to its position in the string. For example, if order = "bcdefghijklmnopqrstuvwxyza", then order_dict will be {'a': 25, 'b': 0, 'c': 1, ..., 'y': 23, 'z': 24}.

Next, we loop over each pair of adjacent words in the words sequence. For each pair of words, we compare them letter by letter.

If we find a pair of letters that are different, we compare their positions in the order string. If the position of the first letter is greater than the position of the second letter, then the words are not sorted lexicographically, and we return False.

If we reach the end of the loop without finding any mismatched letters, we compare the lengths of the two words. If the first word is longer than the second word, then the words are not sorted lexicographically, and we return False.

If we have checked all pairs of adjacent words without finding any problems, then the words are sorted lexicographically according to the order of the alphabet, and we return True.

Here's an example usage of the function:

python

>>> words = ["hello", "hi", "hills"]

>>> order = "hieabfcdgjkmlnopqrstuvwyxz"

>>> is_sorted(words, order)

True

>>> words = ["apple", "banana", "orange"]

>>> order = "abcdefghijklmnopqrstuvwxyz"

>>> is_sorted(words, order)

False

User VFragosop
by
8.3k points