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))
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 10 months ago.
Improve this question
I'm trying to write a simple program where it removes the previous letter when there exists a "/" after the character. Also, if there are two "//" after two characters, it should remove the last two characters. The number of / only exists if there a similar number of characters before so // in this scenario: aa//.
for example
x = 'abc/c/dd//a'
print x.rstrip('/')
it should return
aba
another example
x = '/aab//'
print x.rstrip('/')
should return
a
I have seen solutions trying the method above, but it doesn't seem to work for me. Is there an optimal solution for this?
A simple function can do this :
def stripStr(x, special_char="/"):
buff = ""
for char in x:
if char == special_char:
buff = buff[:-1]
else:
buff += char
return buff
assert stripStr('abc/c/dd//a') == 'aba'
assert stripStr('abc////cde/dd///a') == 'ca'
The idea is to reconstruct the string (in the buff variable) character after character. You simply need to keep appending each char except when you find a / then you have to remove the last char of the string.
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)
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 4 years ago.
Improve this question
For a random string such as:
H!i I am f.rom G3?ermany
how can I move all the special characters to the end of the word, for instance:
Hi! I am from. Germany3?
You can try this one :
s = "H!i I am f.rom G3?ermany"
l = []
for i in s.split():
k = [j for j in i if j.isalpha()]
for m in i:
if not m.isalpha():
k.append(m)
l.append(''.join(k))
print(' '.join(l))
It will o/p like :
"Hi! I am from. Germany3?
In python 2x you can do it in single line like :
k = ' '.join([filter(str.isalpha,i)+''.join([j for j in i if not j.isalpha()]) for i in s.split()])
I'm defining special character as anything thats not a-z, A-Z or spaces:
You can split the string into words, use regex to find the special characters in each word, remove them, add them back to the end of the word, then join the words together to create your new string:
import re
string = "H!i I am f.rom G3?ermany"
words = string.split(' ')
pattern = re.compile('[^a-zA-Z\s]')
new = ' '.join([re.sub(pattern, '', w) + ''.join(pattern.findall(w)) for w in words])
That will turn H!i I am f.rom G3?ermany into Hi! I am from. Germany3?
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I wanted to include spaces too while splitting the text, for that i looked up on google used import re
import re
def censor(text,word) :
text1=re.split(r"(\s+)",text)
#print text1
sum=""
for i in range(0,len(text1)) :
if text1[i]==word :
for j in range(0,len(word)) :
sum=sum+"*"
else :
sum=sum+text[i]
return sum
The error I am getting is
image displaying error and code
If I include an another for loop to replace every 'e' with a whitespace , it doesn't work.
In your code, text1 (very bad naming BTW) is a list of words, and text a single string. Your first for loop is iterating on text1 indices (words in the list), but in the else clause you subscript the whole text string. Obviously you want to get the word from the words list (text1), not the character at position i in the text string. IOW: replace your else clause with:
sum=sum+text1[i]
and the test should pass.
If you used a correct naming and proper code layout you would certainly have spotted the problem more easily:
def censor(text, word) :
words = re.split(r"(\s+)",text)
sum=""
for i in range(0, len(words)) :
if words[i] == word :
for j in range(0, len(word)) :
sum = sum + "*"
else :
# here you easily spot the error
sum = sum + text[i]
return sum
Also you are making things much more complicated than they have to be. You can pre-compute the "replacement" string for "bad" words once for all before the loop (and you don't need a loop to do so), and you don't need a range and indexed acces, ou can iterate directly on the words list instead:
def censor(text, word) :
replacement = "*" * len(word)
words = re.split(r"(\s+)", text)
cleaned = ""
for w in words :
if w == word :
cleaned += replacement
else :
cleaned += w
return cleaned
There would be other possible improvements but at least this is mostly readable and much more pythonic.
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)