famguy74 famguy74 - 1 month ago 6
Python Question

Fixing return format for my function

The code for my function works correctly, but it is not returning the function in the format I would like. The function counts seed values in a 2nd sequence and then is supposed to return the seed counts as a list of integers. It is returning the seed counts but on separate lines rather then in a list. Here is my code and what its returning in command prompt.

def count_each(seeds,xs):
for c in seeds:
count=0
for d in xs:
if c==d:
count=count+1
print ([count])


count_each([10,20],[10,20,30,10])

count_each([4,8],[1,2,4,4,4,8,8,10])

In command prompt, I would like this function to print [2,1] for count_each([10,20],[10,20,30,10]) and [3,2] for count_each([4,8],[1,2,4,4,4,8,8,10]) but instead it is printing each seed value on its own line like so

http://i.stack.imgur.com/vXAd3.png

In the picture above it prints [2], [1], [3], and [2] on separate lines when it should instead print just two lines of [2,1] and [3,2] for the two sequences. How can I have the function return the seed values for each sequence as a list instead of having the values on separate lines.

Edit: I need to accomplish this without importing from other modules and with the simplest code possible.

Answer

You are almost done, but if you want to print the output in a list you must first create list.Here try this:

def count_each(seeds,xs):
    output = []
    for c in seeds:
        count=0
        for d in xs:
            if c==d:
                count=count+1
        output.append(count)
    print (output)