Reputation: 79
I am revisiting a B-Language translation program example in Python from Stanford's notes. This program works where words are transformed such that every vowel cluster is reduplicated with a leading "b".
For example:
The code below works perfectly fine, but due to confusion, I was wondering if there's an alternative way to compute the translate(word, separator="b") function which converts a word string by reduplicating each vowel cluster with a leading b. Is it possible to find out a way which exclude the usage of the computation "start = -1"?
def translate(word, separator="b"):
start = -1
translation = ""
for i in range(len(word)):
ch = word[i]
if isEnglishVowel(ch):
if start == -1:
start = i
else:
if start >= 0:
translation += word[start:i] + separator + word[start:i]
start = -1
translation += ch
if start >= 0:
translation += word[start:] + separator + word[start:]
return translation
def isEnglishVowel(ch):
return len(ch) == 1 and "aeiou".find(ch) >= 0
def TestTranslate():
while True:
word = input("Enter a single word [or hit enter to quit]: ");
if word == "": break
translation = translate(word)
print("\"{}\" -> \"{}\"".format(word, translation))
if __name__ == "__main__":
TestTranslate()
Thank you.
Upvotes: 2
Views: 139
Reputation: 456
I modified the code a bit. It uses vowels
instead of start
but the internal logic is a little more simplified. Basically grow vowels
until you encounter a consonant, then pop vowels
into the translation string with the separator in between.
def translate(word, separator="b"):
translation = ""
vowels = ""
for ch in word:
if vowels and not isEnglishVowel(ch):
translation += separator + vowels
vowels = ""
translation += ch
if isEnglishVowel(ch):
vowels += ch
return translation + separator + vowels if vowels else translation
def isEnglishVowel(ch):
return len(ch) == 1 and ch in 'aeiou'
def TestTranslate():
while True:
word = input("Enter a single word [or hit enter to quit]: ")
if word == "": break
translation = translate(word)
print("\"{}\" -> \"{}\"".format(word, translation))
if __name__ == "__main__":
TestTranslate()
Upvotes: 1