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.

1
  • 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. Commented Mar 18, 2012 at 11:21

5 Answers 5

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?)

Sign up to request clarification or add additional context in comments.

16 Comments

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
@AnthonyDo Have you read the other answers? They explain how to do this, and indeed how to avoid traversing the entire a-z range.
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.
"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.
@AnthonyDo: (1) stackoverflow have its own chat, 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.
|
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')

Comments

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.

Comments

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!).

Comments

-1

for python 2.7 and higher:

[ Solution in previous version of question ]

1 Comment

Don't do students' homework for them. In addition, this version is sub-optimal.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.