Anda di halaman 1dari 8

Learn Python Challenge: Day 4 Exercises | Kaggle

Search kaggle  Competitions Datasets Kernels Discussion Learn 

Bala 
0
Learn Python Challenge: Day 4 Exercises voters
L forked from Learn Python Challenge: Day 4 Exercises by ColinMorris (+0/–0)
last run a few seconds ago · IPython Notebook HTML
using data from LearnToolsPython ·  Public Make Private

Notebook Code Data (1) Comments (0) Log Versions (1) Forks Options Edit Notebook

 Your kernel is now public.

Tags Add Tag

Notebook

Welcome to the exercises for day 4 (these accompany the day 4 tutorial notebook on lists, available here)

As always be sure to run the setup code below before working on the questions (and if you leave this
notebook and come back later, don't forget to run the setup code again).

In [1]:
# SETUP. You don't need to worry for now about what this code does or how it works. If
you're ever curious about the
# code behind these exercises, it's available under an open source license here: https
://github.com/Kaggle/learntools/
import sys; sys.path.insert(0, '../input/learntools/pseudo_learntools')
from learntools.python import binder; binder.bind(globals())
from learntools.python.ex4 import *
print('Setup complete.')

Setup complete.

Exercises

https://www.kaggle.com/balaganabathy/learn-python-challenge-day-4-exercises?scriptVersionId=5517707[05-Sep-18 3:39:35 PM]


Learn Python Challenge: Day 4 Exercises | Kaggle

1.
Complete the function below according to its docstring.

In [2]:
def select_second(L):
"""Return the second element of the given list. If the list has no second
element, return None.
"""
if(len(L) > 1):
return L[1]
else:
return None
q1.check()

Correct

In [3]:
#q1.hint()
q1.solution()

Solution:

def select_second(L):
if len(L) < 2:
return None
return L[1]

2.
You are analyzing sports teams. Members of each team are stored in a list. The Coach is the first name in
the list, the captain is the second name in the list, and other players are listed after that. These lists are
stored in another list, which starts with the best team and proceeds through the list to the worst team last.
Complete the function below to select the captain of the worst team.

In [4]:
def losing_team_captain(teams):
"""Given a list of teams, where each team is a list of names, return the 2nd playe
r (captain)

https://www.kaggle.com/balaganabathy/learn-python-challenge-day-4-exercises?scriptVersionId=5517707[05-Sep-18 3:39:35 PM]


Learn Python Challenge: Day 4 Exercises | Kaggle

from the last listed team


"""
return (teams[-1])[1]

q2.check()

Correct

In [5]:
#q2.hint()
#q2.solution()

3.
The next iteration of Mario Kart will feature an extra-infuriating new item, the Purple Shell. When used, it
warps the last place racer into first place and the first place racer into last place. Complete the function below
to implement the Purple Shell's effect.

In [6]:
def purple_shell(racers):
"""Given a list of racers, set the first place racer (at the front of the list) to
last
place and vice versa.

>>> r = ["Mario", "Bowser", "Luigi"]


>>> purple_shell(r)
>>> r
["Luigi", "Bowser", "Mario"]
"""
temp = racers[0]
racers[0] = racers[-1]
racers[-1] = temp

q3.check()

Correct

In [7]:
#q3.hint()

https://www.kaggle.com/balaganabathy/learn-python-challenge-day-4-exercises?scriptVersionId=5517707[05-Sep-18 3:39:35 PM]


Learn Python Challenge: Day 4 Exercises | Kaggle

q3.solution()

Solution:

def purple_shell(racers):
# One slick way to do the swap is x[0], x[-1] = x[-1], x[0].
temp = racers[0]
racers[0] = racers[-1]
racers[-1] = temp

4.
What are the lengths of the following lists? Fill in the variable lengths with your predictions. (Try to make a
prediction for each list without just calling len() on it.)

In [8]:
a = [1, 2, 3]
b = [1, [2, 3]]
c = []
d = [1, 2, 3][1:]

# Put your predictions in the list below. Lengths should contain 4 numbers, the
# first being the length of a, the second being the length of b and so on.
lengths = [3,2,0,2]

q4.check()

Correct:

a: There are three items in this list. Nothing tricky yet.


b: The list [2, 3] counts as a single item. It has one item before it. So we have 2 items in the list
c: The empty list has 0 items
d: The expression is the same as the list [2, 3], which has length 2.

In [9]:
# line below provides some explanation
q4.solution()

https://www.kaggle.com/balaganabathy/learn-python-challenge-day-4-exercises?scriptVersionId=5517707[05-Sep-18 3:39:35 PM]


Learn Python Challenge: Day 4 Exercises | Kaggle

Solution:

a: There are three items in this list. Nothing tricky yet.


b: The list [2, 3] counts as a single item. It has one item before it. So we have 2 items in the list
c: The empty list has 0 items
d: The expression is the same as the list [2, 3], which has length 2.

5.
We're using lists to record people who attended our party and what order they arrived in. For example, the
following list represents a party with 7 guests, in which Adela showed up first and Ford was the last to arrive:

party_attendees = ['Adela', 'Fleda', 'Owen', 'May', 'Mona', 'Gilbert', 'Ford']

A guest is considered 'fashionably late' if they arrived after at least half of the party's guests. However, they
must not be the very last guest (that's taking it too far). In the above example, Mona and Gilbert are the only
guests who were fashionably late.

Complete the function below which takes a list of party attendees as well as a person, and tells us whether
that person is fashionably late.

In [10]:
def fashionably_late(arrivals, name):
"""Given an ordered list of arrivals to the party and a name, return whether the g
uest with that
name was fashionably late.
"""
if (name in arrivals):
return arrivals.index(name) >= (len(arrivals)/2) and arrivals.index(name) < (l
en(arrivals)-1)

q5.check()

Correct

In [11]:
#q5.hint()
q5.solution()

https://www.kaggle.com/balaganabathy/learn-python-challenge-day-4-exercises?scriptVersionId=5517707[05-Sep-18 3:39:35 PM]


Learn Python Challenge: Day 4 Exercises | Kaggle

Solution:

def fashionably_late(arrivals, name):


order = arrivals.index(name)
return order >= len(arrivals) / 2 and order != len(arrivals) - 1

6.
This question is intended more as a fun riddle than a test of your programming prowess :)

Implement the body of the following function using only tools we've covered so far - NO LOOPS!

In [12]:
def count_negatives(nums):
"""Return the number of negative numbers in the given list.

>>> count_negatives([5, -1, -2, 0, 3])


2
"""
# Equivalent to "if len(nums) == 0". An empty list is 'falsey'.
if not nums:
return 0
else:
# Implicitly converting a boolean to an int! See question 6 of the day
# 3 exercises.
return (nums[0] < 0) + count_negatives(nums[1:])

q6.check()

Correct:

Here's a non-obvious solution using only tools shown in the tutorial notebook:

def count_negatives(nums):
nums.append(0)
# We could also have used the list.sort() method, which modifies a list, putting
it in sorted order.
nums = sorted(nums)
return nums.index(0)

The above implementation relies on the fact that list.index returns the index of the first occurrence of a

https://www.kaggle.com/balaganabathy/learn-python-challenge-day-4-exercises?scriptVersionId=5517707[05-Sep-18 3:39:35 PM]


Learn Python Challenge: Day 4 Exercises | Kaggle

value. (You can verify this by calling help(list.index) .) So if, after sorting the list in ascending order, the
value 0 is at index 0, then the number of negatives is 0. If 0 is at index 2 (i.e. the third element), then there are
two elements smaller than 0. And so on.

Note: it's usually considered "impolite" to modify a list that someone passes to your function without giving them
some warning (i.e. unless the docstring says that it modifies its input). So, if we wanted to be nice, we could
have started by making a copy of nums using the list.copy() method (e.g. our_nums = nums.copy() ),
and then working with that copy rather than the original.

If you're a big Lisp fan (and based on the pre-challenge survey I know there's at least one of you out there!) you
might have written this technically compliant solution (we haven't talked about recursion, but I guess this doesn't
use any syntax or functions we haven't seen yet...):

def count_negatives(nums):
# Equivalent to "if len(nums) == 0". An empty list is 'falsey'.
if not nums:
return 0
else:
# Implicitly converting a boolean to an int! See question 6 of the day
# 3 exercises.
return (nums[0] < 0) + count_negatives(nums[1:])

In [13]:
#q6.hint()

In [14]:
#q6.solution()

That's it for today! If you have any questions or feedback (or just want to argue about whether Pluto should
be a planet), head over to the forums.

Remember that your notebook is private by default. To share it with other people or ask for help with it, you'll
need to make it public. First, you'll need to save a version of your notebook that shows your current work by
hitting the "Commit & Run" button. (Your work is saved automatically, but versioning your work lets you go
back and look at what it was like at the point you saved it. It also let's you share a nice compiled notebook
instead of just the raw code.) Then, once your notebook is finished running, you can go to the Settings tab in
the panel to the left (you may have to expand it by hitting the [<] button next to the "Commit & Run" button)
and setting the "Visibility" dropdown to "Public".


Did you find this Kernel useful?

https://www.kaggle.com/balaganabathy/learn-python-challenge-day-4-exercises?scriptVersionId=5517707[05-Sep-18 3:39:35 PM]


Learn Python Challenge: Day 4 Exercises | Kaggle

Show your appreciation with an upvote


0

Comments (0)Sort by Select...

Click here to enter a


comment

© 2018 Kaggle Inc Our Team


Terms
Privacy
Contact/Support


https://www.kaggle.com/balaganabathy/learn-python-challenge-day-4-exercises?scriptVersionId=5517707[05-Sep-18 3:39:35 PM]

Anda mungkin juga menyukai