Simple question:
I'm new to programming and need to use the command string.count
I know that if I do
a="laringologo"
a.count("o")
it will give me the number of o's in the word.
How can I use the command if I want to count the number of o's after "laringo"?
I know the command works like
string.count(s, sub[, start[, end]] but I don't understand how to use it correctly
You can use the start argument to tell count at which index to start counting. In your case, you want it to start counting after the number of characters in "laringo", so you can do:
a="laringologo"
>>> a.count('o', len("laringo"))
2
#sacul's answer is correct if/when you know that 'laringo' is always at the beginning of a. If it is not, as in the following example, then you should first find it, then skip it, and then count 'o's in the rest of the string:
a = "foobarlaringologo"
a.count('o', a.index('laringo') + len('laringo'))
count() has three attributes string.count(substring, start=…, end=…) If you want to count substrings after a certain number of characters, the syntax would be string.count('substring', numberOfCharacters). If "laringologo" is not necessarily the beginning of the string you can look for it with string.find('substring')
a="laringologo new to programming"
a.count("o", len(laringologo))
#or
b="header laringologo new to programming"
b.count("o", b.find('laringologo')+len('laringologo'))
Related
def most_frequency_occ(chars,inputString):
count = 0
for ind_char in inputString:
ind_char = ind_char.lower()
if chars == ind_char:
count += 1
return count
def general(inputString):
maxOccurences = 0
for chars in inputString:
most_frequency_occ(chars, inputString)
This is my current code. I'm trying to find the most frequent occurring letter in general. I created another function called most_frequency_occ that finds a specific character in the string that occurs the most often, but how do I generalize it into finding the frequent letter in a string without specifying a specific character and only using loops, without any build in string functions either.
For example:
print(general('aqweasdaza'))
should print 4 as "a" occurs the most frequently, occurring 4 times.
If I got your task, I think that using a dictionary will be more comfortable for you.
# initializing string
str = "Hello world"
# initializing dict of freq
freq = {}
for i in str:
if i in freq:
freq[i] += 1
else:
freq[i] = 1
# Now, you have the count of every char in this string.
# If you want to extract the max, this step will do it for you:
max_freq_chr = max(stats.values())
There are multiple ways you find the most common letter in a string.
One easy to understand and cross-language way of doing this would be:
initialize an array of 26 integers set to 0.
go over each letter one by one of your string, if the first letter is an B (B=2), you can increment the second value of the array
Find the largest value in your array, return the corresponding letter.
Since you are using python, you could use dictionaries since it would be less work to implement.
A word of caution, it sounds like you are doing a school assignment. If your school has a plagiarism checker that checks the internet, you might be caught for academic dishonesty if you copy paste code from the internet.
The other answers have suggested alternative ways of counting the letters in a string, some of which may be better than what you've come up with on your own. But I think it may be worth answering your question about how to call your most_frequency_occ function from your general function even if the algorithm isn't great, since you'll need to understand how functions work in other contexts.
The thing to understand about function calls is that the call expression will be evaluated to the value returned by the function. In this case, that's the count. Often you may want to assign the return value to a variable so you can reference it multiple times. Here's what that might look like:
count = most_frequency_occ(chars, inputString)
Now you can do a comparsion between the count and the previously best count to see if you've just checked the most common letter so far:
maxOccurences = 0
for chars in inputString:
count = most_frequency_occ(chars, inputString)
if count > maxOccurences: # check if chars is more common than the previous best
maxOccurences = count
return maxOccurences
One final note: Some of your variable and function names are a bit misleading. That often happens when you're changing your code around from one design to another, but not changing the variable names at the same time. You may want to occasionally reread your code and double check to make sure that the variable names still match what you're doing with them. If not, you should "refactor" your code by renaming the variables to better match their actual uses.
To be specific, your most_frequency_occ function isn't actually finding the most frequent character itself, it's only doing a small step in that process, counting how often a single character occurs. So I'd call it count_char or something similar. The general function might be named something more descriptive like find_most_frequent_character.
And the variable chars (which exists in both functions) is also misleading since it represents a single character, but the name chars implies something plural (like a list or a string that contains several characters). Renaming it to char might be better, as that seems more like a singular name.
I was wondering if there is a way in Python 3.5 to check if a string contains a certain symbol. Also I'd like to know if there is a way to check the amount the string contains. For example, if I want to check how many times the character '$' appears in this string...
^$#%#$$,
how would I do that?
You can use split to check if symbol's in the string:
if your_str.split('$'):
print(your_str.count('$'))
You can also use re.findall:
import re
print(len(re.findall('\$', your_str)))
It returns 0 if there is no such a symbol in the string, otherwise returns count of that symbol in the string.
But the easiest way is to check and return count if symbol is in:
print(your_str.count('$'))
It returns 0 if nothing is found.
These are the built-in functions index and count. You can find full documentation at the official site. Please get used to doing the research on your own; the first step is to get familiar with the names of the language elements.
if my_str.index('$') != 0:
# Found a dollar sign
print my_str.count('$')
I am using Python 3.4.1. The purpose of this program is to take a series of elements that the user types in and run them backwards. For example, "Hello" becomes "olleH". I've been trying to get this right for a while now and It's been completely stumping me for quite some time.
word=input("Type any word:")
word_l=len(word)
word2=None
for word in range(word_l):
word2+=word[word_l]-i
print(word2)
Sorry if this seems like a serious noob question. Thanks.
This is a standard indexing problem. There's a third optional argument when you're slicing that creates a step. By setting that step to -1 you reverse the sequence:
>>> word = "hello"
>>> print(word[::-1])
olleh
>>>
Rule of thumb: If you are using string index or list indexes in a loop in Python to access each element -- look at the problem again 'cause there probably is a better way to do it.
You can simply add each character to the string in turn which will reverse the string:
word='Hello'
word2=''
for c in word:
word2=c+word2
print(word2)
You can also just use reversed:
>>> ''.join(reversed('Hello'))
'olleH'
word=input("Type any word:")
word_l=len(word)
word2=''
for i in range(word_l):
word2+=word[word_l-i-1]
print(word2)
I have two lists:
a - dictionary which contains keywords such as ["impeccable", "obvious", "fantastic", "evident"] as elements of the list
b - sentences which contains sentences such as ["I am impeccable", "you are fantastic", "that is obvious", "that is evident"]
The goal is to use the dictionary list as a reference.
The process is as follows:
Take an element for the sentences list and run it against each element in the dictionary list. If any of the elements exists, then spit out that sentence to a new list
Repeating step 1 for each of the elements in the sentences list.
Any help would be much appreciated.
Thanks.
Below is the code:
sentences = "The book was awesome and envious","splendid job done by those guys", "that was an amazing sale"
dictionary = "awesome","amazing", "fantastic","envious"
##Find Matches
for match in dictionary:
if any(match in value for value in sentences):
print match
Now that you've fixed the original problem, and fixed the next problem with doing the check backward, and renamed all of your variables, you have this:
for match in dictionary:
if any(match in value for value in sentences):
print match
And your problem with it is:
The way I have the code written i can get the dictionary items but instead i want to print the sentences.
Well, yes, your match is a dictionary item, and that's what you're printing, so of course that's what you get.
If you want to print the sentences that contain the dictionary item, you can't use any, because the whole point of that function us to just return True if any elements are true. It won't tell you which ones—in fact, if there are more than one, it'll stop at the first one.
If you don't understand functions like any and the generator expressions you're passing to them, you really shouldn't be using them as magic invocations. Figure out how to write them as explicit loops, and you will be able to answer these problems for yourself easily. (Note that the any docs directly show you how to write an equivalent loop.)
For example, your existing code is equivalent to:
for match in dictionary:
for value in sentences:
if match in value:
print match
break
Written that way, it should be obvious how to fix it. First, you want to print the sentence instead of the word, so print value instead of match (and again, it would really help if you used meaningful variable names like sentence and word instead of meaningless names like value and misleading names like match…). Second, you want to print all matching sentences, not just the first one, so don't break. So:
for match in dictionary:
for value in sentences:
if match in value:
print value
And if you go back to my first answer, you may notice that this is the exact same structure I suggested.
You can simplify or shorten this by using comprehensions and iterator functions, but not until you understand the simple version, and how those comprehensions and iterator functions work.
First translate your algorithm into psuedocode instead of a vague description, like this:
for each sentence:
for each element in the dictionary:
if the element is in the sentence:
spit out the sentence to a new list
The only one of these steps that isn't completely trivial to convert to Python is "spit out the sentence to a new list". To do that, you'll need to have a new list before you get started, like a_new_list = [], and then you can call append on it.
Once you convert this to Python, you will discover that "I am impeccable and fantastic" gets spit out twice. If you don't want that, you need to find the appropriate please to break out of the inner loop and move on to the next sentence. Which is also trivial to convert to Python.
Now that you've posted your code… I don't know what problem you were asking about, but there's at least one thing obviously wrong with it.
sentences is a list of sentences.
So, for partial in sentences means each partial will be a sentence, like "I am impeccable".
dictionary is a list of words. So, for value in dictionary means each value will be a word, like "impeccable".
Now, you're checking partial in value for each value for each partial. That will never be true. "I am impeccable" is not in "impeccable".
If you turn that around, and check whether value in partial, it will give you something that's at least true sometimes, and that may even be what you actually want, but I'm not sure.
As a side note, if you used better names for your variables, this would be a lot more obvious. partial and value don't tell you what those things actually are; if you'd called them sentence and word it would be pretty clear that sentence in word is never going to be true, and that word in sentence is probably what you wanted.
Also, it really helps to look at intermediate values to debug things like this. When you use an explicit for statement, you can print(partial) to see each thing that partial holds, or you can put a breakpoint in your debugger, or you can step through in a visualizer like this one. If you have to break the any(genexpr) up into an explicit loop to do, then do so. (If you don't know how, then you probably don't understand what generator expressions or the any function do, and have just copied and pasted random code you didn't understand and tried changing random things until it worked… in which case you should stop doing that and learn what they actually mean.)
The task that I have to perform is as follows :
Say I have a list of words (Just an example...the list can have any word):
'yappingly', 'yarding', 'yarly', 'yawnfully', 'yawnily', 'yawning','yawningly',
'yawweed', 'yealing', 'yeanling', 'yearling', 'yearly', 'yearnfully','yearning',
'yearnling', 'yeastily', 'yeasting', 'yed',
I have to create a new list of words from which words having the suffix ing are added after removing the suffix (i.e yeasting is added to the new list as yeast) and the remaining words are added as it is
Now as far as insertion of string ending with ing is concerned, i wrote the following code and it works fine
Data=[w[0:-3] for w in wordlist if re.search('ing$',w)]
But how to add the remaining words to the list?? How do I add an else clause to the above if statement? I was unable to find suitable documentation for the above. I did came across several questions on SO regarding the shorthand if else statement, but simply adding the else statement at the end of the above code doesn't work. How do I go about it??
Secondly, if I have to extend the above regular expression for multiple suffixes say as follows:
re.search('(ing|ed|al)$',w)
How do I perform the "trim" operation to remove the suffix accordingly and simultaneously add the word to the new list??
Please Help.
First, what makes you think you need a regexp at all? There are easier ways to strip suffixes.
Second, if you want to use regexps, why not just re.sub instead of trying to use regexps and slicing together? For example:
Data = [re.sub('(ing|ed|al)$', '', w) for w in wordlist]
Then you don't need to work out how much to slice off (which would require you to keep track of the result of re.search so you can get the length of the group, instead of just turning it into a bool).
But if you really want to do things your way, just replace your if filter with a conditional expression, as in iCodez's answer.
Finally, if you're stuck on how to fit something into a one-liner, just take it out of the one-liner. It should be easy to write a strip_suffixes function that returns the suffix-stripped string (which is the original string if there was no suffix). Then you can just write:
Data = [strip_suffixes(w) for w in wordlist]
Regarding your first question, you can use a ternary placed just before the for:
Data=[w[0:-3] if re.search('ing$',w) else w for w in wordlist]
Regarding your second, well, the best answer in my opinion is to use re.sub as #abarnert demonstrated. However, you could also make a slight adaption to your use of re.search:
Data=[re.search('(.*)(?:ing|ed|al)$', w).group(1) for w in wordlist]
Finally, here is a link for more information on comprehensions.