Section #3 Solutions

October 4th, 2020


Written by Brahm Capoor, Juliette Woodrow, Parth Sarin, Kara Eng, Tori Qiu and Peter Maldonado

Parameters Review

Checking Ranges

        
def in_range(n, low, high):
    """
    Returns True if n is between low and high, inclusive.
    high is guaranteed to be greater than low.
    """
    if n >= low and n <= high:
        return True
    # we don't need an else statement here because
    # returning True would have ended the function
    # early
    return False


def in_range(n, low, high):
    """
    A clever alternative solution that leverages the fact that 
    we're computing a boolean expression anyway
    """
    return n >= low and n <= high


def main():
    num_1 = int(input("Enter first number: "))
    num_2 = int(input("Enter second number: "))
    num_3 = int(input("Enter third number: "))

    if in_range(num_2, num_1, num_3) or in_range(num_2, num_3, num_1):
        print(str(num_2) + " is in between " +
              str(num_1) + " and " + str(num_3))
    else:
        print(str(num_2) + " is not in between " +
              str(num_1) + " and " + str(num_3))


if __name__ == "__main__":
    main()
        
      

FizzBuzz

        
def fizzbuzz(n):
    count = 0
    for i in range(1, n + 1):
        if i % 15 == 0:
            count += 1
            print("Fizzbuzz")
        elif i % 3 == 0:
            count += 1
            print("Fizz")
        elif i % 5 == 0:
            count += 1
            print("Buzz")
        else:
            print(i)
    return count


def main():
    num = int(input("Number to count to: "))
    count = fizzbuzz(num)
    print(str(count) + " numbers were fizzed or buzzed")


if __name__ == "__main__":
    main()

        
      

Medical Test Simulator

        

import random


def simulate_tests(num_people, test_accuracy, infection_rate):

    true_positives = 0
    false_positives = 0
    false_negatives = 0
    true_negatives = 0

    for i in range(num_people):
        is_sick = random.random() < infection_rate
        test_is_correct = random.random() < test_accuracy

        if is_sick:
            if test_is_correct:
                true_positives += 1
            else:
                false_negatives += 1
        else:
            if test_is_correct:
                true_negatives += 1
            else:
                false_positives += 1

    print("True positives: " + str(true_positives))
    print("False positives: " + str(false_positives))
    print("False negatives: " + str(false_negatives))
    print("True negatives: " + str(true_negatives))

    return false_positives / (false_positives + true_positives)


def main():
    num_people = int(input("Number of people: "))
    test_accuracy = float(input("Test accuracy: "))
    infection_rate = float(input("Infection rate: "))

    positive_tests_incorrect = simulate_tests(
        num_people, test_accuracy, infection_rate)

    print(str(positive_tests_incorrect * 100) +
          "% of positive tests were incorrect")


if __name__ == "__main__":
    main()

        
    

Lists Review

Collapse

  
def collapse(nums):
  result = []
  for i in range(len(nums)//2):
    # since we're going pairs at a time, we only need
    # to go as many as times as half the number of elements
    result.append(nums[i * 2] + nums[i * 2 + 1])

  if len(nums) % 2 == 1:
    result.append(nums[-1])
  return result
  

Rotate

        
def right_list_right(numbers, num):
    output_list = []
    
    for i in range(len(numbers) - num, len(numbers)):
      output_list.append(numbers[i])
    
    for i in range(0, len(numbers) - num):
      output_list.append(numbers[i])
    
    return output_list
        
      

Images

Double Left

          
def double_left(filename):
    """
    Takes the left half of image, and copies it on top of the right half.
    """
    image = SimpleImage(filename)
    mid_x = image.width // 2
    for y in range(image.height):
        for x in range(mid_x):
            pixel = image.get_pixel(x, y)
            pixel_right = image.get_pixel(mid_x + x, y)
            pixel_right.red = pixel.red
            pixel_right.green = pixel.green
            pixel_right.blue = pixel.blue
    image.show()
          
      

Squeeze Width

          
def squeeze_width(filename, n):
    image = SimpleImage(filename)
    out = SimpleImage.blank(width=image.width // n, height=image.height)
    for y in range(out.height):
        for x in range(out.width):
            pixel_out = out.get_pixel(x, y)
            pixel = image.get_pixel(x * n, y)

            pixel_out.red = pixel.red
            pixel_out.green = pixel.green
            pixel_out.blue = pixel.blue
    out.show()
          
      

Crop Image

          
def crop_image(filename, n):
    """
    Takes the left half of image, and copies it on top of the right half.
    """
    image = SimpleImage(filename)
    out = SimpleImage.blank(image.width - 2 * n, image.height - 2 * n)

    for y in range(out.height):
        for x in range(out.width):
            input_pixel = image.get_pixel(x + n, y + n)
            out.set_pixel(x, y, input_pixel)

    out.show()
          
      


Debugging with Doctests

Here's a fixed version of the program:

        
def greatest_common_divisor(a, b):
    """
    Return the greatest common divisor of a and b.

    >>> greatest_common_divisor(4, 16)
    4
    >>> greatest_common_divisor(16, 4)
    4
    >>> greatest_common_divisor(9, 24)
    3
    """
    if a < b:
        lower = a
    else:
        lower = b

    gcd = 1
    for i in range(1, lower + 1):
        if a % i == 0 and b % i == 0:
            gcd = i
    
    return gcd