Kaggle Challenge 04 - Booleans and Conditionals

JongseokLee·2021년 8월 7일
0
post-thumbnail

Kaggle Challenge 04 -Booleans and Conditionals

0. Comparison Operations

OperationDescriptionOperationDescription
a == ba equal to ba != ba not equal to b
a < ba less than ba > ba greater than b
a <= ba less than or equal to ba >= ba greater than or equal b

memorize the order of precedence

def f(x):
    if x > 0:
        print("Only printed when x is positive; x =", x)
        print("Also only printed when x is positive; x =", x)
    print("Always printed, regardless of x's value; x =", x)

f(1)
f(0)

<Result>

Only printed when x is positive; x = 1
Also only printed when x is positive; x = 1
Always printed, regardless of x's value; x = 1
Always printed, regardless of x's value; x = 0
print(bool(1)) # all numbers are treated as true, except 0
print(bool(0))
print(bool("asf")) # all strings are treated as true, except the empty string ""
print(bool(""))
# Generally empty sequences (strings, lists, and other types we've yet to see like lists and tuples)
# are "falsey" and the rest are "truthy"

<Result>

True
False
True
False

1. Question01

Many programming languages have sign available as a built-in function. Python doesn't, but we can define our own!
In the cell below, define a function called sign which takes a numerical argument and returns -1 if it's negative, 1 if it's positive, and 0 if it's 0.

Solution

def sign(x):
    if x > 0:
        return 1
    elif x < 0:
        return -1
    else:
        return 0

2. Question 02

2. We've decided to add "logging" to our to_smash function from the previous exercise.

def to_smash(total_candies):
    """Return the number of leftover candies that must be smashed after distributing
    the given number of candies evenly between 3 friends.
    
    >>> to_smash(91)
    1
    """
    print("Splitting", total_candies, "candies")
    return total_candies % 3

to_smash(91)

What happens if we call it with total_candies = 1?

to_smash(1)

That isn't great grammar!
Modify the definition in the cell below to correct the grammar of our print statement. (If there's only one candy, we should use the singular "candy" instead of the plural "candies")

Solution

Solution: A straightforward (and totally fine) solution is to replace the original print call with:

if total_candies == 1:
    print("Splitting 1 candy")
else:
    print("Splitting", total_candies, "candies")
Here's a slightly more succinct solution using a conditional expression:

print("Splitting", total_candies, "candy" if total_candies == 1 else "candies")

3. Question 03

To prove that prepared_for_weather is buggy, come up with a set of inputs where either:
the function returns False (but should have returned True), or
the function returned True (but should have returned False).
To get credit for completing this question, your code should return a Correct result.

def prepared_for_weather(have_umbrella, rain_level, have_hood, is_workday):
    # Don't change this code. Our goal is just to find the bug, not fix it!
    return have_umbrella or rain_level < 5 and have_hood or not rain_level > 0 and is_workday

# Change the values of these inputs so they represent a case where prepared_for_weather
# returns the wrong answer.
have_umbrella = True
rain_level = 0.0
have_hood = True
is_workday = True

# Check what the function returns given the current values of the variables above
actual = prepared_for_weather(have_umbrella, rain_level, have_hood, is_workday)
print(actual)

# Check your answer
q3.check()

Solution

Solution: One example of a failing test case is:

have_umbrella = False
rain_level = 0.0
have_hood = False
is_workday = False
Clearly we're prepared for the weather in this case. It's not raining. Not only that, it's not a workday, so we don't even need to leave the house! But our function will return False on these inputs.

The key problem is that Python implictly parenthesizes the last part as:

(not (rain_level > 0)) and is_workday
Whereas what we were trying to express would look more like:

not (rain_level > 0 and is_workday)

4. Question 04

The function is_negative below is implemented correctly - it returns True if the given number is negative and False otherwise.
However, it's more verbose than it needs to be. We can actually reduce the number of lines of code in this function by 75% while keeping the same behaviour.
See if you can come up with an equivalent body that uses just one line of code, and put it in the function concise_is_negative. (HINT: you don't even need Python's ternary syntax)

def is_negative(number):
    if number < 0:
        return True
    else:
        return False

def concise_is_negative(number):
    pass # Your code goes here (try to keep it to one line!)
    
    
# Check your answer
q4.check()

Solution

def concise_is_negative(number):
    return number < 0

5. Question 05a

The boolean variables ketchup, mustard and onion represent whether a customer wants a particular topping on their hot dog. We want to implement a number of boolean functions that correspond to some yes-or-no questions about the customer's order. For example:

def onionless(ketchup, mustard, onion):
    """Return whether the customer doesn't want onions.
    """
    return not onion
    
def wants_all_toppings(ketchup, mustard, onion):
    """Return whether the customer wants "the works" (all 3 toppings)
    """   

Solution

def wants_all_toppings(ketchup, mustard, onion):
    """Return whether the customer wants "the works" (all 3 toppings)
    """
    pass
    return ketchup and mustard and onion

5. Question 05b

def wants_plain_hotdog(ketchup, mustard, onion):
    """Return whether the customer wants a plain hot dog with no toppings.
    """
    pass

# Check your answer
q5.b.check()

Solution

return not ketchup and not mustard and not onion
We can also "factor out" the nots to get:

return not (ketchup or mustard or onion)

5. Question 05c

def exactly_one_sauce(ketchup, mustard, onion):
    """Return whether the customer wants either ketchup or mustard, but not both.
    (You may be familiar with this operation under the name "exclusive or")
    """

Solution

def exactly_one_sauce(ketchup, mustard, onion):
    """Return whether the customer wants either ketchup or mustard, but not both.
    (You may be familiar with this operation under the name "exclusive or")
    """
    pass
    return (ketchup and not mustard) or (mustard and not ketchup)

6. Question 06

We’ve seen that calling bool() on an integer returns False if it’s equal to 0 and True otherwise. What happens if we call int() on a bool? Try it out in the notebook cell below.
Can you take advantage of this to write a succinct function that corresponds to the English sentence "does the customer want exactly one topping?"?

def exactly_one_topping(ketchup, mustard, onion):
    """Return whether the customer wants exactly one of the three available toppings
    on their hot dog.
    """
    pass

# Check your answer
q6.check()

Solution

return (int(ketchup) + int(mustard) + int(onion)) == 1

#Fun fact: we don't technically need to call int on the arguments. Just by doing addition with booleans, Python implicitly does the integer conversion. So we could also write...

return (ketchup + mustard + onion) == 1

Vocabularies

be evaluated (as, by, on) ~로 평가된다.
succinct[a] 간단명료한, 간결한(=concise)
come up with ~을 생산하다, 제시(제안)하다, 찾아 내다
be implemented 실시되다. implement[VN] 시행하다.
verbose 췌언이 많음(장황하다)
equivalent[a] 동등한, (n)등가물, 상당(대응)하는 것
correspond[V] 일치하다, 부합하다, 상응(해당)하다 + to/whith sth
exclusive[a] 독점적인, 고가의, 전용의 exclusive of ~를 제외하고
convert[v] from sth into sth
be dealt 패를 받다. / to be dealt a good/bad hand 패가 잘/잘 안들어오다

profile
DataEngineer Lee.

0개의 댓글