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.
Related
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 5 days ago.
Improve this question
we have encoded strings that want to decryption it.
First, the first letter of the string, then the last letter. Then the rest of the letters are stored in the same way. For example, the string amir is first added to the new letter. Then the last letter is r. This process continues in the same way, ie in the next stage m and in the next stage after the addition. (That is, first the first letter and the last letter, then the second letter and then the last letter of the last letter, and this process continues until the word)
In the second step, the whole string is reversed.
In the third step, the letter a becomes 4. The letter o is replaced by 0. The letter t becomes 7 and finally the letter i becomes 1.
Note: It is guaranteed that the number of letters is always even and only includes lowercase English letters
example:
input 1mr4
output amir
input w00lrlledh
output helloworld
I read this but I have no idea of write a program
You can use replace to make the character replacements.
For the encoding part: to apply the permutation of the characters, apply the logic with a variable i that you let run from 0 to the half of the string. Take the character at index i and the one that is i positions from the right (i.e. you can use -1-i). Then concatenate those characters. You can reverse the order at the same time.
To do the opposite, replace the opposite characters.
For the permutation, analyse how it works on a piece of paper and you'll find the logic of where to find the characters that need to be placed from left to right.
Here is code:
def encrypt(s):
for a, b in "a4", "o0", "i1", "t7":
s = s.replace(a, b)
return "".join(s[-1-i] + s[i] for i in range(len(s) // 2 - 1, -1, -1))
def decrypt(s):
for a, b in "a4", "o0", "i1", "t7":
s = s.replace(b, a)
return "".join(s[-1-i*2] for i in range(len(s) // 2)) + \
"".join(s[i*2] for i in range(len(s) // 2))
I'm trying to solve a problem that I have with a recurring character problem.
I'm a beginner in development so I'm trying to think of ways I can do this.
thisWord = input()
def firstChar(thisWord):
for i in range(len(thisWord)):
for j in range(i+1, len(thisWord)):
if thisWord[i] == thisWord[j]:
return thisWord[i]
print(firstChar(thisWord))
This is what I came up with. In plenty of use cases, the result is fine. The problem I found after some fiddling around is that with a word like "statistics", where the "t" is the first recurring letter rather than the "s" because of the distance between the letters, my code counts the "s" first and returns that as the result.
I've tried weird solutions like measuring the entire string first for each possible case, creating variables for string length, and then comparing it to another variable, but I'm just ending up with more errors than I can handle.
Thank you in advance.
So you want to find the first letter that recurs in your text, with "first" being determined by the recurrence, not the first occurrence of the letter? To illustrate that with your "statistics" example, the t is the first letter that recurs, but the s had its first occurrence before the first occurrence of the t. I understand that in such cases, it's the t you want, not the s.
If that's the case, then I think a set is what you want, since it allows you to keep track of letters you've already seen before:
thisword = "statistics"
set_of_letters = set()
for letter in thisword:
if letter not in set_of_letters:
set_of_letters.add(letter)
else:
firstchar = letter
break
print(firstchar)
Whenever you're looking at a certain character in the word, you should not check whether the character will occur again at all, but whether it has already occurred. The algorithmically optimal way would be to use a set to store and look up characters as you go, but it could just as well be done with your double loop. The second one should then become for j in range(i).
This is not an answer to your problem (one was already provided), but an advice for a better solution:
def firstChar(thisWord):
occurrences: dict[str, int] = {char: 0 for char in thisWord} # At the beginning all the characters occurred once
for char in thisWord:
occurrences[char] += 1 # You found this char
if (occurrences[char] == 2): # This was already found one time before
return char # So you return it as the first duplicate
This works as expected:
>>> firstChar("statistics")
't'
EDIT:
occurrences: dict[str, int] = {char: 0 for char in thisWord}
This line of code creates a dictionary with the chars from thisWord as keys and 0 as values, so that you can use it to count the occurrences starting from 0 (before finding a char its count is 0).
I'm newbie in Python so that I have a question. I want to change letter in word if the first letter appears more than once. Moreover I want to use input to get the word from user. I'll present the problem using an example:
word = 'restart'
After changes the word should be like this:
word = 'resta$t'
I was trying couple of ideas but always I got stuck. Is there any simple sollutions for this?
Thanks in advance.
EDIT: In response to Simas Joneliunas
It's not my homework. I'm just finished reading some basic Python tutorials and I found some questions that I couldn't solve on my own. My first thought was to separate word into a single letters and then to find out the place of the letter I want to replace by "$". I have wrote that code but I couldn't came up with sollution how to get to specific place and replace it.
word = 'restart'
how_many = {}
for x in word:
how_many=+1
else:
how_many=1
for y in how_many:
if how_many[y] > 0:
print(y,how_many[y])
Using str.replace:
s = "restart"
new_s = s[0] + s[1:].replace(s[0], "$")
Output:
'resta$t'
Try:
"".join([["$" if ch in word[:i] else ch for i, ch in enumerate(word)])
enumerate iterates through the string (i.e. a list of characters) and keeps a running index of the iteration
word[:i] checks the list of chars until the current index, i.e. previously appeared characters
"$" if ch in word[:i] else ch means replace the character at existing position with $ if it appears before others keep the character
"".join() joins the list of characters into a single string.
This is where the python console is handy and lets you experiment. Since you have to keep track of number of letters, for a good visual I would list the alphabet in a list. Then in the loop remove from the list the current letter. If letter does not exist in the list replace the letter with $.
So check if it exists first thing in the loop, if it exists, remove it, if it doesn’t exist replace it from example above.
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 7 years ago.
Improve this question
How can I return a duplicated word in a list?
I was asked to create a function, word_count(text, n). The text is converted into a list and then return the word that is repeated n times. I've tried to write it but it seems to return every single word.
>>> repeat_word_count("one one was a racehorse two two was one too", 3)
['one']
I've used the for loop and conditioned it. I'm wanted to post my code but I'm scared that my school will find the code online :(
I think I know what it is that you are wanting to do and without seeing your code I can't point out exactly where you're going wrong so I'll take you through creating this function step by step and you should be able to figure out where you went wrong.
I think you are trying to create this:
def function(a,b):
"""where a is a sentence and b is the target number.
The function will return to you each word in the
given sentence that occurs exactly b times."""
To do this we have to do the following:
converts the sentence into a list of words and removes punctuation,capitalization,and spaces.
iterates through each unique word in the sentence and print it if it occurs exactly b times in the sentence
put these together to make a function
so in your example your sentence was "one one was a racehorse two two was one too", and you're looking for all words that occur exactly 3 times, so the function should return the word "one"
We'll look at each step one at a time.
FIRST STEP -
we have to take the sentence or sentences and convert them into a list of words. Since I don't know if you will be using sentences with punctuation and/or capitalization I'll have to assume that its possible and plan to deal with them. We'll have to omit any punctuation/spaces from the list and also change all the letters in each word to lowercase if they happened to have a capital letter because even though "Cat" and "cat" are the same word, according to a computer brain, "Cat" does NOT equal any of these:
"cat" - lowercase c doesn't match uppercase C in "Cat"
" Cat" - there is an extra space at the start of the word
"Cat." - There is a period after the word
"Cat " - There is a space after the word
So if we use "One one was a racehorse two two was one, too." as our input we'll need to handle spaces, punctuation, and capitalization. Luckily all of this work can be done with 2 lines of code by using a regular expression and list comprehension to get rid of all the junk and create a list of words.
import re
wordlist=[i.lower() for i in re.findall(r"[\w']+",sentence)]
This gives us our list of words:
['one', 'one', 'was', 'a', 'racehorse', 'two', 'two', 'was', 'one', 'too']
SECOND STEP -
Now we need to iterate through each Unique word in the wordlist and see if it occurs exactly b times. Since we only need unique words we can create a list that only contains each word exactly once by converting the wordlist from a list to a set and looping through each word in the set and counting the number of times they appear in the wordlist. Any that occur exactly b number of times are our solutions. I'm not exactly sure how you were wanting the results returned but i'm going to assume you want to have each word that fits the criteria to be printed one at a time.
for word in set(wordlist):
if wordlist.count(word)==b:
print word
THIRD STEP -
Now I'll put all this together to create my function:
import re
def repeat_word_count(a,b):
wordlist=[i.lower() for i in re.findall(r"[\w']+",a)]
for word in set(wordlist):
if wordlist.count(word)==b:
print word
I hope this helps you understand a bit better
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)