joelgrus / data-science-from-scratch

code for Data Science From Scratch book
MIT License
8.63k stars 4.5k forks source link

Missing code of the introduction chapter #41

Open JBPressac opened 7 years ago

JBPressac commented 7 years ago

Hello, The following code is not present at the end of the FINDING KEY CONNECTORS section of https://github.com/joelgrus/data-science-from-scratch/blob/master/code/introduction.py:

num_friends_by_id = [(user["id"], number_of_friends(user)) for user in users]
sorted(num_friends_by_id,
       key= lambda (user_id, num_friends): num_friends,
       reverse=True)

For the Python 3 version, I propose the following solution to take the PEP 3113 into account:

num_friends_by_id = [(user["id"], number_of_friends(user)) for user in users]
sorted(num_friends_by_id,
       key= lambda userid_numfriends: userid_numfriends[1],
       reverse=True)
PETOLI commented 5 years ago

What exactly does the "key= lambda userid_numfriends: userid_numfriends[1]" section of the sorted code line do? It generates the correct output (according to the sample output in the text) but I'm lost as to how it computes it? Thanks!

rafaelmorais85 commented 5 years ago

It works perfectly for me!

sobanjawaid26 commented 4 years ago

This is due to the versions of python, the code in book is in version 2. The code mentioned by @JBPressac for version 3 works perfectly.

Karlosprado commented 3 years ago

muito obrigado pela ajuda!

Zahed-Golabi commented 1 year ago

What exactly does the "key= lambda userid_numfriends: userid_numfriends[1]" section of the sorted code line do? It generates the correct output (according to the sample output in the text) but I'm lost as to how it computes it? Thanks!

The sorted function asks how to sort the list! Well we wanna sort the list which each element is a tuple (each element of the list is a tuple of two values). The key parameter wants to know by which value of the tuple the sorted function should work, so with the lambda expression we say that each element of the list is a tuple (x is a tuple so we can sort it with x[0] or x[1]) and sort it with the second value of the tuple.