Devolan
Devolan

Reputation: 21

How to count separate items in list from input

Making a simple program which responds to the user's inputs.

In the example, the input "I like math", would return the response "That's cool". I want the response to change if the user inputs two items from the list, for example "I like math and biology".

I decided to get this done by using the count function, but it always returns the value 0. What would I have to do to get the if response?

list = ["math", "physics", "biology", "computer science"]
favsub = input("What are your favorite subjects? \n")
favsub = favsub.lower()
favsub = favsub.split()
num = favsub.count(list)
if num == 2:
    print("Both?")
else
    print("That's cool")

The code above is a simplified example, if you want to see the actual code, I'll leave it in a google doc here.

Upvotes: 0

Views: 1818

Answers (3)

Chad Kennedy
Chad Kennedy

Reputation: 1736

You could make list and favsub sets instead, and the take the length of the intersection.

NOTE: This will only work if all the phrases in list and favsub are single words, without a space.

Upvotes: 2

user2390182
user2390182

Reputation: 73480

list.count(x) only counts a single element x. Of course, your list is not an element of favsub and it does not magically sum the counts of its elements. However, building on your approach, you can do the following, using sum:

favsub = input("...").lower()
# do not split, otherwise you can't count "computer science" 
num = sum(x in favsub for x in list)

Generally, you should not name variables list (or str, int, etc.) as it shadows built-in names.

Upvotes: 3

DeepSpace
DeepSpace

Reputation: 81654

Your approach is too naive. First you will have to tokenize the user input (what if the user inputs math,physics instead of math and physics? .split will not separate math from physics in this case).

Then you will need to call favsub.count with each memeber of list (which is a bad variable name by the way as it shadows the built-in list).

I will suggest another naive (but easier) approach. Forget about splitting and tokenizing the user input. Simply search each recognized subject and sum the results:

 subjects_list = ["math", "physics", "biology", "computer science"]
 favsub = input("What are your favorite subjects? \n")
 favsub = favsub.lower()
 count = 0
 for subject in subjects_list:
     if subject in favsub:
         count += 1
 print(count)

This is essentially the same as @schwobaseggl's answer but with an explicit counter.

Upvotes: 1

Related Questions