.pop is cutting off after prematurely - python

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)

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))

Related

Get the longest length words and remove the \n after each string?

f = open('wordlist.txt','w')
for x in range(4):
u = input('please enter how many words you like to write')
f.write(u + '\n')
print('it have been wrote into file')
e = 0
y = 0 #y for total length
f = open('wordlist.txt','r')
for x in f:
print(len(x))
y += len(x)
e += 1
if len(x) >= len(x):
z = len(x) #get largest length
avglength = y/e #get average length for each line
print(z)
print(y)
print(avglength)
as the code above, i want to get the largest length in file but its only get me the length of last word, why is that happening? and how to remove the '\n' after each string which i need to find each word length but the length is incorrect. For example, the 'sss' is supposed to have length of 3 and in my code i added '\n' each line, this may causing the 'sss' is having the length of 4. any helps?
You write in your code:
if len(x) >= len(x):
z = len(x)
which is always going to be True. As a result your z will take the length value of your last x, which will be your last word.
You could keep track of your current maximum length, by outside of the for loop define a max_length variable:
max_length = 0
and in the loop use:
max_length = max([len(x), max_length])
if len(x) >= max_length:
z = len(x)
max_length = z
Or as you pointed out in the comments below you could simply write this entire statement as:
z = max([len(x), z])
provided you have set z = 0 outside of the for loop.
Here is a slightly modified way of doing the calculations you want. It might be easier to read, and it uses the context manager with to handle opening and closing your file:
# get words and write to file
with open('wordlist.txt','w') as f:
for x in range(4):
u = input('please enter a word: ')
f.write(u + '\n')
print('Your words have been written into the file')
# read words and count find length of longest word
with open('wordlist.txt') as f:
words = f.readlines()
word_lengths = [len(i.strip()) for i in words] # get the length of each word in list after removing white space
max_length = max(word_lengths) # find the longest length
total_length = sum(word_lengths) # find the total length of all words
average_word_length = total_length / len(words) # find the average length
You can use .split() method to remove \n from your string.
Here is what you have to do:
x = x.split('\n')
x = x[0]
You can add this in for x in f: loop.
Here is the full code:
f = open('wordlist.txt', 'w')
for x in range(4):
u = input('Please enter the word: ')
f.write(u + '\n')
print('it has been written into file')
z = 0
e = 0
y = 0 # y for total length
f = open('wordlist.txt', 'r')
for x in f:
x = x.split('\n') #Now, x = ['Your Input', '']
x = x[0] #Select first string
print(len(x))
y += len(x)
e += 1
if len(x) >= z:
z = len(x) # get largest length
avglength = y / e # get average length for each line
print(z)
print(y)
print(avglength)
Here is the run:
Please enter the word: This
Please enter the word: is
Please enter the word: just
Please enter the word: testing
Respective Output:
4
2
4
7
7
17
4.25
Another possible solution:
# Use open() as a context manager so you don't have to worry about closing the file.
with open('wordlist.txt','r') as opened:
# Create a list of words in the file.
# words = list(opened)
# EDIT: The traditional way to split some lines and strip
# the newline character.
words = opened.read().strip().split("\n")
# Start max_length at negative 1.
max_length = -1
# List object to hold all word lengths.
all_lengths = []
# Number of words written to file
num_of_words = len(words)
# Iterate the list of words.
for word in words:
# Get length of the current word.
current_length = len(word)
# Append the length of the current word to the list.
all_lengths.append(current_length)
# Using all_lengths[-1] gets the latest item on the list
# Also, we only care if the current value is larger than the max value.
if all_lengths[-1] > max_length:
max_length = all_lengths[-1]
# Average length of word per line.
average_length = sum(all_lengths) / num_of_words

Function, that turns a word in a string to stars

Im doing an exercise, where im defining a function that takes two inputs - a sentence and a word, that will be replaced by stars in the sentence input.
Problem is, I cant get the final output to put spaces in between words, ie it prints all the words crammed together. Any help please ?
def censor(text, word):
lis = text.split()
output =""
p = []
for w in lis:
if w != word:
p.append(w)
else:
l = len(w)
y = "*" * l
p.append(y)
output = output.join(p)
print output
censor("Hello world televison", "world")
You don't need to initialize output to an empty string first. You can just do
output = " ".join(p)
Notice the " ".join(), that is what determines how you are joining your strings. In this case, it's a single space. Also, you need to return something from your function, so instead of using print you should do
return output
Here's another solution, even though it's a little tricky, it should handle all the different cases that can occur:
def censor(text, word):
text = '.' + text + '.'
for i in range(len(text)):
if text[i].lower() == word[0].lower():
toCensor = True
for j in range(len(word)):
if text[i + j].lower() != word[j].lower():
toCensor = False
break
if toCensor:
if (ord(text[i - 1]) < ord('A') or ord(text[i - 1]) > ord('z'))\
and (ord(text[i + len(word)]) < ord('A') or ord(text[i + len(word)]) > ord('z')):
lst = list(text)
for j in range(len(word)):
lst[i + j] = '*'
text = "".join(lst)
lst = list(text)
lst = lst[1 : -1]
return "".join(lst)
censor("World worlds world television", "world")
>>> ***** worlds ***** television
It handles capital letters and all the punctuation.

Python Scrambler Program

This program takes words in a sentence and scrambles them.
The rules are:
- first and last letter remain the same
- punctuation at the end of a word stays the same
- punctuation with a word is scrambled like the middle letters
My problem is that if I have multiple punctuation at the end of a word it does not scramble it.
Ex) testing!!! should be something like t!ste!nig! or t!est!nig!
but not tstenig!!!
How can I fix that?
import random
import string
original_text = input("Enter your text: ").split(' ')
seed = int(input("Enter a seed (0 for random): "))
punctuation = []
for c in string.punctuation:
punctuation.append(c)
if seed is not 0:
random.seed(seed)
randomized_list = []
def scramble_word(word):
alpha = word[0]
end_punctuation = ''
if word[-1] in punctuation:
x = -1
while word[x] in punctuation:
end_punctuation += word[x]
x -= 1
omega = word[x]
middle = word[1: x]
else:
omega = word[-1]
middle = word[1:-1]
end_punctuation = ""
middle_list = list(middle)
random.shuffle(middle_list)
shuffled_text = "".join(middle_list)
new_words = alpha + shuffled_text + omega + end_punctuation
return new_words
for item in original_text:
if len(item) <= 3:
randomized_list.append(item)
else:
randomized_list.append(scramble_word(item))
new_words = " ".join(randomized_list)
print(new_words)
The problem is that you don't add in the punctuation to the shuffle; see the two amended lines below:
if word[-1] in punctuation:
x = -1
while word[x] in punctuation:
end_punctuation += word[x]
x -= 1
omega = word[x]
middle = word[1: x] + end_punctuation[1:] # Include all except the final character
end_punctuation = end_punctuation[0] # Just use the final character
else:
omega = word[-1]
middle = word[1:-1]
end_punctuation = ""
That does the trick for me:
In [63]: scramble_word('hello!?$')
Out[63]: 'hle?l!o$'
In [64]: scramble_word('hello!?$')
Out[64]: 'h?!ello$'
In [65]: scramble_word('hello!?$')
Out[65]: 'hlel!?o$'
In [66]: scramble_word('hello!')
Out[66]: 'hlleo!'
In [67]: scramble_word('hello!')
Out[67]: 'hello!'
In [68]: scramble_word('hello!')
Out[68]: 'hlleo!'
In [69]: scramble_word('hello')
Out[69]: 'hlelo'
By the way, you don't need the punctuation variable; word[x] in string.punctuation will work the same.
My take on it, can shorten the code a bit. (In Python 3.5.1)
import random
words = input("Enter your text: ")
def scramble(words):
for x in words.split():
middle = x[1:-1]
middle_list = list(middle)
random.shuffle(middle_list)
shuffled = "".join(middle_list)
print ("".join(x[0]+shuffled+x[-1]),"", end="")
scramble(words)
My output was for example from:
Masterson!!%& makes baking%$ potatoes great!
to
Ment!osrs!a%& mkeas bigkna%$ patooets gerat!
I'm sure someone could shorten it even more dramatically.

Python: Converting word to list of letters, then returning indexes of the letters against lower case alphabet

I have already completed the task but in its most basic form looking for help shortening it and so it can apply to any word not just one with eight letters, here's what I've got so far (bit long for what it does):
alpha = map(chr, range(97, 123))
word = "computer"
word_list = list(word)
one = word[0]
two = word[1]
three = word[2]
four = word[3]
five = word[4]
six = word[5]
seven = word[6]
eight = word[7]
one_index = str(alpha.index(one))
two_index = str(alpha.index(two))
three_index = str(alpha.index(three))
four_index = str(alpha.index(four))
five_index = str(alpha.index(five))
six_index = str(alpha.index(six))
seven_index = str(alpha.index(seven))
eight_index = str(alpha.index(eight))
print (one + "=" + one_index)
print (two + "=" + two_index)
print (three + "=" + three_index)
print (four + "=" + four_index)
print (five + "=" + five_index)
print (six + "=" + six_index)
print (seven + "=" + seven_index)
print (eight + "=" + eight_index)
What you are probably looking for is a for-loop.
Using a for-loop your code could look like this:
word = "computer"
for letter in word:
index = ord(letter)-97
if (index<0) or (index>25):
print ("'{}' is not in the lowercase alphabet.".format(letter))
else:
print ("{}={}".format(letter, str(index+1))) # +1 to make a=1
If you use
for letter in word:
#code
the following code will be executed for every letter in the word (or element in word if word is a list for example).
A good start to learn more about loops is here: https://en.wikibooks.org/wiki/Python_Programming/Loops
You can find tons of ressources in the internet covering this topic.
Use for loop for loop,
alpha = map(chr, range(97, 123))
word = "computer"
for l in word:
print '{} = {}'.format(l,alpha.index(l.lower()))
Result
c = 2
o = 14
m = 12
p = 15
u = 20
t = 19
e = 4
r = 17
Start with a dict that maps each letter to its number.
import string
d = dict((c, ord(c)-ord('a')) for c in string.lowercase)
Then pair each letter of your string to the appropriate index.
result = [(c, d[c]) for c in word]
thanks for the help managed to solve it myself in a different way using a function and a while loop, not as short but will work for all lower case words:
alpha = map(chr, range (97,123))
word = "computer"
count = 0
y = 0
def indexfinder (number):
o = word[number]
i = str(alpha.index(o))
print (o + "=" + i)
while count < len(word):
count = count + 1
indexfinder (y)
y = y+1

pattern finding in a string python

I try to create a modified LZW which will find patterns of words inside a string. My problem is that 1st element is '' and last is not checked if it is in the list. I saw the pseudo-code from here : https://www.cs.duke.edu/csed/curious/compression/lzw.html . Here is my script for compression:
string = 'this is a test a test this is pokemon'
diction = []
x = ""
count = 0
for c in string.split():
print (c)
print (x)
#x = x + " " + c
if x in diction:
x += " " + c
#print("debug")
else:
#print(x)
diction.append(x)
x = c
count +=1
#print(count)
print (diction)
I tried to fix the 2nd problem by 'appending' a random word to the end of the string but I don't think that's the best solution.
For the 1st problem I tried just to define the variable "x" as str or None but I get this < class 'str' > inside the list.
The link deals with character and splitting a string will give an array of words.
In order to get not an empty string in the dictionary and parsing the last element.
string = 'this is a test a test this is pokemon'
diction = []
x = ""
count = 0
for c in string.split():
print (c)
if x+" "+c in diction:
x += " " + c
else:
diction.append(x+" "+c)
x = c
count +=1
print (diction)
But perhaps you would like something like :
string = 'this is a test a test this is pokemon'
diction = []
x = ""
count = 0
for c in string:
print (c)
if x+c in diction:
x += c
else:
diction.append(x+c)
x = c
count +=1
print (diction)
I'm not sure what the code pretends, but to fix the issues that you mentioned I think you could do this:
string = 'this is a test a test this is pokemon'
diction = []
x = None
count = 0
for c in string.split():
if x in diction:
x += " " + c
else:
if x: diction.append(x)
x = c
count += 1
if not x in diction: diction.append(x)
print (diction)
The output for that code would be:
['this', 'is', 'a', 'test', 'a test', 'this is', 'pokemon']

Categories

Resources