3

The entry needs to be lower and in the end the program must print the number of occurrences. For example mem.

smthing = str(input())
if (smthing == smthing.lower()):
    smthing.find(mem)

I'm a total wreck at this so I couldnt go far.

I forgot to tell that I can't use count or list.

1
  • what about overlapping substrings? Commented Apr 24, 2015 at 14:34

7 Answers 7

4

What about something like

string = "hello world hello".lower()
replace = "hello".lower()
count = 0

while string.find(replace) != -1:
    string = string.replace(replace, "", 1)
    count += 1

print count
# => Output
# => 2

To take care of the overlapping strings, instead of replacing the entire substring, we could just replace a single character, preferably the first, replace[0] from the original string

string = "boboobobobobob".lower()
replace = "bob".lower()
count = 0 

while string.find(replace) != -1:
    string = string.replace(replace[0], "", 1)
    count += 1

print count
# Output
# => 6
Sign up to request clarification or add additional context in comments.

5 Comments

probably best not to use str
@PadraicCunningham Good point !!. I have corrected that in answer. Thank you :)
It would be really easy with count, but I'm not allowed to use it.
@plushiecat Using count it could have written in a single line. Hope this answer is apt as per your requirements (using only str.replace and str.find).
it works but wich changes on this should i make to recognise overlapping strings? Padraic gave an example but I havent learned lambda yet so I cant use it.
2

If you have overlapping strings you will need to replace a character a a time:

sub = "bob"
smthing = input()
count = 0

for i in iter(lambda: smthing.find(sub), -1):
    smthing = smthing.replace(sub[0], "", 1)
    count += 1
print(count)

So for boboobobobobob you would get 6 instead of 3.

If you can't use a count but can use either one or the other you could use replace alone, though this won't include overlapping:

print((len(smthing) - len(smthing.replace(sub,""))) / len(sub))

3 Comments

This solves half of my problems, but since I haven't been presented to lambda on class yet I am not allowed to use it.......
The lambda with iter is the same as using a while loop. the last value is a sentinel value that breaks the loop. It can be rewritten as while smthing.find(sub != -1
You could do it recursively also: def rec(s, sub):return 1 + rec(s.replace(sub,"", 1), sub) if s.find(sub) != -1 and s.islower() else 0
1

For the record, you could do this with just string.replace():

smthing = str(input())  
word='mem'
x=0

while word in smthing:
    smthing=smthing.replace(word,'',1)
    x+=1

print x

Demo:

>>> 
memory memory memory
3

Comments

0

You don't; you will require additional tools, possibly just basic arithmetic. For instance, if you replace your substring with one of a different length, the result's length can be compared to the original to count the number of occurences. Another option is to use the start argument to find to find additional occurences. I'm rather interested in knowing what you've tried; the code you show simply doesn't produce any result.

5 Comments

I tried doing it with count but I was told later that I'm not allowed to.
That sort of thing is exactly why this is a poorly presented challenge; the rules are incomplete at best, and for real world programming knowing and using tools like the count method is appropriate. Neither solution I alluded to requires count, though.
I agree with you. My professor insists on giving us such chalenges before teaching us the apropriate way to solve them, only so she can later on say: "oh you did this like that but it is easier this way!".
She also forbid us to use break.
There's a point to exercising fundamentals also; it can give you a better understanding of the higher level tools, and more importantly, allow you to build functioning code when existing ones don't fit. "Using only" can work if the set is complete, such as using only the tools explained in chapters up to the current exercise. It really sucks for demonstrating the expressiveness of a language, though.
0

Try this code:

smthing = "blablabla"
mem = "bl"
count = 0
if (smthing == smthing.lower()):
    bkpsmthing = smthing # maybe you'll need it later
    while (smthing.find(mem) > -1):
        smthing = smthing.replace(mem, '', 1)
        count += 1
print count

It uses the fact that str.find returns -1 when not finding anything, or the index to the lowest entry to stop:

Return the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end]. Return -1 on failure.

It also uses the fact that str.replace can remove a single entry (the lowest) by using the thrid argument (maxreplace). This way we constantly remove entries we've counted:

... If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.

The process can be described like this:

find "bl" in "blablabla" -> found at index 0
replace "bl" in "blablabla" -> gives "ablabla"
find "bl" in "ablabla" -> found at index 1
replace "bl" in "ablabla" -> gives "aabla"
find "bl" in "aabla" -> found at index 2
replace "bl" in "aabla" -> gives "aaa"
find "bl" in "aaa" -> not found, returns -1
stop

To do the same thing withtout the count variable use this simple recursion (amke sure you validate the string is lowercase before using my_count):

def my_count(my_string, my_substring):
    if my_string.find(my_substring) > -1:
        new_string = my_string.replace(my_substring, '', 1)
        return my_count(new_string, my_substring) + 1
    return 0

Output:

>>> my_count("blablabla", "bl")
3

The recursion unfolds as follows:

my_count("blablabla", "bl") =
= my_count("ablabla", "bl") + 1 =
= my_count("aabla", "bl") + 1 + 1 =
= my_count("aaa", "bl") + 1 + 1 + 1 =
= 0 + 1 + 1 + 1 = 3

2 Comments

I'm really sorry! I forgot to mention that I'm not allowed to use count. It would be far simpler with count.
This is not using count. Only a variable named count. I've added a recursive solution that doesn't even require this :-)
-1

Your problem -- finding and counting all the occurrences of a substring in a string -- doesn't necessitate replacing as defined.

You should be able to just take your input, force it to lower, and use the count method to find substrings.

num_substrings = input().lower().count(substring)

Comments

-1

I don't see this approach yet, just loop over find counting occurences :

a='this is a test aaaa'
count =0
loc = a.find('is')
while loc > -1:
    count += 1
    loc = a.find('is',loc+1)
print count -1 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.