How to save each letter while the while loop is running - python

word = raw_input('Enter a word: ')
for i in word:
if i in ['a','e','i','u','A','E','I','O','o','U']:
word1 = i
break
else:
print i,
print ""
i = 0
while word[i]!=word1:
This is where I am having a problem. I need to save each letter before the vowel(or g as I have attempted). This is the beginnings of a pig latin translator. In this stage, I am trying to flip the prefix and the rest of the word.
g = word[i]
i = i+1
prefix = g + word1
print prefix
Example:
input - person
output - rsonpe
input - hello
output - llohe
input - pppat
output - tpppa
input - hhhhhelllllloool
output - llllllooolhhhhhe
I am flipping the letters before the first vowel, and the rest of the word.

you can use regular expression if you are familiar with it or you can just edit your code like this in a very simple and crude way.
word = raw_input('Enter a word: ')
word1 = 0
for i in range(0,len(word)) :
if word[i] in ['a','e','i','u','A','E','I','O','o','U']:
word1=i
break
print word[word1+1:]+word[:word1]+word[word1]

Looks like a job for regular expressions:
import re
Vowel = re.compile('[aeiouAEIOU]')
def flipper ( inStr ) :
myIndex = Vowel.search( inStr ).start() + 1
return inStr[myIndex:] + inStr[:myIndex]
flipper( 'hello' )
output:
'llohe'
Alternatively, if you really want to do it with a while loop, you just need to define a global variable outside of the while loop that you can save to.

Related

How do I choose 2 or more letters in a word?

Basically my plan was to return text with random-sized letters in words i.e. "upper" or "lower". The script is working, though it seems raw (I am a Beginner and I'd appreciate some corrections from You).
The problem is:
It is not consistent. With that said, it can print word 'about' even if it should be 'About' or something similar.
I want to be sure that the maximum of UPPER or lower letters in a row do not exceed 3 letters. and I don't know how to do it.
Thank you in advance.
#!/usr/bin/env python3
import random
message = input()
stop = ''
def mocking(message):
result = ''
for word in message:
for letter in word:
word = random.choice(random.choice(letter.upper()) + random.choice(letter.lower()))
result += word
return result
while stop != 'n':
print(mocking(message))
stop = input("Wanna more? y/n ").lower()
if stop == 'n':
break
else:
message = input()
You need to split the input into words, decide how many positions inside the word you want to change (minimum 3 or less if the word is shorter).
Then generate 3 unique positions inside the word (via random.sample) to change, check if upper then make lower else make upper. Add to resultlist and join words back together.
import random
message = "Some text to randomize"
def mocking(message):
result = []
for word in message.split():
len_word = len(word)
# get max 3 random positions
p = random.sample(range(len_word),k = min(len_word,3))
for position in p:
l = word[position]
if l.isupper():
word = word[:position] + l.lower() + word[position+1:]
else:
word = word[:position] + l.upper() + word[position+1:]
result.append(word)
return ' '.join(result)
while True:
print(mocking(message))
stop = input("Wanna more? y/n ").lower()
if stop == 'n':
break
else:
message = input()
See Understanding slice notation for slicing
At most 3 modifications? I would go with something like this.
def mocking(message):
result = ''
randomCount = 0
for word in message:
for letter in word:
newLetter = random.choice( letter.upper() + letter.lower() )
if randomCount < 3 and newLetter != letter:
randomCount += 1
result += newLetter
else:
result += letter
randomCount = 0
return result
If the random choice has modified the letter then count it.

How to remove Triplicate Letters in Python

So I'm a little confused as far as putting this small code together. My teacher gave me this info:
Iterate over the string and remove any triplicated letters (e.g.
"byeee mmmy friiiennd" becomes "bye my friennd"). You may assume any
immediate following same letters are a triplicate.
I've mostly only seen examples for duplicates, so how do I remove triplicates? My code doesn't return anything when I run it.
def removeTriplicateLetters(i):
result = ''
for i in result:
if i not in result:
result.append(i)
return result
def main():
print(removeTriplicateLetters('byeee mmmy friiiennd'))
main()
I have generalized the scenario with "n". In your case, you can pass n=3 as below
def remove_n_plicates(input_string, n):
i=0
final_string = ''
if not input_string:
return final_string
while(True):
final_string += input_string[i]
if input_string[i:i+n] == input_string[i]*n:
i += n
else:
i += 1
if i >= len(input_string):
break
return final_string
input_string = "byeee mmmy friiiennd"
output_string = remove_n_plicates(input_string, 3)
print(output_string)
# bye my friennd
You can use this for any "n" value now (where n > 0 and n < length of input string)
Your code returns an empty string because that's exactly what you coded:
result = ''
for i in result:
...
return result
Since result is an empty string, you don't enter the loop at all.
If you did enter the loop you couldn't return anything:
for i in result:
if i not in result:
The if makes no sense: to get to that statement, i must be in result
Instead, do as #newbie showed you. Iterate through the string, looking at a 3-character slice. If the slice is equal to 3 copies of the first character, then you've identified a triplet.
if input_string[i:i+n] == input_string[i]*n:
Without going in to writing the code to resolve the problem.
When you iterate over the string, add that iteration to a new string.
If the next iteration is the same as the previous iteration then do not add that to the new string.
This will catch both the triple and the double characters in your problem.
Tweaked a previous answer to remove a few lines that were not needed.
def remove_n_plicates(input_string, n):
i=0
result = ''
while(True):
result += input_string[i]
if input_string[i:i+n] == input_string[i]*n:
i += n
else:
i += 1
if i >= len(input_string):
break
return result
input_string = "byeee mmmy friiiennd"
output_string = remove_n_plicates(input_string, 3)
print(output_string)
# bye my friennd
Here's a fun way using itertools.groupby:
def removeTriplicateLetters(s):
return ''.join(k*(l//3+l%3) for k,l in ((k,len(list(g))) for k, g in groupby(s)))
>>> removeTriplicateLetters('byeee mmmy friiiennd')
'bye my friennd'
just modifying #newbie solution and using stack data structure as solution
def remove_n_plicates(input_string, n):
if input_string =='' or n<1:
return None
w = ''
c = 0
if input_string!='':
tmp =[]
for i in range(len(input_string)):
if c==n:
w+=str(tmp[-1])
tmp=[]
c =0
if tmp==[]:
tmp.append(input_string[i])
c = 1
else:
if input_string[i]==tmp[-1]:
tmp.append(input_string[i])
c+=1
elif input_string[i]!=tmp[-1]:
w+=str(''.join(tmp))
tmp=[input_string[i]]
c = 1
w+=''.join(tmp)
return w
input_string = "byeee mmmy friiiennd nnnn"
output_string = remove_n_plicates(input_string, 3)
print(output_string)
output
bye my friennd nn
so this is a bit dirty but it's short and works
def removeTriplicateLetters(i):
result,string = i[:2],i[2:]
for k in string:
if result[-1]==k and result[-2]==k:
result=result[:-1]
else:
result+=k
return result
print(removeTriplicateLetters('byeee mmmy friiiennd'))
bye my friennd
You have already got a working solution. But here, I come with another way to achieve your goal.
def removeTriplicateLetters(sentence):
"""
:param sentence: The sentence to transform.
:param words: The words in the sentence.
:param new_words: The list of the final words of the new sentence.
"""
words = sentence.split(" ") # split the sentence into words
new_words = []
for word in words: # loop through words of the sentence
new_word = []
for char in word: # loop through characters in a word
position = word.index(char)
if word.count(char) >= 3:
new_word = [i for i in word if i != char]
new_word.insert(position, char)
new_words.append(''.join(new_word))
return ' '.join(new_words)
def main():
print(removeTriplicateLetters('byeee mmmy friiiennd'))
main()
Output: bye my friennd

Python Case Matching Input and Output

I'm doing the pig latin question that I'm sure everyone here is familiar with it. The only thing I can't seem to get is matching the case of the input and output. For example, when the user enters Latin, my code produces atinLay. I want it to produce Atinlay.
import string
punct = string.punctuation
punct += ' '
vowel = 'aeiouyAEIOUY'
consonant = 'bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ'
final_word = input("Please enter a single word. ")
first_letter = final_word[:1]
index = 0
if any((p in punct) for p in final_word):
print("You did not enter a single word!")
else:
while index < len(final_word) and (not final_word[index] in vowel):
index = index+1
if any((f in vowel) for f in first_letter):
print(final_word + 'yay')
elif index < len(final_word):
print(final_word[index:]+final_word[:index]+'ay')
What you need is str.title(). Once you have done your piglatin conversion, you can use title() built-in function to produce the desired output, like so:
>>> "atinLay".title()
'Atinlay'
To check if a string is lower case, you can use str.islower(). Take a peek at the docs.
simply use the built in string functions.
s = "Hello".lower()
s == "hello"
s = "hello".upper()
s == "HELLO"
s = "elloHay".title()
s == "Ellohay"

Storing multiple inputs in one variable

I have a while loop, which will keep asking a user to input words until they type stop. The input is stored in a variable called sentence.
My question is how do I store multiple inputs into one variable.
My current code is
stop = "stop"
sentence = []
while sentence != stop:
sentence = input("Enter a word: ")
sentence = sentence
print(sentence)
I don't understand how I would keep storing variables from one input and print out all the variable stored separated by commas/spaces etc
All you need to do is append() your new variables to the array:
>>> a = []
>>> for x in range(5):
... a.append("Hello!")
...
>>> a
['Hello!', 'Hello!', 'Hello!', 'Hello!', 'Hello!']
At the end, if you need everything in a single variable you can use join():
>>> ",".join(a)
'Hello!,Hello!,Hello!,Hello!,Hello!'
stop = "stop"
# okay --- 'sentence' is a list. Good start.
sentence = []
while sentence != stop:
# ...but now you've replaced the list 'sentence' with the word that was just input
# NOTE that in Python versions < 3, you should use raw_input below.
sentence = input("Enter a word: ")
# ...and this does nothing.
sentence = sentence
print(sentence)
Works better if you do something like this:
stop = "stop"
sentence = []
# create a new variable that just contains the most recent word.
word = ''
while word != stop:
word = input("Enter a word: ")
# stick the new word onto the end of the list
sentence.append(word)
print(sentence)
# ...and convert the list of words into a single string, each word
# separated by a space.
print " ".join(sentence)
...or to re-design a bit to omit the 'stop', something like:
stop = "stop"
sentence = []
while True:
word = input("Enter a word: ")
if word == stop:
# exit the loop
break
sentence.append(word)
# ...and convert the list of words into a single string, each word
# separated by a space.
print " ".join(sentence)
Its pretty simple
stop = "stop"
sentence = []
all = ""
while sentence != stop:
sentence = input("Enter a word: ")
all += sentence + ","
print(all)
One of your problems is that you are constantly writing over your sentence variable.
What you want to do is make use of the list append method. Documentation on lists:
https://docs.python.org/3/tutorial/datastructures.html
Example:
a = []
a.append(1)
a.append(2)
a.append(3)
print(a)
[1, 2, 3]
Next, you are looking to end your code if the user enters "stop". So what you should do is check in your loop if "stop" was written, and make use of Python's break, to break out of the loop.
What this means is that you should change your loop to loop indefinitely until you get that stop, using while True.
Your code can now simply look like this:
sentence = []
while True:
entry = input("Enter a word: ")
if entry == "stop":
break
sentence.append(entry)
print(sentence)
You probably want something like this:
sentence = []
while True:
word = input("Enter a word: ")
if word == "stop":
break
sentence.append(word)
print " ".join(sentence) + "."

How to format my string

def main():
print('Please enter a sentence without spaces and each word has ' + \
'a capital letter.')
sentence = input('Enter your sentence: ')
for ch in sentence:
if ch.isupper():
capital = ch
sentence = sentence.replace(capital, ' ' + capital)
main()
Ex: sentence = 'ExampleSentenceGoesHere'
I need this to print as: Example sentence goes here
as of right now, it prints as: Example Sentence Goes Here (with space at the beginning)
You can iterate over the string character by character and replace every upper case letter with a space and appropriate lower case letter:
>>> s = 'ExampleSentenceGoesHere'
>>> "".join(' ' + i.lower() if i.isupper() else i for i in s).strip().capitalize()
'Example sentence goes here'
Note that check if the string is in upper case is done by isupper(). Calling strip() and capitalize() just helps to deal with the first letter.
Also see relevant threads:
Elegant Python function to convert CamelCase to snake_case?
How to check if a character is upper-case in Python?
You need to convert the each uppercase letter to a lowercase one using capital.lower(). You should also ignore the first letter of the sentence so it stays capitalised and doesn't have a space first. You can do this using a flag as such:
is_first_letter = True
for ch in sentence:
if is_first_letter:
is_first_letter = False
continue
if ch.isupper():
capital = ch
sentence = sentence.replace(capital, ' ' + capital.lower())
I'd probably use re and re.split("[A-Z]", text) but I'm assuming you can't do that because this looks like homework. How about:
def main():
text = input(">>")
newtext = ""
for character in text:
if character.isupper():
ch = " " + character.lower()
else:
ch = character
newtext += ch
text = text[0]+newtext[2:]
You could also do:
transdict = {letter:" "+letter.lower() for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'}
transtable = str.maketrans(transdict)
text.translate(transtable).strip().capitalize()
But again I think that's outside the scope of the assignment

Categories

Resources