Prompt user until 5 unique vowels or consonants have been input - python

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'

Related

How to find the longest word in a string without using split method

I need an algorithm that can find the longest word in a string, I can't use split(), the only predefined function I can use is find() and I don't think it's useful for this solution.
This is what I managed to do so far:
ch=input("donner: ")
def plus_long(ch):
p=ch.find(" ")
if p==-1:
return ch
maximum=""
mot=""
while p!=-1:
mot=ch[:p]
print(mot)
ch=ch[p+1:]
print(ch)
if len(mot)>len(maximum):
maximum=mot
p=ch.find(" ")
return maximum
print("maximum est: ",plus_long(ch))
But this one doesn't check the last word because there are no more spaces.
EDIT: Thank you all for the answers, i realised how to solve it this morning by putting ch in a new variable and comparing it to maximum and it worked
ch=input("donner: ")
def plus_long(ch):
p=ch.find(" ")
if p==-1:
return ch
maximum=""
mot=""
while p!=-1:
mot=ch[:p]
print(mot)
ch=ch[p+1:len(ch)]
print(ch)
if len(mot)>len(maximum):
maximum=mot
p=ch.find(" ")
f=ch
if len(f)>len(maximum):
maximum=f
return maximum
print("maximum est: ",plus_long(ch))
I've split this problem into two parts:
Use find to create the list of words.
Find the longest word in the list.
def plus_long(ch):
letters = "abcdefghijklmnopqrstuvwxyz"
words = ['']
for v in ch:
if letters.find(v.lower()) != -1: # Use find to check if the character is part of the alphabet
words[-1] += v # If so, add that character to the last string in the list
else:
words.append('') # Else, start a new string
result = "" # Check which string is the longest
for word in words:
if len(word) > len(result):
result = word
return result
Test:
>>> plus_long("Hello!!!!!!!!!!! How are you? I am exhausted.")
Output:
'exhausted'
I see that the other answers don't put punctuation into account, so that using their functions, the result would be 'Hello!!!!!!!!!!!'.
You can find using split and len:
# Longest word
# Reading sentence from user
sentence = input("Enter sentence: ")
# Finding longest word
longest = max(sentence.split(), key=len)
# Displaying longest word
print("Longest word is: ", longest)
print("And its length is: ", len(longest))
The output is:
Enter sentence: Tongue tied and twisted just an earth bound misfit I
Longest word is: twisted
And its length is: 7
Here is your code with an addition that checks the last word (len) when p == -1 just as the loop is going to exit. This addition reported the correct max length if the last word is greater than maximum.
ch=input("donner: ")
def plus_long(ch):
p=ch.find(" ")
if p==-1:
return ch
maximum=""
mot=""
while p!=-1:
mot=ch[:p]
print(mot)
ch=ch[p+1:]
print(ch)
if len(mot)>len(maximum):
maximum=mot
p=ch.find(" ")
# 'ch' now has the last word in a sentence
# it needs to be checked against 'maximum'
if p == -1:
if len(ch) > len(maximum):
maximum = ch
return maximum
print("maximum est: ",plus_long(ch))
You can set p to None if the find method returns -1 so that ch[:p] would slice the rest of the string to get the last word:
def plus_long(ch):
maximum = ""
while True:
p = ch.find(" ")
if p == -1:
p = None
mot = ch[:p]
if len(mot) > len(maximum):
maximum = mot
if p is None:
break
ch = ch[p + 1:]
return maximum
Using find
def plus_long(ch):
longest = ""
i = 0
while i < len(ch):
n = ch.find(" ", i)
if n == -1:
n = len(ch)
if len(longest) < len(ch[i:n]):
longest = ch[i:n]
i = n+1
Test:
print (plus_long("there is a cat on a very big banana tree"))
print (plus_long("there is a cat on a mountain"))
print (plus_long("there"))
Output:
banana
mountain
there
ch=input("donner: ")
def plus_long(ch):
word = ''
maximum = ''
for letter in ch:
if letter == ' ':
if len(maximum) < len(word):
maximum = word
word = ''
else:
word += letter
return maximum
print("maximum est: ",plus_long(ch))
this is a very long and probably the worst method as far as Big 'O' Notation is concerned but it is a simple approach for beginners.
def longWord (sentence):
singleWord = ""
words = []
for letter in sentence:
if letter != " ":
singleWord += letter
else:
words += [singleWord]
singleWord = ""
words += [singleWord]
for i in range(len(words)-1):
biggestWord = ""
if len(words[i]) >= len(words[i+1]):
biggestWord += words[i]
else:
biggestWord += words[i+1]
print(words)
print(biggestWord)
longWord("This is a callback")
OUTPUT -
['This', 'is', 'a', 'callback']
callback
I know you already have a few answers. Here's a code with O(1)
ch=input("donner: ")
prev_pos = 0
max_word = ''
for i, sp in enumerate(ch):
if sp == ' ':
if len(ch[prev_pos:i]) > len(max_word): max_word = ch[prev_pos:i]
prev_pos = i+1
if len(ch[prev_pos:]) > len(max_word): max_word = ch[prev_pos:]
print ('longest word :', max_word, 'length :', len(max_word))
The output for this are:
donner: sentence
longest word : sentence length : 8
donner: this sentence
longest word : sentence length : 8
donner: this is a sentence
longest word : sentence length : 8
donner: this sentence is expectedly very lengthy
longest word : expectedly length : 10
donner: word is lengthy
longest word : lengthy length : 7
I wanted to give you an alternate approach as well. I have added comments for you to understand the code
ch=input("donner: ") #input the sentence
word = '' #capture each word in this variable
wd = [] #store all the words into this list
for sp in ch: #iterate thru the string
if sp != ' ': word += sp #concat to create the word
else:
wd.append(word) #add the word to list
word = '' #reset word
wd.append(word) #add the last word to the list
long_word = max(wd,key=len) #find the longest word
print ('longest word :',long_word, 'length :', len(long_word))

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)

List slicing issues in python

This code seems like it should work. It sums up the number of words that are "striped" (letter-consonant-letter-etc.) and then returns the sum. However when I test it with print (striped("My name is ...") ) it only counts my and is and gives me a sum of 2 instead of 3... why is name missing?
VOWELS = "AEIOUY"
CONSONANTS = "BCDFGHJKLMNPQRSTVWXZ"
def striped(text):
my_sum = 0
text = text.replace(".", " ").replace(",", " ").split()
vowels = VOWELS.lower()
consonants = CONSONANTS.lower()
for word in text:
word = word.lower()
if ((word[::2] in vowels and word[1::2] in consonants)\
or (word[::2] in consonants and word[1::2] in vowels))\
and len(word) > 1:
print (word)
my_sum += 1
return my_sum
Here is a solution with lists. The problem with your code is that words longer than two characters return a substring when you use [::2] rather than single characters that are tested whether they are contained in vowels / constants.
By converting it to a list first, you can check every item of the list whether it is contained in the according set of characters.
VOWELS = "AEIOUY"
CONSONANTS = "BCDFGHJKLMNPQRSTVWXZ"
def striped(text):
my_sum = 0
text = text.replace(".", " ").replace(",", " ").split()
vowels = VOWELS.lower()
consonants = CONSONANTS.lower()
for word in text:
word = word.lower()
if ((all(c in vowels for c in list(word[::2]))\
and all(c in consonants for c in list(word[1::2])))\
or (all(c in consonants for c in list(word[::2]))\
and all(c in vowels for c in list(word[1::2]))))\
and len(word) > 1:
print (word)
my_sum += 1
return my_sum
print striped("My name is")
You should use set.issubset() instead.
VOWELS = "AEIOUY"
CONSONANTS = "BCDFGHJKLMNPQRSTVWXZ"
def striped(text):
my_sum = 0
text = text.replace(".", " ").replace(",", " ").split()
vowels = set(c for c in VOWELS.lower())
consonants = set(c for c in CONSONANTS.lower())
for word in text:
word = word.lower()
if ((set(word[::2]).issubset(vowels) and set(word[1::2]).issubset(consonants))\
or (set(word[::2]).issubset(consonants) and set(word[1::2]).issubset(vowels)))\
and len(word) > 1:
print (word)
my_sum += 1
return my_sum
striped('My name is...')
The reason it works for my and is is that they are two char words, so you are checking if if m is in the string of constants, and if y is in the string of vowels, which works. For longer words like name, then clearly nm is not in the string of sonsonants, so it fails.
Instead, you should use sets. Essentially, you want to find if set(['n','m']) is a subset of the set of consonants.

How to get least occurring vowel in string?

I have this code that is supposed to print out the least occurring vowel when a word is entered, but it doesn't print out a vowel and the least value. Here is my code:
#Program to count the least occurring vowels
# take input from the user
w = input("Enter a word or sentence: ")
# string of vowels
vowel = 'aeiouAEIOU'
min_vowel = w[0]
min = w.count(w[0])
# make it suitable for caseless comparisions
w = w.casefold()
count = 0
# count the vowels
for char in w:
if vowel in w:
if w.count(vowel) < min:
min_vowel = w[0]
min = w.count(w)
print ("The least occuring vowel is",min_vowel,"with",min,"occurences.")
Please can anyone tell me where am going wrong?
If you want to be able to identify multiple vowels with the least occurences, I suggest using a different approach:
from collections import Counter
w = input("Enter a word or sentence: ")
vowel = "aeiouy"
# Count occurences of all vowels.
w = Counter(c for c in w.lower() if c in vowel)
# Get vowels with lowest occurences.
min_values = {k: w[k] for k in w if w[k] == min(w.values())}
# Print vowels.
print("The least occuring vowel is:")
for m in min_values:
print("{vowel} with {occ} occurences.".format(vowel=m, occ=min_values[m]))
Example:
>>> (...)
>>> Enter a word or sentence: Bananas are YUMMY!
The least occuring vowel is:
e with 1 occurences.
u with 1 occurences.

How to scramble the words in a sentence - Python

I have created the following code to scramble the letters in a word (except for the first and last letters), but how would one scramble the letters of the words in a sentence; given the input asks for a sentence instead of a word. Thank you for your time!
import random
def main():
word = input("Please enter a word: ")
print(scramble(word))
def scramble(word):
char1 = random.randint(1, len(word)-2)
char2 = random.randint(1, len(word)-2)
while char1 == char2:
char2 = random.randint(1, len(word)-2)
newWord = ""
for i in range(len(word)):
if i == char1:
newWord = newWord + word[char2]
elif i == char2:
newWord = newWord + word[char1]
else:
newWord = newWord + word[i]
return newWord
main()
May I suggest random.shuffle()?
def scramble(word):
foo = list(word)
random.shuffle(foo)
return ''.join(foo)
To scramble the order of words:
words = input.split()
random.shuffle(words)
new_sentence = ' '.join(words)
To scramble each word in a sentence, preserving the order:
new_sentence = ' '.join(scramble(word) for word in input.split())
If it's important to preserve the first and last letters as-is:
def scramble(word):
foo = list(word[1:-1])
random.shuffle(foo)
return word[0] + ''.join(foo) + word[-1]
Split the sentence into a list of words (and some punctuation) with the split method:
words = input().split()
and then do pretty much the same thing you were doing before, except with a list instead of a string.
word1 = random.randint(1, len(words)-2)
...
newWords = []
...
newWords.append(whatever)
There are more efficient ways to do the swap than what you're doing, though:
def swap_random_middle_words(sentence):
newsentence = list(sentence)
i, j = random.sample(xrange(1, len(sentence) - 1), 2)
newsentence[i], newsentence[j] = newsentence[j], newsentence[i]
return newsentence
If what you actually want to do is apply your one-word scramble to each word of a sentence, you can do that with a loop or list comprehension:
sentence = input().split()
scrambled_sentence = [scramble(word) for word in sentence]
If you want to completely randomize the order of the middle letters (or words), rather than just swapping two random letters (or words), the random.shuffle function is likely to be useful.

Categories