0
genres_list = ['rock', 'pop', 'folk', 'dance', 'rusrap', 'ruspop', 'world', 'electronic', 'alternative', 'children', 'rnb', 'hip', 'jazz','postrock', 'latin', 'classical', 'metal', 'reggae', 'tatar','blues','pop', 'jazz']

# write function to count the number of specific genre in genres_list 

def find_genre(genre):
    count=0
    for count in genres_list:
        if count == genre:
            count=count+1
    return count

number=find_genre(pop)
print(number)

output:

TypeError: can only concatenate str (not "int") to str

2
  • 2
    This line for count in genres_list: makes count a string. Commented Feb 7, 2020 at 20:39
  • 1
    And when you fix that, this line number=find_genre(pop) will show a next error. Commented Feb 7, 2020 at 20:41

4 Answers 4

3

Try this. list has a method to count the number occurences of an element.

genres_list = ['rock', 'pop', 'folk', 'dance', 'rusrap', 'ruspop', 'world', 'electronic', 'alternative', 'children', 'rnb', 'hip', 'jazz','postrock', 'latin', 'classical', 'metal', 'reggae', 'tatar','blues','pop', 'jazz']

print(genres_list.count('pop'))

output

2

list.count() complexity is O(n).

You can write your own count function.

def find_genre(genre):
    count=0
    for _genre in genres_list:
        if _genre==genre:
            count+=1
    return count

print(find_genre('pop'))
#2

timeit analysis over a list of size 2 million. Results as of this writing (python 3.7, windows 10)

In [38]: timeit genres_list.count('pop') #My answer
26.6 ms ± 939 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [40]: timeit Counter(genres_list)['pop'] #Pitto's answer using collections.Counter
92.5 ms ± 751 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

Now, custom count function everyone suggested including me.

def find_genre(genre):
    count=0
    for _genre in genres_list:
        if _genre==genre:
            count+=1
    return count

In [42]: timeit find_genre('pop')
63.9 ms ± 803 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

Just for the sake of comparison(Which I don't recommend using) I wrote some other functions to calculate count.

In [36]: timeit sum(list(map(lambda x:x=='pop',genres_list)))
334 ms ± 13.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [37]: timeit len(list(filter(lambda x:x=='pop',genres_list)))
188 ms ± 18.3 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [44]: timeit ' '.join(genres_list).count('pop')
41.5 ms ± 2.6 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Error occurred in your code because you use count for calculating the count of a genre and again you used count as a looping variable. In every iteration count becomes a str and we can't add str to a int type.

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

2 Comments

@Ch3steR: Might it be that the timeit comparison is not really fair? As in this case, the creation of the Counter() element is fairly expensive as it hashes over all elements (i guess it does something like counts = {element: element_list.count(element) for element in set(element_list)} only optimized to O(n)) which is slow at the creation but then as O(1) for the count lookup?
@BStadlbauet Counter takes O(n) to build. Think of it this way every time a new key is encountered it's value corresponding to key is set to 1. If the key is already in present increase its count by 1. The time complexity is O(n). And to check if a key is present or not takes constant time O(1).
2

I would use Counter to achieve this result:

import collections

genres_list = ['rock', 'pop', 'folk', 'dance', 'rusrap', 'ruspop', 'world', 'electronic', 'alternative', 'children', 'rnb', 'hip', 'jazz','postrock', 'latin', 'classical', 'metal', 'reggae', 'tatar','blues','pop', 'jazz']

counted = collections.Counter(genres_list)
print(counted['rock'])

Output
1

Another possible solution, if you specifically want to fix your current approach:

def find_genre(genre):
    count=0
    for current_genre in genres_list:
        if current_genre == genre:
            count=count+1
    return count

number=find_genre('pop')
print(number)

Output
2

Your main issue was that naming the for loop variable in the same way that you named the counter variable was confusing you (and was behaving differently too).

As pointed out in comment from Johnny Mop:

This line for count in genres_list: makes count a string.

1 Comment

Nice use of Counter as it calculates count of each element in O(n). +1 .
0

As Johnny Mopp already pointed out in the comments, for count in genres_list overwrites your count variable to be a string, so you could either do:

def find_genre(searched_genre):
    count=0
    for genre in genres_list:
        if searched_genre == genre:
            count = count+1
    return count

number = find_genre('pop')
print(number)

Or in a more pythonic way using list comprehension:

def find_genre(searched_genre):
    return len([genre for genre in genres_list if genre == searched_genre])

Or use a collection as @Pitto suggested (which might not be as intuitive when you first start programming)

4 Comments

Nice solution here, +1. If we want to be helping new programmers then I'd like to add that list comprehensions are not easy either :) (check it well because I think you are missing brackets)
Your pythonic way will not work unless you force a list comprehension with square brackets: len([...])
@Pitto: True that, it is probably also fairly slow compared to your collections.Counter() method!
@MatiasCicero: Thanks for the hint, you are right of course! I thought len() might be able to iterate over a generator, but just looked up that elements have to provide the __len__() dunder method
0

First, you're using the same variable name in your iteration as the index in your list.

Second, you should use apostrophes in the argument pop like this 'pop'.

Hope this helps:

genres_list = ['rock', 'pop', 'folk', 'dance', 'rusrap', 'ruspop', 'world', 'electronic', 'alternative', 'children', 'rnb', 'hip', 'jazz','postrock', 'latin', 'classical', 'metal', 'reggae', 'tatar','blues','pop', 'jazz']

# write function to count the number of specific genre in genres_list
def find_genre(genre):
    num=0
    for count in genres_list:
        if count == genre:
            num=num+1
    return num

number=find_genre('pop')
print(number)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.