python i need to not repeated words in a while loop - python

I need not to get the words again once its displayed using random.choice,
this is the problem it shouldnt repeated words because the words have been already used
I tried to delete the word using list.remove but It doesn't work and i didn't get any results
import random
a = ["hello", "carls", "theme", "threw", "folks", "dime", "blondie", "ocean"]
c = True
while c:
c = input("")
filtered_list = []
for word in a:
if c.upper() in word:
filtered_list.append(word)
if len(filtered_list) > 0:
words = random.choice(filtered_list)
print(words)
else:
print(f"there are any words with {c} or all the words have been used")

i'm not sure the original message of the example to solve; but i tried this
#!/usr/bin/python3
import random
a = ["hello", "carls", "theme", "threw", "folks", "dime", "blondie", "ocean"]
c = True
while c:
c = input("")
print("a ", a)
filtered_list = []
for word in a:
if c.lower() in word:
a.remove(word)
filtered_list.append(word)
if len(filtered_list) > 0:
words = random.choice(filtered_list)
print(words)
else:
print(f"there are any words with {c} or all the words have been used")

Use another list for used words:
from random import choice
a = ["hello", "carls", "theme", "threw", "folks", "dime", "blondie", "ocean"]
used = []
while c := input('').lower():
filtered_list = [word for word in a if c in word and word not in used]
if filtered_list: used += [words := choice(filtered_list)]; print(words)
else: print(f'there are any words with {c} or all the words have been used'); # used = []
Output:
e
ocean
e
blondie
e
threw
e
dime
e
theme
e
hello
e
there are any words with e or all the words have been used
You might also need to reset used list to empty list after reach else statement for different search input of another character or letter.

You should start by creating a new normalised list because this code is destructive. In the question, the list contains all lowercase words but it's better to generalise
Then:
from random import choice
a = ["hello", "carls", "theme", "threw", "folks", "dime", "blondie", "ocean"]
acopy = [word.lower() for word in a]
while acopy:
if (c := input('Enter a single character: ').lower()) == '?':
print(acopy)
elif len(c) == 1:
if possibles := [i for i, word in enumerate(acopy) if c in word]:
print(acopy.pop(choice(possibles)))
else:
print(f'There are no words containing {c}')
As written, the while loop will only terminate when the acopy list is empty. You might want to do something else such as empty input.
Bonus: Enter ? to see what's remaining in the list

If i understand your problem correctly, your requirement is once the word displayed, it will not displayed again. So delete the word from the list a once you get the value from random.choice , so that you won't get the word again or maintain another list which holds the value already shown
import random
a = ["hello", "carls", "theme", "threw", "folks", "dime", "blondie", "ocean"]
already_show = []
c = True
while c:
c = input("Enter Letter to search:")
filtered_list = []
for word in a:
if c in word:
filtered_list.append(word)
if len(filtered_list) > 0:
words = random.choice(filtered_list)
if words not in already_show:
already_show.append(words)
print(words)
else:
print("random.choice selected the already selected word")
already_show = [] #Reset for another search
else:
print(f"there are any words with {c} or all the words have been used")

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)

Comparing a value to multiple values in a list

I am having an issue with this code:
words = []
counter = 0
wordcount = 0
intraWord = 1
loop = 0
ConsonantCluster3 = ["sch" "scr", "shr", "sph", "spl", "spr", "squ", "str", "thr"]
while(loop == 0):
sentence = input('Enter a sentence in english: ')
sentence.lower()
words = sentence.split()
for x in range(0,intraWord):
if(words[counter][:3] in ConsonantCluster3):
print("True")
input()
else:
print("False")
input()
My goal is if, for example, the user inputs "screen" the program would spit out True, but instead it is spitting out False. I am using Python 3.
Here is one way.
ConsonantCluster3 = {"sch", "scr", "shr", "sph", "spl", "spr", "squ", "str", "thr"}
sentence = input('Enter a sentence in english: ')
words = sentence.lower().split()
for x in words:
if x[:3] in ConsonantCluster3:
print("True")
else:
print("False")
Explanation
Many of your variables and a loop are not necessary.
Your list is missing , after the first element.
You can loop through a list simply via for x in lst.
str.lower() is not in-place. Assign to a variable.
You can also make use of list comprehension to combine the conditions to make the code simpler:
ConsonantCluster3 = {"sch", "scr", "shr", "sph", "spl", "spr", "squ", "str", "thr"}
sentence = input('Enter a sentence in english: ')
words = sentence.lower().split()
if len([x for x in words if x[:3] in ConsonantCluster3]) > 0:
print("True")
else:
print("False")

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]

Print only vowels in a string

I am new in Python and I'm trying to print all the vowels in a string. So if someone enters "Hey there, everything alright?" , all vowels needs to be printed...but I don't know how? (so it's not about counting the vowels, its about printing the vowels)
For now I've got this ;
sentence = input('Enter your sentence: ' )
if 'a,e,i,o,u' in sentence:
print(???)
else:
print("empty")
Something like this?
sentence = input('Enter your sentence: ' )
for letter in sentence:
if letter in 'aeiou':
print(letter)
The two answers are good if you want to print all the occurrences of the vowels in the sentence -- so "Hello World" would print 'o' twice, etc.
If you only care about distinct vowels, you can instead loop over the vowels. In a sense, you're flipping the code suggested by the other answers:
sentence = input('Enter your sentence: ')
for vowel in 'aeiou':
if vowel in sentence:
print(vowel)
So, "Hey there, everything alright?" would print
a e i
As opposed to:
e e e e e i a i
And the same idea, but following Jim's method of unpacking a list comprehension to print:
print(*[v for v in 'aeiou' if v in sentence])
Supply provide an a list comprehension to print and unpack it:
>>> s = "Hey there, everything allright?" # received from input
>>> print(*[i for i in s if i in 'aeiou'])
e e e e e i a i
This makes a list of all vowels and supplies it as positional arguments to the print call by unpacking *.
If you need distinct vowels, just supply a set comprehension:
print(*{i for i in s if i in 'aeiou'}) # prints i e a
If you need to add the else clause that prints, pre-construct the list and act on it according to if it's empty or not:
r = [i for i in s if i in 'aeiou']
if r:
print(*r)
else:
print("empty")
You could always use RegEx:
import re
sentence = input("Enter your sentence: ")
vowels = re.findall("[aeiou]",sentence.lower())
if len(vowels) == 0:
for i in vowels:
print(i)
else:
print("Empty")
You can always do this:
vowels = ['a', 'e', 'i', 'o', 'u', 'y']
characters_input = input('Type a sentence: ')
input_list = list(characters_input)
vowels_list = []
for x in input_list:
if x.lower() in vowels:
vowels_list.append(x)
vowels_string = ''.join(vowels_list)
print(vowels_string)
(I am also a beginner btw)

Matching input letters with a dictionary in Python

I'm trying to make a program that will read in words from a .txt file and having the user input letters of own choosing, and the program will give print out all the matches.
This is what I got so far:
fil = open("example.txt", "r")
words = fil.readlines()
letters = raw_input("Type in letters: ")
compare = set(letters)
lista = []
for a_line in words:
a_line = a_line.strip()
lineword = set(a_line)
if compare >= lineword:
lista.append(rad)
print lista
Now this works only to a certain degree. It does match the user input with the content of the .txt file, but I want it to be more precise. For example:
If I put in "hrose" it will find me "horse", but it will also find me "roses" with two s, since it only compares elements and not amount
How can I make the program to only use the specified letters?
You can use Counter:
from collections import Counter
def compare(query, word):
query_count = Counter(query)
word_count = Counter(word)
return all([query_count[char] >= word_count[char] for char in word])
>>> compare("hrose", "rose")
True
>>> compare("hrose", "roses")
False
Counters are your friend
from collections import Counter
fil = open("example.txt", "r")
words = [(a.strip(), Counter(a.strip())) for a in fil.readlines()]
letters = raw_input("Type in letters: ")
letter_count = Counter(letters)
word_list = []
for word, word_count in words:
if all([letter_count[char] >= word_count[char] for char in word]):
word_list.append(word)
print word_list
looking at the comments, it's possible you may only want exact matches, if so, you don't even need a counter
fil = open("example.txt", "r")
words = [(a.strip(), sorted(a.strip())) for a in fil.readlines()]
letters = sorted(raw_input("Type in letters: "))
word_list = [word for word, sorted_word in words if letters == sorted_word]
print word_list
you can map a mapping dictionary with key as the letters in the word and value being how many times it occurs in that word.
Now just compare two dictionaries.
fil = open("example.txt", "r")
words = fil.readlines()
letters = raw_input("Type in letters: ")
compare = list(letters)
letter_dict = {}
for letter in compare:
try:
letter_dict[letter] += 1
except KeyError:
letter_dict[letter] = 0
lista = []
for a_line in words:
a_line = a_line.strip()
lineword = list(a_line)
word_dict = {}
for letter in lineword:
try:
word_dict[letter] += 1
except KeyError:
word_dict[letter] = 0
flag = True
for key, value in letter_dict.items():
if key not in word_dict or word_dict[key] < value:
flag = False
break;
if flag:
lista.append(a_line)
print lista
one approach you could follow is to use set fundtions:
either use issubset/issuperset
set("horse").issubset(set("hrose")) #returs True
set("horse").issubset(set("roses")) #returns False
or
set("horse").difference(set("hrose")) #returns empty set based on set length you know close call
set("horse").difference(set("roses")) #returns set(['h'])
In the second approach, if you have the choice to choose among multiple options, you could go for result with small length.

Categories