I am doing a Pig Latin code in which the following words are supposed to return the following responses:
JavaScript
x
7
1
"computer" == "omputercay"
2
"think" == "inkthay"
3
"algorithm" == "algorithmway"
4
"office" == "officeway"
5
"Computer" == "Omputercay"
6
"Science!" == "Iencescay!"
7
However, for the last word, my code does not push the ‘!’ to the end of the string. What is the code that will make this happen?
All of them return the correct word apart from the last which returns “Ience!Scay!”
JavaScript
1
21
21
1
def pigLatin(word):
2
vowel = ("a","e","i","o","u")
3
4
first_letter = word[0]
5
if first_letter in vowel:
6
return word +'way'
7
8
else:
9
l = len(word)
10
i = 0
11
while i < l:
12
i = i + 1
13
if word[i] in vowel:
14
x = i
15
new_word = word[i:] + word[:i] + "ay"
16
17
if word[0].isupper():
18
new_word = new_word.title()
19
20
return new_word
21
Advertisement
Answer
For simplicity, how about you check if the word contains an exlamation point !
at the end and if it does just remove it and when you are done add it back. So instead of return
ing just check place !
at the end (if you discovered it does at the beggining).
JavaScript
1
31
31
1
def pigLatin(word):
2
vowel = ("a","e","i","o","u")
3
4
first_letter = word[0]
5
if first_letter in vowel:
6
return word +'way'
7
8
else:
9
hasExlamation = False
10
11
if word[-1] == '!':
12
word = word[:-1] # removes last letter
13
hasExlamation = True
14
15
l = len(word)
16
i = 0
17
while i < l:
18
i = i + 1
19
if word[i] in vowel:
20
x = i
21
new_word = word[i:] + word[:i] + "ay"
22
23
if word[0].isupper():
24
new_word = new_word.title()
25
26
break # do not return just break out of the `while` loop
27
if hasExlamation:
28
new_word += "!" # same as new_word = new_word + "!"
29
return new_word
30
31
That way it does not treat !
as a normal letter and the output is Iencescay!
. You can of course do this with any other character similarly
JavaScript
1
8
1
specialCharacters = ["!"] # define this outside the function
2
3
def pigLatin():
4
# all of the code above
5
if word in specialCharacters:
6
hasSpecialCharacter = True
7
# then you can continue the same way
8