For example:
q=["hi", "sky"]
p=["here","sky","sky","sky","sky"]
What would the function be defined to get:
count_words(["hi", "sky"], ["here","sky","sky","sky","sky"])
[0, 4]
# answer where hi appears 0 times and sky appears 4 times
I started the code off like this:
def count_words(q, p):
count = 0
for word in q:
if q==p:
(q.count("hi"))
(q.count("sky"))
return count
I keep getting one value of 0, which accounts for q
, but I can't get a value for p
.
Or if you can't use
collections.Counter
for some reason:EDIT:
It looks like there should be some timings to "clear things up" about which solution is more efficient. Since @chrisz forgot to post his actual test code, I had to do it myself.
Unfortunately, Vivek's code took
11min 10sec
to run while mine took only46.5ms
.Here is a simpler answer (by simpler I mean one-liner and no use of additional libraries) -
Output
Explanation
[ p.count(i) for i in q ]
is a list comprehension which is like iterating through theq
list on the fly and counting for the respective elements inp
Timings (depends on the data)