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")
Related
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")
I'm trying to make a program that will convert any text into a different form. That means that a text such as 'hi there' becomes 'hI tHeRe'.
list = []
word = input('Enter in a word or a sentence! ')
for num in range(len(word)):
list.clear()
list.append('i')
letter = word[num]
for x in range(len(list)):
if x % 2 == 0:
i = word.index(letter)
place = letter.lower()
word = word.replace(word[i], place)
if not x % 2 == 0:
i = word.index(letter)
place = letter.upper()
word = word.replace(word[i], place)
print(word)
However, when I run the code it just prints the same string as normal.
When using replace, you have to assign the result to your variable:
word = word.replace(word[i], place)
However, replace is actually not what you want here. replace replaces all instances of a certain pattern with a new string. In your current code, every instance of whatever letter word[i] represents will be replaced with the result of .lower() or .upper().
You also don't want to use the word list, since doing so will shadow the Python built-in list class.
If you want to keep most of your original logic, you can follow #khelwood's suggestion in the comments and end up with the following:
word = input('Enter in a word or a sentence! ')
wordList = list(word)
for i in range(len(word)):
if i % 2 == 0:
wordList[i] = word[i].lower()
else:
wordList[i] = word[i].upper()
print(''.join(wordList))
Here is one of my previous codes, you can change all the variable names to whatever you see fit.
s = input('Enter in a word or string.')
ret = ""
i = True # capitalize
for char in s:
if i:
ret += char.upper()
else:
ret += char.lower()
if char != ' ':
i = not i
print(ret)
I hope it works for you.
Try this one liner -
a = 'hi there'
''.join([i[1].lower() if i[0]%2==0 else i[1].upper() for i in enumerate(a)])
'hI ThErE'
If you care about each word starting from lowercase then this nested list comprehension works -
' '.join([''.join([j[1].lower() if j[0]%2==0 else j[1].upper() for j in enumerate(i)]) for i in a.split()])
'hI tHeRe'
The problem is with list.clear in the beginning of the for loop.
Each iteration you clear the list so the second for iteration run on the first item only.
Remove list.clear and it should scan the input word
Apologies for the bad formatting, it is my first post.
I'm currently trying to return a list of words that begin with vowels from a given list, yet it is returning nothing. Is there a possibility for assistance?
x = ["A","B","C","D","E","F",]
wordList = []
for i in x:
if i[0].lower() == ['a','e','i','o','u']:
wordList.append(i)
return wordList
Another way to do it:
x = ["A","B","C","D","E","F",]
wordList = [ i for i in x if i.lower().startswith(('a','e','i','o','u')) ]
x = ["A","B","C","D","E","F",]
wordList = []
for i in x:
if i.lower() in ['a','e','i','o','u']:
wordList.append(i)
return wordList
try this.you will get letters that are vowels. for words beginning with vowels you can do the following.
x = ["A","B","C","D","E","F",]
wordList = []
for i in x:
if i[0].lower() in ['a','e','i','o','u']:
wordList.append(i)
return wordList
do up vote if liked.
So, here is what I got:
def getSentence():
sentence = input("What is your sentence? ").upper()
if sentence == "":
print("You haven't entered a sentence. Please re-enter a sentence.")
getSentence()
elif sentence.isdigit():
print("You have entered numbers. Please re-enter a sentence.")
getSentence()
else:
import string
for c in string.punctuation:
sentence = sentence.replace(c,"")
return sentence
def list(sentence):
words = []
for word in sentence.split():
if not word in words:
words.append(word)
print(words)
def replace(words,sentence):
position = []
for word in sentence:
if word == words[word]:
position.append(i+1)
print(position)
sentence = getSentence()
list = list(sentence)
replace = replace(words,sentence)
I have only managed to get this far, my full intention is to take the sentence, seperate into words, change each word into a number e.g.
words = ["Hello","world","world","said","hello"]
And make it so that each word has a number:
So lets say that "hello" has the value of 1, the sentence would be '1 world world said 1'
And if world was 2, it would be '1 2 2 said 1'
Finally, if "said" was 3, it would be '1 2 2 1 2'
Any help would be greatly appreciated, I will then develop this code so that the sentence and such is stored into a file using file.write() and file.read() etc
Thanks
If you want just the position in which each word is you can do
positions = map(words.index,words)
Also, NEVER use built-in function names for your variables or functions. And also never call your variables the same as your functions (replace = replace(...)), functions are objects
Edit: In python 3 you must convert the iterator that map returns to a list
positions = list(map(words.index, words))
Or use a comprehension list
positions = [words.index(w) for w in words]
Does it matter what order the words are turned into numbers? Is Hello and hello two words or one? Why not something like:
import string
sentence = input() # user input here
sentence.translate(str.maketrans('', '', string.punctuation))
# strip out punctuation
replacements = {ch: str(idx) for idx, ch in enumerate(set(sentence.split()))}
# builds {"hello": 0, "world": 1, "said": 2} or etc
result = ' '.join(replacements.get(word, word) for word in sentence.split())
# join back with the replacements
Another idea (although don't think it's better than the rest), use dictionaries:
dictionary = dict()
for word in words:
if word not in dictionary:
dictionary[word] = len(dictionary)+1
Also, on your code, when you're calling "getSentence" inside "getSentence", you should return its return value:
if sentence == "":
print("You haven't entered a sentence. Please re-enter a sentence.")
return getSentence()
elif sentence.isdigit():
print("You have entered numbers. Please re-enter a sentence.")
return getSentence()
else:
...
Whenever I run this code it just gives me a blank list, I am wondering what I am doing wrong. I am trying to print a list of words that are longer than n. When i try to run the updated code it only prints the first word from the list of words that i enter.
def filterlongword(string,number):
for i in range(len(string)):
listwords = []
if len(string[i]) > number:
listwords.append(string[i])
return listwords
def main():
words = input("Please input the list of words: ")
integer = eval(input("Please input an integer: "))
words1 = filterlongword(words,integer)
print("The list of words greater than the integer is",words1)
main()
Initialize listwords before the loop
Return listwords after the loop
Split the input string into a list of words
def filterlongword(string,number):
listwords = []
for i in range(len(string)):
if len(string[i]) > number:
listwords.append(string[i])
return listwords
And a nicer version using list comprehension:
def filterlongword(string,number):
return [word for word in string if len(word) > number]
To split the input string into a list of words, use
words = input("Please input the list of words: ").split()
even better would be just
def filterlongword(string,number):
return filter(lambda word:len(word)>number, string)
# or: return [w for w in string if len(w) > number]
def listing(guess, number):
new_list = []
for i in range(len(guess)):
if len(guess[i]) > number:
new_list.append(guess[i])
print (new_list)
list1 = input("take input: ")
list = list1.split(",")
def main():
global list, integer1
integer = input()
integer1 = int(integer)
listing(list, integer1)
main()
**try this code..this will work, use a delimiter to form a list of your input **
Your main problem is passing words as a single string rather than an iterable of strings. The secondary problem is not specifying the separator between words for the missing .split. Here is my version.
I made longwords a generator function because in actually use, one does not necessary need the sequence of long words to be a list, and I gave an example of this in the output formatting.
def longwords(wordlist, length):
return (word for word in wordlist if len(word) >= length)
def main():
words = input("Enter words, separated by spaces: ").split()
length = int(input("Minimum length of words to keep: "))
print("Words longer than {} are {}.".format(length,
', '.join(longwords(words, length))))
main()
This results in, for instance
Enter words, separated by spaces: a bb ccc dd eeee f ggggg
Minimum length of words to keep: 3
Words longer than 3 are ccc, eeee, ggggg.
Maybe you can shorten the code to the following:
def filter_long_words():
n = raw_input("Give words and a number: ").split()
return sorted(n)[1:] # sorted the List , number it is the shorter .
# called the item from the second position to ende .
print filter_long_words()
def filter_long_words(**words**,**number**):
l=[]
split = **words**.split(",")
for i in split:
if len(i) > **number**:
l.append(i)
return l
**w** = input("enter word:")
**n** = int(input("Enter number"))
filter_long_words(**w**,**n**)
TRY THIS
***
def filter_long_words(n, words):
list_of_words=[]
a= words.split(" ")
for x in a:
if len(x)>n:
list_of_words.append(x)
return list_of_words
for i in range(len(listOfWords)):
listOfInt = []
for i in range(len(listOfWords)):
listOfInt.append(len(listOfWords[i]))
print('List of word length: ',listOfInt)
def filter_long_words(lst,n):
a=[]
for i in lst:
if n<len(i):
a.append(i)
return a
To filter list of words
def filter_long_words(lst,n):
return [word for word in lst if len(word)>n]