Crash Code Part-3 (Word shortening with duplicates)


Following question was asked in IBM Corporation-Campus Hiring- 18-Jan-23_B2. Test duration: 30 mins

Problem Description

A particular application uses the following logic to reduce length of sentences by shortening the individual words:

  • Take each word and remove the vowels in it to get its shortened form
  • It is possible that two different words have the same shortened form. In this case:
    • The first shortened word is used as-is
    • For the second shortened word that is same as the first, number 1 is appended at the end
    • For the third shortened word that is same as the first, number 2 is appended at the end and so on.

Given a sentence, the program should print the final shortened version of the sentence based on the rules above.

For example, short form for both ‘build and ‘bold’ would be ‘bid’ as per the rules above. The numbers to be added will depend on the order of the words in the sentence

Function Description:

Complete the function shorten5entence in the editor below. The function must print the final shortened version of the sentence based on the rules above

shorten5entence has the following parameter(s): sentence: a String

Constraints

  • Only lowercase letters would be present in the sentence

Examples

Sample Case 0

Sample Input For Custom Testing

it was bold to make the build larger

Sample Output

t ws bld t1 mk th bld1 lrgr

Explanation:

The words are shortened by removing the vowels from each word. When there are repeating words in shortened form, the first one is used as-is and the second one onwards a number is appended. Thus, ‘it’ becomes ’t’,’to’ becomes t1’. Similarly ‘bold’ becomes ‘bld’ and ‘build’ becomes ‘bld1’.

Sample Case 1

Sample Input For Custom Testing

we made the builds larger

Sample Output

w md th blds lrgr

Explanation:

The words are shortened by removing the vowels from each word. Here all shortened versions are distinct, hence no need to append numbers.

Solve

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/bin/python3
#
# Complete the 'shortenSentence' function below.
#
# The function accepts STRING sentence as parameter.
#
import re
def shortenSentence(sentence):

  # Write your code here
  
    arr = sentence.split()
    arr2 = []
    vowels = ['a', 'e', 'i', 'o', 'u']
    newwrd = ""
    count = 0
    for word in arr:
        for i in range (len(word)):
            if (word[i] not in vowels):
                newwrd = newwrd + word[i]
        if (newwrd in arr2):
            res = re.compile(newwrd)
            y = list(filter(res.match, arr2))[-1]
            if (y[-1].isnumeric()):
                newwrd = newwrd + str(int(y[-1]) + 1)
            else:
                newwrd = newwrd + str(1)
        arr2.append(newwrd)
        newwrd = ""
    print(" ".join(arr2))

if __name__ == '__main__': 
  [...]