Barbegazi
Barbegazi

Reputation: 1

.pop is cutting off after prematurely

I'm trying to make a Pig Latin translator but if you type in more then two words for an input the .pop function starts to go nuts and I cant figure out why. Information and a fix would be helpful. Thanks.

x = input("Type phrase or word you would like to be translated to pig latin:")
x = x.strip()
y = x.split()
z = []
n = len(y) -1
a = 0

for i in range(0, n):
    first_word = y.pop(a)
    pig_latin = first_word[1:len(first_word)] + first_word[0] + "ay"
    a += 1
    z.append(pig_latin)

print(pig_latin)

Upvotes: 0

Views: 48

Answers (1)

tdelaney
tdelaney

Reputation: 77367

You have several problems. First, you keep reducing the size of the list with pop(a) but also increment a. a eventually exceeds the size of the now-diminished list and you get the error. As a first cut, we can fix the bugs in the original

x = input("Type phrase or word you would like to be translated to pig latin:")
x = x.strip()
y = x.split()
z = []
#n = len(y) -1
n = len(y)
#a = 0

for i in range(0, n):
    first_word = y.pop(0)
    pig_latin = first_word[1:len(first_word)] + first_word[0] + "ay"
    #a += 1
    z.append(pig_latin)

#print(pig_latin)
print(" ".join(z))

But there is no advantage to doing the error prone indexing. We could shorten the program to

x = input("Type phrase or word you would like to be translated to pig latin:")
y = x.strip().split()
z = []

for word in y:
    pig_latin = word[1:] + word[0] + "ay"
    z.append(pig_latin)

print(" ".join(z))

Or use list comprehensions to reduce it further still

x = input("Type phrase or word you would like to be translated to pig latin:")
z = [word[1:] + word[0] + "ay" for word in x.strip().split()]
print(" ".join(z))

Upvotes: 1

Related Questions