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
Related
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
I'd like to check if a Python string contains BOTH letter and number, but nothing else. In other words, strings like "A530", "D592" should return True, whereas strings like "ABCDE" (all letters), "000326" (all number), and "A339*加>" (alphanumeric but also has special characters) will return False.
I've seen a lot of sites that show how to check if string contains either letter or number, but not both. This site https://www.geeksforgeeks.org/python-program-to-check-if-a-string-has-at-least-one-letter-and-one-number/ shows how to check both letter and number, but they iterate through each character in the string, which is not very efficient and something I tried to avoid doing if possible.
Solution without regex :)
s=input()
print(not ((all(i.isdigit() for i in s) or (all(i.isalpha() for i in s)) or (any(not i.isalnum() for i in s)))))
If you don't prefer regex then here is the way.
All conditions checked separately. It is Pythonic and readable as well.
Code:
import string
lst = ["A530", "D592", "ABCDE", "000326", "A339*加>"]
str_ascii_digits = string.ascii_letters + string.digits
passed = [s for s in lst if
any(ch in string.ascii_letters for ch in s ) and
any(ch in string.digits for ch in s) and
all((ch in str_ascii_digits for ch in s))]
print(passed)
Output:
['A530', 'D592']
If those string are individual strings, you can use a regex to check that:
import re
re.match("^(?=.*[a-zA-Z])(?=.*[\d])[a-zA-Z\d]+$", "A530") # Will return an re.Match object
re.match("^(?=.*[a-zA-Z])(?=.*[\d])[a-zA-Z\d]+$", "A339*加>") # Will return None
re.match("^(?=.*[a-zA-Z])(?=.*[\d])[a-zA-Z\d]+$", "AAAA") # Will return None
re.match("^(?=.*[a-zA-Z])(?=.*[\d])[a-zA-Z\d]+$", "0000") # Will return 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 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 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 8 years ago.
Improve this question
In python, how do you reverse the order of words in a string and also reverse the order of the letters in the word.
For example, if the input is:
Hello world
The output should be:
olleH dlrow
My attempt:
a=input('Line: ')
print(a[::-1])
Your desired output conflicts with the description of your requirements viz "how do you reverse the order of words in a string and also reverse the order of the letters in the word.". That would simply be the same as reversing the string, which you have already provided as your solution. Instead, to reverse the the letters in each word, but retain the order of those words, you can use split() and a reverse slice ([::-1]) on each word.
s = "Hello world"
for word in s.split():
print word[::-1],
Or, like this:
print ' '.join(word[::-1] for word in s.split())
The above assumes that you do not need to retain the exact whitespace between words.
You may try this using the slice option:
def reverseOrder(strs):
return ''.join([strs[i] for i in xrange(len(strs)-1, -1, -1)])
or better try this:
>>> s='Hello World'
>>> ' '.join(w[::-1] for w in s.split())
'olleH dlrow'
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 9 years ago.
Improve this question
I have to get a sentence from the user and an integer, divide that sentence into words. And then count the characters in each word. Each word that has more characters than the integer put in from the user is supposed to be printed. So if the user puts in the sentence "i love cats" and the number 3. All the words that have more than 3 characters (in this case just love) are supposed to appear as well as the amount of characters it contains (in this case 4). The problem is that I don't know how to get the program to count the letters in each specific word. Is there a way that I can cut a list into sublists and then count the characters in each sublist?
If you can isolate the word in a string, you can simply use len to get the number of letters.
To isolate those words, you can split the string on whitespace using .split().
Other than that, iterate through the words with a for loop, or use a list comprehension.
s = "i love cats"
n = 3
[(x, len(x)) for x in s.split() if len(x) > n]
Prints
[('love', 4), ('cats', 4)]
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)