Python Anagrams recursion [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 months ago.
Improve this question
I have this code:
mylist = open('sortedwords.txt')
txt = mylist.read()
mylist = txt.split()
stuff = input('Type a word here: ')
def removeletters (word, Analysis):
for char in range (len(Analysis)):
if Analysis [char] in word:
word = word.replace(Analysis[char],"",1)
return word
def anagramSubset(word, textList):
newWord = word
for char in range(len(textList)):
if textList[char] not in newWord:
return False
else:
newWord = newWord.replace(textList[char],"",1)
return True
def anagram(word, textList):
savedWords =[]
for checkword in textList:
if len(word) == len(checkword) and anagramSubset(word, checkword):
savedWords.append(checkword)
print(checkword)
anagram(stuff, mylist)
It is supposed to take an input word, remove letters from the input word, then make a subset of words and save that to an array to print off of.
The problem is that the code will save every word that can be created from the input. E.g. an input of spot results in top, tops, stop, pots, pot, etc. The result should only have tops, pots, and stop.
What is wrong with the code, and how do I fix it?

I looked at the code and am wondering what the recursion is adding? The first pass does all of the computational work and then the recursion adds some extra stack frames and alters how output is printed. Am I making the wrong assumption that textList is a list of valid words split from a single line in a file?
When I run this locally with a particular word list, this gets the same effect (in the sense that it finds words whose letters are a subset) with less thrashing:
def anagram(word, textList):
savedWords = []
for checkword in textList:
if anagramSubset(word, checkword):
savedWords.append(checkword)
print(savedWords)
If the problem eventually becomes that you're getting words that have too few letters, you could fix your problem by checking that a word is the length of the original word before you add it with:
if len(original_word) == len(checkword):
savedWords.append(checkword)

Related

I need help (with def) print out some alphabet [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
currently I faced issue with python code
I have two questions relate with "def" code.
1)
I need to print out 6 alphabet which is "K,E,Y,S,N,O"
slimier like under sample
enter image description here
2)
how can I print out this alphabet if user typing one word like "KEY" then print out *mark with KEY
or If user typing "BED" then print out "E"only because we only have alphabet with K,E,Y,S,N,O
if can anyone help me with this two questions? I appreciate that
Thanks
Question 1 need work with 2-dimensional list (list with lists for rows) and I skip this problem.
As for Question 2 you can filter chars in word.
You can treat string "BED" as list of chars (even without using list("BED")) and you can use it in for-loop to check every char with list ["K","E","Y","S","N","O"] (or "KEYSNO") and skip chars "B" and "D"
#my_chars = "KEYSNO" # also works
my_chars = ["K","E","Y","S","N","O"]
word = "BED"
for char in word:
if char in my_chars:
print(char, "- OK")
else:
print(char, "- unknown")
Result:
B - unknown
E - OK
D - unknown
This way you can create new list to keep only correct chars
my_chars = ["K","E","Y","S","N","O"]
word = "BED"
filtered_chars = []
for char in word:
if char in my_chars:
filtered_chars.append(char)
print(filtered_chars)
Result:
['E']
In Python you can write it even shorter using list comprehension
filtered_chars = [char for char in word if char in my_chars]
Eventually you can write it with function filter() like
filtered_chars = list(filter(lambda char: char in my_chars, word))

how do i remove a key from a dictionary when the key is a space bar [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
def search4vowels(word):
"""fucntion searchs for vowels from a given string input("") & counts them """
vowels = set("aeiou")
vowels = str(vowels)
found = {}
for letter in word:
if letter in vowels:
found.setdefault(letter, 0)
found[letter]+=1
for k,v in sorted(found.items()):
print (k,"has",v,"vowels in the sentence",word)
how do i remove/delete or pop the space bar key & value in the found dictionary if i was to write a given sentence as the word function argument
Try this in your interpreter:
str(set("aeiou"))
The result is:
"{'a', 'u', 'o', 'i', 'e'}"
As the string representation of that data structure contains spaces, the code you posted therefore believes that a space is a vowel. Several punctuation characters are also vowels. Obviously this isn't what you want.
As suggested in comments, it would be better to simply use
vowels = "aeiou"
if letter in vowels:
stuff
Because "in" is expected to work on a set, vowels = set("aeiou") would have worked, and is better practice. Just don't take the string representation. In the case of a five character string, performance isn't a concern, but set provides better lookup for existence in an arbitrarily large data set.
Oh yes, just to answer the question literally, the first comment (Paul H) is correct on how you can remove a key from the dict, after having added it by mistake.
found.pop(' ', None)

How can I write "EvenWord" Recursive in Python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
We tried to solve the following problem with friends but we couldn't come to a conclusion. How can we approach this question?
The full question is:
Even Words Problem: An even word is a word that contains an even number of copies of every letter. For example, the word "tattletale"
is an even word, since there are four copies of 't' and two copies of
'a,' 'e,' and 'l.' Similarly, "appeases" and arraigning" are even
words. However, "banana" is not an even word, because there is just
one 'b' and three copies of 'a.'
Write a function def isEvenWord(word) that accepts as input a string
representing a single word and returns whether or not that word is an
even word.
Your solution should be recursive and must not use any loops (e.g.
while, for). As a hint, this problem has a beautiful recursive
decomposition:
• The empty string is an even word, since it has 0 copies of every
letter.
• Otherwise, a word is an even word if there are at least two copies
of the first letter and the word formed by removing two copies of the
first letter is itself an even word.
For example, we can see that the word "appeases" is an even word using
the following logic:
"appeases" is an even word, because "ppeses" is an even word, because
"eses" is an even word, because "ss" is an even word, because "" is an
even word.
Screenshot of the problem description
I assume the tricky part is not using loop since this the solution must be recursive.
In this problem, you want to find whether the count of each letter can be divided by two.
Here are the steps you can follow:
1) Define your base condition
In this problem, the base condition is when there are no more letters in the word to check; in other words, your word is an empty string ''.
If the base condition is reached, it means that you have checked the count of all the letters in the word and the count was always even. So you can stop there. You've checked all the letters in the word and their count and they are even --> you return True and you are done.
2) Define what you do if the base condition is not reached:
In this problem, you need to check that the count of each letter in the word is even. You can store the letter in a variable and check its count in the word.
You must check the last letter each time, create a new word that doesn't contain the letter already checked, and run the isEvenWord(word) function again on the new word.
If when you check the count of the letter, it is not even, then you are done, you know that the word is not even since at least one letter in the word is not even so you return False.
If the count of the letter you are checking is even then you continue the check the next letter by calling your function again on the new word made of the remaining letters that you haven't checked yet.
Here is the code version of the explanation above:
def isEvenWord(word):
if word == '': # base condition
return True
else:
last_letter = word[-1]
if word.count(last_letter) % 2 != 0:
return False
else:
next_word = word[0:-1] #create the next word you want to test (ie the word except the last letter)
next_word = word.replace(last_letter, '') # in the new word, replace the variable last_letter (the letter you just counted) by an empty string '' which is like removing it
return isEvenWord(next_word)
Very nice little puzzle, thanks for sharing.
I hope this helps.

Python Find a word in a list [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Hello so I have to do a program that identifies all of the positions where a word occurs in a list but when I run my program it doesn't output anything.
Here's my code :
sentence =("ASK NOT WHAT YOUR CONTRY CAN DO FOR ASK WHAT YOU CAN DO FOR YOUR CONTRY") #This is a list
print (sentence)
text = input("Choose a word from the sentence above")#this prints out some text with an input
sentence = sentence.split(" ")# This splits the list
text = text.upper ()# this makes the text in capital letters
def lookfor ():
if text in sentence:
for i in sentence:
value = sentence.index(sentence)
print ("Your word has been found in the sentence at the position", value + "and", value )
else:
print ("The word that you have typed is not found in the sentence.")
Thank you
To answer your questions, nothing is happening because you aren't calling the function.
There's a lot of work remaining on your function, but here are some general tips:
1) Index only finds the first instance of an element in a list
2) You can't be sure that a word is in your sentence exactly twice
3) Use descriptive variable names. For example, for word in sentence makes a lot more sense intuitively
You can do something like this:
sentence =("ASK NOT WHAT YOUR CONTRY CAN DO FOR ASK WHAT YOU CAN DO FOR YOUR CONTRY") #This is a list
print (sentence)
text = raw_input("Choose a word from the sentence above: ")#this prints out some text with an input
sentence = sentence.split(" ")# This splits the list
text = text.upper ()# this makes the text in capital letters
def lookfor (text):
indexes = [ idx+1 for word, idx in zip(sentence, range(0,len(sentence))) if text == word ]
print ("Your word has been found in the sentence at these positions", indexes )
if not indexes:
print ("The word that you have typed is not found in the sentence.")
lookfor(text)
Example:
ASK NOT WHAT YOUR CONTRY CAN DO FOR ASK WHAT YOU CAN DO FOR YOUR CONTRY
Choose a word from the sentence above: for
('Your word has been found in the sentence at these positions', [8, 14])

Testing to see if a word contains only specified syllables [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I need to test if a word only contains certain syllables. For example if a word, "pikakapichu" contains only the syllables, "pi", "ka", or "chu", I want to return "Yes". If it contains other syllables or characters then I want to return "No".
Another example:
word= "pikapikachudo"
Returns: "NO" because it has a syllable other than 'pi', 'ka', and 'chu'
You appear to be describing a phonology where each syllable is open and the nucleus vowel is always preceded by a cluster of consonants. (With some additions which I hope are unimportant here, Japanese is a language with this structure.) Thus you can use a regular expression like
[bcdfghj-np-tvwxz]+[aeiou]
to describe each syllable.
Try to store the syllables in a list, and going through that list and replace every item in the list with an empty string.
Eg: Take pi and replace pi' with empty string inside l. Output should "pikapikachudo --> kakachudo
same process to the other items.
"pikapikachudo --> kakachudo --> do
At the end, we test if l is empty or no. If it's empty, it means that these are the only sylabules in the word l
l= "pikapikachudo"
r= [ 'pi', 'ka','chu']
def isOnlysyllables_in_word(l,r):
for x in r:
l= l.replace(x, '')
print "You still have <",l,"> in word"
return l==''
print isOnlysyllables_in_word(l,r) #return False

Categories

Resources