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.
解决方案
Here is a simpler answer (by simpler I mean one-liner and no use of additional libraries) -
q=["hi", "sky"]
p=["here","sky","sky","sky","sky"]
def count_words(q,p):
return [ p.count(i) for i in q ]
print(count_words(q,p))
Output
[0, 4]
Explanation
[ p.count(i) for i in q ] is a list comprehension which is like iterating through the q list on the fly and counting for the respective elements in p
Timings (depends on the data)
# My solution
1.78 µs ± 214 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
# @Delirious Solution 1
7.55 µs ± 1.58 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
# @ Delirious Solution 2
3.86 µs ± 348 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)