Substring Counting in Python and Adding 2 Numbers From One Line of Input
python
Solution
For the first question, `str.count()` does not find overlapping matches, as you noticed. Instead, use `str.find()` and advance your starting index after each time you find a match, until the result is `-1`, for example:
>>> 'assesses'.find('sses', 0) # first look at the start of the string
1
>>> 'assesses'.find('sses', 2) # now look at previous index + 1
4
>>> 'assesses'.find('sses', 5) # now look at previous index + 1
-1
Since there were two results before we got `-1`, we know that there are two locations to find `'sses'` in `'assesses'`.
For you second question, you will need to `split()` the string on `'+'`, which will give you a list of two strings. Call `int()` on each of them, and then add them together.
Problem
I'm following a python website for my schoolwork. It's really neat, it gives you tasks to complete and compiles the code in the browser. Anyway, I came to a challenge that I'm not really sure how to go about. One of the questions was: The same substring may occur several times inside the same string: for example "assesses" has the substring "sses" 2 times, and "trans-Panamanian banana" has the substring "an" 6 times. Write a program that takes two lines of input, we call the first needle and the second haystack. Print the number of times that needle occurs as a substring of haystack. I'm not too sure how I should start this, I know I have to compare the two strings but how? I used the `count` method, but it didn't recognize the second occurrence of `sses` in `assesses`. My second question is one I solved but I cheated a little. The question was: Write a program that takes a single input line of the form «number1»+«number2», where both of these represent positive integers, and outputs the sum of the two numbers. For example on input 5+12 the output should be 17. I used the `eval()` method and it worked, I just think that this wasn't what the grader had in mind for this. Any insight would be greatly appreciated. EDIT: Second question was solved.