Python : the s language decoded using append - python

Input a sentence: Whasat doso yousou presefeser?
Output a sentence: What do you prefer?
At the moment only the p is changed by []. There are some mistakes with the code but I can not find it.
# input a sentence
text = input('Enter a text: ')
# create two variables
vowelgroup = []
decoded_text = []
vowel = 'aeiou'
# loop through all letters of sentence
for i in text:
if i != "vowel" and i != "s":
decoded_text.append(i)
if i == "vowel":
vowelgroup.append(i)
if i == "s":
decoded_text.append(vowelgroup)
# unlist the decoded tekst to string
L = ''.join(map(str, decoded_text))
print(L)

# input a sentence
text = input('Enter a text: ')
# create two variables
vowelgroup = []
decoded_text = []
vowel = 'aeiou'
# loop through all letters of sentence
container = False
for i in text:
if container:
container = False
continue
if i != "vowel" and i != "s":
decoded_text.append(i)
if i == "vowel":
vowelgroup.append(i)
if i == "s":
for j in vowelgroup:
decoded_text.append(j)
container = True
# unlist the decoded tekst to string
L = ''.join(map(str, decoded_text))
print(L)
Is this what you are aiming for? I don't get which among the letters beside an 's' will should be the trigger. In this case, once an 's' is scanned, the next character will automatically be skipped.

We iterate through the sentence letter by letter i. When the first letter i is not a vowel (a consonant) we store it in our decoded text variable. We repeat till when we encounter a vowel we save this vowel letter(s) in the vowel group till we encounter a 's' and we want to pass this vowelgroup to the decoded tekst instead of the 's'. Than we continue till we encounter again a non vowel (consonant) letter which will be added again to the decoded tekst and so on and on for each letter i.
text = input('Enter a text: ')
vowelgroup = []
decoded_text = []
vowel = 'aeiou'
for i in text:
if i != 'vowel':
decoded_text.append(i)
if i == 'vowel':
vowelgroup.append(i)
if i == 's':
decoded_text.append(vowelgroup)
L = ''.join(map(str, decoded_text))
print(L)

Related

I'm trying to perform some manual encoding of strings using python

Probelm Description:
sms_encoding() which accepts a sentence and converts it into an abbreviated sentence to be sent as SMS and returns the abbreviated sentence.
Rules are as follows:
a. Spaces are to be retained as is
b. Each word should be encoded separately
If a word has only vowels then retain the word as is
If a word has a consonant (at least 1) then retain only those consonants
My Code:
#PF-Assgn-50
def sms_encoding(data):
#start writing your code here
vowels=set("aeiouAEIOU")
v_list=[]
c_list=[]
final_list=[]
new_string=''
word=data.split()
word2=[]
for i in range(0,len(word)):
ch=word[i]
#print(ch)
if ch in vowels:
v_list.append(ch)
for letter in word[i]:
if letter not in vowels:
c_list.append(letter)
c_list.append(" ")
new_string=''.join(v_list)+''.join(c_list)
final_list.append(new_string)
#print(v_list)
return ' '.join(final_list)
data="Have a Nice Day"
print(sms_encoding(data))
My Output:
aHv **<2spaces>** Nc **<1space>** Dy
Expected Output:
Hv a Nc Dy (contains only 1 space)
You could iterate over words in the sentence taking only consonants only if the word contains atleast one consonant:
data = "Have a Nice Day"
splitted = data.split()
for i, x in enumerate(splitted):
if not all(y in 'aeiou' for y in x.lower()):
splitted[i] = ''.join([y for y in x if y.lower() not in 'aeiou'])
print(' '.join(splitted))
# Hv a Nc Dy
This will work for all cases... retains all except vowels when even 1 character in a string is not vowel.
def sms_encoding(data):
vowels = set("aeiouAEIOU")
words = data.split()
encoded_words = []
for i in range(0,len(words)):
vow_count = 0
cons_word = []
for x in words[i]:
if x in vowels:
vow_count =vow_count+1
elif x not in vowels:
cons_word.append(x)
if vow_count == len(words[i]):
encoded_words.append(words[i])
elif vow_count != len(words[i]):
encoded_words.append("".join(cons_word))
encoded_msg = " ".join(encoded_words)
return encoded_msg
data=input("Kindly enter your message for sms encoding : ")
print(sms_encoding(data))
Try and let me know!
def sms_encoding(data):
vowel = "aeiouAEIOU"
list1 = data.split()
list2 = []
for i in list1:
length=len(i)
if length == 1:
list2.append(i)
list2.append(" ")#to add spaces between the words
else:
count=0
for a in i:
if a in vowel:
count+=1
if count==length: #to check if all the letters are vowels
list2.append(i)
list2.append(" ")
for a in i:
if a not in vowel:
list2.append(a)
list2.append(" ")
list2.pop() #to remove the extra space at the end of the whole sentence
q="".join(list2)
return q
data = "I love Python aeio"
print(sms_encoding(data))
try this code it will work the question is from infytq
def sms_encoding(data):
data=data.lower()
a=data.split()
v1=""
for i in range(0,len(a)):
z=a[i]
v=""
c1=0
for j in z:
if j not in ('a','e','i','o','u'):
v=v+j
elif j in ('a','e','i','o','u'):
c1=c1+1
if(c1!=len(z)):
v1=v1+v+" "
elif(c1==len(z)):
v1=v1+z+" "
word=v1[0:len(v1)-1]
return word
data="I love Python"
print(sms_encoding(data))
def sms_encoding(new_s):
encrypt_string = []
consonant_list = []
vowel_set = set("aeiouAEIOU")
for word in range(0, len(new_s)):
v_letter = new_s[word]
if v_letter in vowel_set:
encrypt_string.append(v_letter)
for letter in v_letter:
if letter not in vowel_set:
consonant = " ".join(letter)
encrypt_string.append(consonant)
encrypt_string.append(" ")
encrypt_string = "".join(encrypt_string)
print(encrypt_string)
s = input("Enter a string ")
new_s = s.split()
sms_encoding(new_s)

Python : how to decode the text in s-language (strings)

Input exists out of a sentence or text in s-language: Isis thasat yousour sisisteser?
Output exists out same sentence without s-language : Is that your sister?
Problems:
I have the following code but some things are not working. For example I can not append after the if statements and my if statements are too litteral. Also the print(decoded_tekst) is not working.
Method:
I iterate through the different positions of the text with two variables ("vowelgroup" to store the vowels and "decoded text" to store the consonant and if "s" to replace it by the vowelgroup).
text = input('Enter a text: ')
vowelgroup = []
decoded_text = []
sentence = []
vowel = 'aeiou'
count = 0
for i in text:
if i is not vowel and not "s":
sentence = decoded_text.append(i)
if i is vowel:
vowelgroup = vowelgroup.append(vowel)
if i is "s":
decoded_text = sentence.append(vowelgroup)
count += 1
print(decoded_text)
You look a little confused about how append works. append just adds the argument to the end of the list and it returns None. E.g:
l = [1,2]
a = l.append(3)
print a # None
print l # [1,2,3]
So you just use it like:
l = [1,2]
l.append(3)
print l # [1,2,3]

Prompt user until 5 unique vowels or consonants have been input

The purpose of the code is best explained below, for example if I were to enter 'hello' then 'luck' then 'liar' the proper outputs should be '5' 'eouia' 3' and 'ckr'. When I do this however it keeps prompting me for more inputs after entering 'liar'.
###########################################################
# Algorithm
# Ask for a word
# Count and store all vowels in the words (repeats only are
# counted once)
# count and store only consonants after the last vowel, if the
# if last letter is a vowel no consonants are stored
# once all 5 vowels are stored or at least 5 consonants are
# stored
# print
# what vowels appear and how many
# what consonants appear
###########################################################
VOWELS = 'aeiou'
word = input('Input a word: ')
wordlow = word.lower() #converts the input to all lowercase
vowcount = 0
concount = 0
vowcollected_str = ''
concollected_str = ''
#ends the program once 5 vowels or consonants have been stored
while vowcount <= 4 and concount <= 4:
vowcount = 0
concount = 0
#stores the actual letter that is being stored, not just how many
vowcollected_str = ''
concollected_str = ''
for i, ch in enumerate(wordlow):
if ch in VOWELS:
if ch not in vowcollected_str:
vowcollected_str += ch
position = i
vowcount += len(vowcollected_str)
if ch not in VOWELS:
if ch not in concollected_str:
concollected_str += wordlow[i:]
concount += len(word[i:])
word = input('Input a word: ')
wordlow = word.lower()
print(vowcount)
print(vowcollected_str)
print(concount)
print(concollected_str)
I'd keep a set of the all the required vowels and subtract all the letters you input until the set is empty:
VOWELS = 'aeiou'
vowelsSoFar = set(VOWELS)
while vowelsSoFar:
word = input('enter a word: ')
vowelsSoFar -= set(word)
# Feel free to print out the remains vowels, for example
You can use list comprehensions to get the vowels and return the len.
Code
import itertools as it
words = 'hello', 'luck', 'liar'
seen_vowels = "".join(c for w in words for c in w if c in "aeiou")
seen_vowels
# 'eouia'
len(seen_vowels)
# 5
Trailing consonants could be found via takewhile of each reversed word.
trailing_cons = "".join("".join(it.takewhile(lambda x: x not in "aeiou", w[::-1]))[::-1] for w in words)
trailing_cons
# 'ckr'
Details
Note, takewhile grabs all consonants before the first observed vowel. By reversing each word, we get the trailing consonants.
"".join(it.takewhile(lambda x: x not in "aeiou", "luck"[::-1]))
# 'kc'

Pig Latin Python program

I've been working on a Pig Latin program. However, it doesn't seem to be working and I can't figure out why.
user_input = input("Enter word to be translated:")
def translate(user_input):
first = user_input[0]
if first == "a" or "e" or "i" or "o" or "u":
user_input = user_input.lower()
user_input += "way"
return user_input
else:
user_input = user_input.lower()
user_input = user_input[1:]+first+"ay"
return user_input
print(translate(user_input))
On top of that, I was looking to utilize enumerate to find the position of the first vowel, slicing to isolate the first letter of the word and concatenation to form the word. I've read up on how to use it on a couple websites but I can't seem to figure out how to correctly apply it to this program. I think I would have to define Vowels = 'aeiou' before def translate(user_input) right??
You cannot chain if statements like that in Python, you have to do it the long way:
if first == "a" or first == "e" or first == "i" or first == "u":
or shorten it to:
if first in ["a", "e", "i", "u"]:
Here is the solution. I've made a few changes in your code which i will be explaining below.
user_input = input("Enter word to be translated:\n")
#change_1
vowels = ['a','e','i','o','u']
def translate(user_input):
first = user_input[0]
#change_2
if first in vowels:
user_input = user_input.lower()
user_input += "way"
return user_input
else:
user_input = user_input.lower()
#change_3
for letter in user_input:
if letter in vowels:
index_value = user_input.index(letter)
break
#change_4
user_input = user_input[index_value:] +user_input[:index_value]+ "ay"
return user_input
print(translate(user_input))
1) Create a list of vowels.
2) As our friend #zwer mentioned You cannot chain if statements like that in
Python. So
if first in vowels:
3) For every letter in user_input check if that letter is a vowel and if that letter is a vowel then find the index of it's occurrence.
For example take the word 'trash'
Here a is the first vowel and it's index is 2
if letter in vowels:
index_value = user_input.index(letter)
4) According to wikipedia
"all letters before the initial vowel are placed at the end of the word sequence"
For the word 'trash' it would be
user_string = user_input[2:] + user_input[:2]+"ay"
which would be slicing the word from that index to end, merged with letters before that index. And finally an "ay".
'ash' + 'tr' + 'ay'
Hope this helps.
You can define vowels in the outer scope.
vowels = 'a', 'e', 'i', 'o', 'u'
Then anywhere you can use:
if first in vowels:
My Solution covers the below rules:
1. A word is a consecutive sequence of letters (a-z, A-Z) or apostrophes. You may assume that the input to the function will only be a single "word". Examples: Zebra , apple
2. If a word starts with a vowel, the Pig Latin version is the original word with "way" added to the end
3. If a word starts with a consonant, or a series of consecutive consonants, the Pig Latin version transfers ALL consonants up to the first vowel to the end of the word, and adds "ay" to the end.
4. The letter 'y' should be treated as a consonant if it is the first letter of a word, but treated as a vowel otherwise.
5. If the original word is capitalized, the new Pig Latin version of the word should be capitalized in the first letter. If the original capital letter was a consonant, and thus moved, it should not be capitalized once in its new location.
Solution Starts here:
eng_to_pig_latin = {"football": "ootballfay", "Pittsburgh":"Ittsburghpay",
"Apple":"Appleway","oink":"oinkway",
"ontology":"ontologyway","yellow":"ellowyay","yttrium":"iumyttray"}
eng_word = 'yttrium'
vowels = 'aeiou'
def pig_latin(eng_word):
sub,str1 = [],''
first = eng_word[0]
second = eng_word[1]
# Rule 2
if first.lower() in vowels:
piglatin = eng_word +'way'
# Rule 3
elif first.lower() == first and second.lower() in vowels:
piglatin = eng_word[1:]+first+'ay'
elif first.lower()+second.lower() not in vowels:
# Rule 3 & 4
for l in eng_word:
if l not in vowels:
sub.append(l)
else:
str1 = eng_word[eng_word.index(l):]
break
str2 = ''.join(sub)
piglatin = str1+str2+'ay'
else:
# Rule 5
piglatin = eng_word[1:].capitalize()+first.lower()+'ay'
print(f'Test word is {eng_word} and its equivalent piglatin word is
{piglatin}. Comparison with mapping dictionary is
{eng_to_pig_latin[eng_word] == piglatin}')
pig_latin(eng_word)
Note: The dictionary uses is only to cross-check if the results are as expected, which I am doing in the last print statement.
my logic to translate given word in to Pig Latin translation
vowels=['a','e','i','o','u']
def igpay(name):
a_list=list(name)
if a_list[0] in vowels:
print("First letter is a Vowel")
apnd_letters="way"
else:
print("First letter is a Consonant")
a_list.append(a_list[0])
a_list.pop(0)
apnd_letters="ay"
print("Pig transaltion is {0}".format("".join(a_list)+str(apnd_letters)))
Output:
igpay("pig")
First letter is a Consonant
Pig transaltion is igpay
igpay("apple")
First letter is a Vowel
Pig transaltion is appleway
You can do it exactly the same as you are doing it except you will need to change the second line in translate:
if first == "a" or "e" or "i" or "o" or "u":
to:
if first == "a" or first == "e" or first == "i" or first == "o" or first == "u":
or:
if first in 'aeiou':
If you want to be able to use capital letters however, I would recommend changing first to first.lower().
This becomes:
user_input = input("Enter word to be translated:")
def translate(user_input):
first = user_input[0]
if first.lower() in 'aeiou':
user_input = user_input.lower()
user_input += "way"
return user_input
else:
user_input = user_input.lower()
user_input = user_input[1:]+first+"ay"
return user_input
print(translate(user_input))
If you want the code a bit shorter, I have managed to shorten it to:
def translate():
user_input = input('Enter a word or sentence')
for i in range(len(user_input.split())): print(str((user_input.split())[i][1::])+((user_input.split())[i])[0]+'ay', end=' ')
translate()
Here is another two ways to go about it
Method 1:
Using a function that recursively translates words
sentence = str(input('Input Sentence: '))
vowels = 'aeiouAEIOU'
# 1. strip removes whitespace before and after input
# 2. pig_word_latin deals with one word at a time
# 3. join collects all the words into one sentence with spaces
def pig_latin_word(word):
vowelStart = True
#print(word)
if word[0] not in vowels:
vowelStart = False
return pig_latin_word(word[1:] + word[:1])
elif word[0] in vowels and not vowelStart:
return word + 'ay'
elif word[0] in vowels and vowelStart:
return word + 'way'
def pig_latin(sentence):
words: list = sentence.strip().split(' ')
new_words = []
for word in words:
new_words.append(pig_latin_word(word))
print(" ".join(new_words))
pig_latin(sentence)
Method 2:
Using a function that recursively translates sentences by keeping track of spaces
sentence = str(input('Input Sentence: ')).strip()
vowels = 'aeiouAEIOU'
suffix = {}
suffix[True] = 'way'
suffix[False] = 'ay'
def pig_latin(sentence, acc='', cluster='', word=''):
#print('S:'+sentence, 'C:'+cluster, 'W:'+word)
#print('Acc:',acc)
new_word = len(word)==0
vowel_start= len(cluster)==0
#print('NW:',new_word, suffix[vowel_start])
#print('-')
if len(sentence) == 0:
return acc+word+cluster+suffix[vowel_start]
if sentence[0] == ' ':
return pig_latin(sentence[1:], acc+word+cluster+suffix[vowel_start]+' ')
if new_word == True:
if sentence[0] not in vowels:
#print('1---')
return pig_latin(sentence[1:], acc, cluster+sentence[0], '')
elif sentence[0] in vowels and not vowel_start:
#print('2---')
return pig_latin(sentence[1:], acc, cluster, word+sentence[0])
elif sentence[0] in vowels and vowel_start:
#print('3---')
return pig_latin(sentence[1:], acc, '', word+sentence[0])
else:
return pig_latin(sentence[1:], acc, cluster, word+sentence[0])
print(pig_latin(sentence))

If the last word in 's' starts with a consonant, it will say index out of range. How do I change the program to change that?

def to_pig_latin(s):
j = 0 # points to first character in word
i = 0
new_sentence_1 = '' # variable to store strings being changed
vowel_position = 0 # show the position of the first vowel
number_of_words = 0
number_of_spaces = s.count(" ")
number_of_words = number_of_spaces + 1
space_position = s.find(" ") # find the position of the first space
sent = s[:space_position] # slice the first word of the sentence
old_sent = s[len(sent)+1:] # stores the old sentence without the first word of s
while number_of_spaces >= 0:
if sent[j] in ["a", "e", "i", "o", "u"]: # checks if first character is a vowel
new_sentence = sent + "way" # adds 'way' to the first word
new_sentence_1 = new_sentence_1 + ' ' + new_sentence # adds the words
else: # if first character is not equal to a vowel
for i in range(len(sent)):
# check to see if first character in s is a vowel
if s[i] == 'a':
break
if s[i] == 'e':
break
if s[i] == 'i':
break
if s[i] == 'o':
break
if s[i] == 'u':
break
vowel_position = i # takes position of first vowel reached in word
consonant_sequence = sent[:vowel_position] # stores all the consonants up to the first vowel, but not the first vowel
sent = sent[vowel_position:] # slices the word from the first vowel to the end
new_sentence = sent + 'a' + consonant_sequence + 'ay' # adds strings
new_sentence_1 = new_sentence_1 + ' ' + new_sentence # adds the words
s = old_sent # takes the value of old_sent
space_position = s.find(" ") # find the position of the first space
How do I change the part below in order to for it to check even if there is one word in s? Or if the last word in the string s ends with a word that begins with one or more consonant?
if space_position == -1:
space_position = len(s)
sent = s[:space_position]
if sent[j] in ["a", "e", "i", "o", "u"]:
new_sentence = sent + "way"
new_sentence_1 = new_sentence_1 + ' ' + new_sentence
break
else:
for i in range(len(sent)):
if s[i] == 'a':
break
if s[i] == 'e':
break
if s[i] == 'i':
break
if s[i] == 'o':
break
if s[i] == 'u':
break
vowel_position = i
consonant_sequence = sent[:vowel_position]
sent = sent[vowel_position:]
new_sentence = sent + 'a' + consonant_sequence + 'ay'
new_sentence_1 = new_sentence_1 + ' ' + new_sentence
sent = s[:space_position]
old_sent = s[len(sent)+1:]
number_of_spaces = s.count(" ")
number_of_words = number_of_spaces + 1
return new_sentence_1[1:]
test program for english/piglatin translator:
import piglatin
choice = input ("(E)nglish or (P)ig Latin?\n")
action = choice[:1]
if action == 'E':
s = input("Enter an English sentence:\n")
new_s = piglatin.to_pig_latin(s)
print("Pig-Latin:")
print(new_s)
elif action =='P':
s = input("Enter a Pig Latin sentence:\n")
new_s = piglatin.to_english(s)
print("English:")
print(new_s)
Output:
(E)nglish or (P)ig Latin? E
Enter an English sentence: My friend next to me is wearing a shoe
Traceback (most recent call last):
File "/Applications/Wing101.app/Contents/Resources/src/debug/tserver/_sandbox.py",
line 9, in <module>
File "/Users/azhar/Desktop/Computer Science/Assignments/Assignment 4 (Functions & Strings)/piglatin.py", line 46, in to_pig_latin
if sent[j] in ["a", "e", "i", "o", "u"]: # checks if first value in j is equal to a vowel
builtins.IndexError: string index out of range
I think, rather than fixing that specific problem, it would be easier to simplify the code.
First, you can split the sentence with s.split(), which will give you a list of words split on whitespace. Second, you can use s.find() to find the index of a given string. Third, you can use ' '.join(sen) to join a list of strings using spaces.
So using these, your code reduces to this (I also added handling of capitalization):
def to_pig_latin(sen):
senlst = sen.lower().split() # split into list of words
for i, word in enumerate(senlst):
if word[0] in 'aeiou':
senlst[i] += 'way'
else:
for vow in 'aeiou':
ind = word.find(vow)
if ind >= 0:
break
if ind < 0: # no vowel in word
continue
senlst[i] = word[ind:]+'a'+word[:ind]
newsen = ' '.join(senlst) # combine list of words into sentence
if sen[0].isupper(): # make capitalization like original
newsen = newsen.capitalize()
return newsen
However, if you really want to check if there is a word at all, you can do if s.strip():. What this will do is strip out and leading or trailing whitespace. If there are no words, this will leave you with an empty string. In python, an empty string (or empty list or tuple) is considered False, so you can use it in an if test to then do whatever sort of handling of that situation you want.

Categories