Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>first, you should separate the dictionary that was passed in, and the dictionary that you are going to return.</p> <pre><code>def build_person_to_matches(d, name): ret = {} collect = 0 for books in d[name]: for person in d.keys(): if books in d[person]: collect += 1 ret[person] = collect return ret d = { 'Tom': ['fiction', 'documentary', 'science'], 'John': ['computer science', 'math'], 'Jack': ['science', 'computer science', 'math', 'chemistry'] } print build_person_to_matches(d, 'Jack') </code></pre> <p>Second, switch the order of the two for loops, and move the <code>collect = 0</code> line into the first loop.</p> <pre><code>def build_person_to_matches(d, name): ret = {} for person in d.keys(): collect = 0 for books in d[name]: if books in d[person]: collect += 1 ret[person] = collect return ret d = { 'Tom': ['fiction', 'documentary', 'science'], 'John': ['computer science', 'math'], 'Jack': ['science', 'computer science', 'math', 'chemistry'] } print build_person_to_matches(d, 'Jack') </code></pre> <p>Optionally, for the sake of readability, you may as well move the inner loop into its own function, to make it more obvious to the reader what is going on.</p> <pre><code>def how_many_genres_both_people_like(d, person_a, person_b): total = 0 for books in d[person_a]: if books in d[person_b]: total += 1 return total def build_person_to_matches(d, name): ret = {} for person in d.keys(): ret[person] = how_many_genres_both_people_like(d, name, person) return ret d = { 'Tom': ['fiction', 'documentary', 'science'], 'John': ['computer science', 'math'], 'Jack': ['science', 'computer science', 'math', 'chemistry'] } print build_person_to_matches(d, 'Jack') </code></pre> <p>Output:</p> <pre><code>{'John': 2, 'Jack': 4, 'Tom': 1} </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload