2

I'm trying to write a function that takes two string arguments and returns the number of times a character from the first string occurs in the second string.

I am a complete beginner to python and am stumped. If anyone could point me in the right direction that would be great. I've been given this to start with:

def occurrences(text1, text2):
    """Return the number of times characters from text1 occur in text2

    occurrences(string, string) -> int
    """
    #Your code goes here

As you can see, 2 strings are needed. I thought that string 1 and string 2 would be sufficient but I have no idea how to to define them.

I have started with this so far and I'm not even having any success.

for c in "string":
    print c
    if c == char c in "string2":
        count += 1

I'm just throwing in random variables because how am I suppose to find char(A-Z) in a string that I dont even know?

EDIT: some of the tips you guys have told me i havn't learned yet. For this question i should be using:

  • for loop
  • in

Some hints were given to me also:

Hint 1: You might find in useful for testing if one string is in another string.

Hint 2: Look at each character in the second argument and see if it is in the first argument.

Robert Gowland
  • 7,677
  • 6
  • 40
  • 58
Anthony Do
  • 1,409
  • 4
  • 18
  • 19
  • 1
    This is a good question because you explain your problem, you show what you have done so far, explain why/how you are stuck, and have flagged it as homework. – Marcin Mar 18 '12 at 11:21

5 Answers5

4

Let's start here and have a bit of a discussion:

As you can see, 2 strings are needed. I thought that string 1 and string 2 would be sufficient but I have no idea how to to define them.

They are provided for you: they are called text1 and text2. They come from the code that calls the functions. Were functions explained to you at some point? In your own words, how does a function work? What will the code look like that calls occurrences?

(Hint for the last part: there is an example given on your assignment sheet.)

Next:

if c == char c in "string2":

What do you expect this to mean? In particular, what do you expect char to mean? (Have you studied programming languages other than Python before?)

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • No i havn't studied other programming languages before. I have done some HTML in highschool but it was pretty basic. With this, i am trying to explain that: if c belongs to a character in strings 2. I think i put the c there for c = c in string 2 – Anthony Do Mar 18 '12 at 12:06
  • Ok, and the rest of the questions? (I'll edit the answer with your responses and continue on; we can delete the comments afterwards. Or we can take it to chat if that becomes necessary.) – Karl Knechtel Mar 18 '12 at 12:07
  • How would i make the function find individual letters (A-Z) in the strings. I have made the function so far that for c in text 1, count the number of c's in text 2. I still dont understand how i can write this in python. – Anthony Do Mar 18 '12 at 12:12
  • 1
    @AnthonyDo Have you read the other answers? They explain how to do this, and indeed how to avoid traversing the entire a-z range. – Marcin Mar 18 '12 at 12:15
  • 2
    Please, I'm trying to guide your understanding here. To do so, I must first assess what you know. For this to work, I need you to answer the questions, not skip ahead and re-ask what you were asking. – Karl Knechtel Mar 18 '12 at 12:21
  • Marcin, Rikpoggi's answers dont make much sense :S. I dont see any help on the a-z range. I have uploaded an image of the entire question onto tinypic. http://i42.tinypic.com/1ihq4i.jpg – Anthony Do Mar 18 '12 at 12:22
  • @AnthonyDo Ask about the parts of them you don't understand. I'm certain that Rik Poggi's answer makes sense. – Marcin Mar 18 '12 at 12:25
  • Ok. I'll answer the questions stated above.Were functions explained to you at some point?No functions wern't explained to me.In your own words, how does a function work? A function will work if there is code that can be executed.What will the code look like that calls occurrences? I don't know what you mean by calls occurences. Im very sorry, im very new the programming language. – Anthony Do Mar 18 '12 at 12:26
  • set('fooled') - does this mean that i can put set('text1') into the code and it will print the individual set of characters in text 1? 'hello world'. count('e'). I understand that this counts the numbers of e's in 'hello world' but can i/how implement this into my code so that it counts the numbers of characters (A-Z) in text 1? – Anthony Do Mar 18 '12 at 12:31
  • 1
    "calling" a function is how it is used. There is something very wrong if functions weren't explained to you at all yet, considering that you are being expected to write one. Please consult your reference materials, or try Google (e.g. `what is a function in python`, `how do functions work in python` etc.) or Wikipedia before we move on. `occurrences` is the function that you are defining (`def` is short for "define"). To test the code, you will need to call the function, so you will need to know what that looks like. --- Never mind @RikPoggi's answer for now. Take it one step at a time. – Karl Knechtel Mar 18 '12 at 12:33
  • 2
    @AnthonyDo: *(1)* stackoverflow have its own [chat](http://chat.stackoverflow.com/), outside chats are discouraged. *(2)* If there's something not clear in my answer you could've asked there. *(3)* You *have* to play with those thing in order to learn them otherwise they will remain obsucre. Anyway I've updated my answer hoping to have made it more clear. – Rik Poggi Mar 18 '12 at 12:49
  • @RikPoggi unfortunately he needs 4 more rep to use the chat here >_ – Karl Knechtel Mar 18 '12 at 12:50
  • @KarlKnechtel: It wasn't a 4 upvote question, but if someone is really willingful to learn I have no problem in fixing that. – Rik Poggi Mar 18 '12 at 12:53
  • Thanks. I created and am waiting in http://chat.stackoverflow.com/rooms/9012/q9757799 – Karl Knechtel Mar 18 '12 at 12:56
  • @AnthonyDo: I'll wait there too. – Rik Poggi Mar 18 '12 at 12:57
  • Thanks for your help guys, i think i'm gonna read that python introduction Rik has linked me to. Python is actually really hard, i believed it was easy and i could do the problems without that much readings. now i am 1 week behind in my course. Thanks for your answers and time spent helping me on my question. – Anthony Do Mar 18 '12 at 13:01
1

Since this sounds like homework, I'm just going to give you some pointers about what you'll need to do:

  1. Find out which charachters are in the text1 string. The point is that you wont interate over the same charachter twice.
    set() can help you with that:

    >>> set('fooled')
    set(['d', 'e', 'l', 'o', 'f'])
    

    Try to play a bit with them.

  2. Iterate over the set of (different) charachters from text1. You can use .count():

    >>> 'hello world'.count('e')
    1
    >>> 'hello world'.count('o')
    2
    

    This can count how many times a charachter occures in a string, you'll need to sum all those values and return that sum.

Note: There are many ways for doing what you're asking this is only one of them (and not the best performant one). If you look around searching for "count string occurences" or something like, that you can find other interesting solutions :)


Another approach could be to to start from text2:

  1. Iterate with a for-loop over text2
  2. If a char from text2 is found in text1, than increment by one your sum.

Update: Have you tried a bit to play with them?

Check the difference between:

>>> word = 'fooled'
>>> for c in word:
...     print(c)

and:

>>> word = 'fooled'
>>> for c in set(word):
...     print(c)

It shouldn't be hard to call inside the for-loop text2.count(c).

If this still "doens't make much sense", than I'd suggest to read a good Python Tutorial and come back later.

Community
  • 1
  • 1
Rik Poggi
  • 28,332
  • 6
  • 65
  • 82
1

You have to put your code in the function and use the arguments the function has. This should help you figure out how it works:

def occurrences(text1, text2):
    """Return the number of times characters from text1 occur in text2

    occurrences(string, string) -> int
    """
    # loop through the string in the variable `text1`
    for c in text1: 
        print c 
        # see if its in `text2`
        if c in text2: 
            pass # you do the rest ;)

# calls the function with 'fooled' -> text1 and 'hello world' -> text2
print occurrences('fooled', 'hello world')
Jochen Ritzel
  • 104,512
  • 31
  • 200
  • 194
0

So, you know how to iterate over the characters in a string: good.

What you are not doing is anything that could count them. You need a set of counters to keep track of each character in the string. One way to achieve that is with a dict, or collections.defaultdict, or another class found in collections.

Use the docs, Luke.

Bonus tip: It is possible to do this (readably) in O(m+n) time, in a single line, using appropriate datastructures and a list comprehension (google it!).

Marcin
  • 48,559
  • 18
  • 128
  • 201
-1

for python 2.7 and higher:

[ Solution in previous version of question ]

Community
  • 1
  • 1
FoRever_Zambia
  • 1,179
  • 9
  • 13