#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Felix Muzny 10/18/2022 DS 2000 Lecture 12 - functions and optional parameters, functions and functions as parameters, if __name__ == __main__, dictionaries Logistics: - Homework 5 is due this Friday 10/21 @ 9pm - Quiz 6 is available - remote attendance (https://bit.ly/remote-ds2000-muzny) Three ways to participate (please do one of these!) 1) via the PollEverywhere website: https://pollev.com/muzny 2) via text: text "muzny" to the number 22333 to join the session 3) via Poll Everywhere app (available for iOS or Android) Warm-up 1 - --- Write two different good, working function calls for the given generate_list function. """ import random # this example has no positinal parameters def generate_list(lower = 1, upper = 9): """ Generate a list of length 10 filled with random ints from a lower bound to an upper bound (1 - 9 by default). Parameters ---------- lower : int, optional Inclusive lower bound of integers to generate. The default is 1. upper : int, optional Inclusive upper bound of integers to generate. The default is 9. Returns ------- new_ls : list Generated list of ints. """ new_ls = [] for i in range(10): new_ls.append(random.randint(lower, upper)) return new_ls """ Warm-up 2 - passing functions as parameters --- Write down two good, working function calls for the given list_info function and one bad, non-working function call """ def list_info(ls, func): print(func(ls)) numbers = [1, 2, 5, 6, 17] data = [[1, 12], [23, 24], [35, 36]] """ Optional parameters --- Examples with python built-in functions. We always list positional (non-optional) parameters first. print("Here", "are", "words", sep="what to put in between") plt.plot(xs, ys, "o", color="red") Writing our own functions with an optional parameter --- General syntax: def function_name(positional, parameters, first, then = optional): # code Call the function as normal, but specify the values of any optional parameters that you send to the function. If a function takes both positional and optional parameters, they will be assigned in order if no optional names are specified. """ def person_info(name, likes_mushrooms = False, age = 10): print("Name", name) print("Likes mushrooms?", likes_mushrooms) print("Age", age) # example function calls """ Passing functions as parameters --- Using our function that we wrote from before (convert_int), write a new version that will convert everything from a list into a string. """ def convert_mutate(ls, cast = int): """ Converts all values in given list according to the given function. Changes to ints by default. Mutates the given list. Parameters ---------- ls : list list of values to be converted. cast : function, optional Function to be applied to every element in the list. The default is int. Returns ------- None. """ for i in range(len(ls)): ls[i] = cast(ls[i]) print("convert_mutate examples") my_floats = [43.2, 35.4, 1123.123] words = "This is a sentence".split() numbers = "1 12 12 3 12 57".split() """ Writing our own modules & if __name__ == "__main__": --- We've written a number of quite useful functions that are rather general purpose. For instance: in earnings_lec10.py, we had: (https://course.ccs.neu.edu/ds2000/felix_lectures/earnings_lec10.py) - read_data - get_column From lecture on Friday, we had a convert list function. These are all highly useful, very general data processing functions that I might not want to re-write every time I want to use them. Solution: write our own module! """ """ Dictionaries --- A dictionary is a *data structure*, similarly to lists. A dictionary links a *key* to a *value*. Examples: student emails -> graduation year words -> definitions words -> counts of how often they occur Keys: any immutable data type keys are *unique* Values: any data type values are not unique """ # Dictionary examples # Creating a dictionary # adding a key/value pair to a dictionary # updating a key/value pair in a dictionary # iterating through all values in a dictionary """ How is a list similar to a dictionary? --- """ # if time: create a dictionary of counts def count_words(text): """ Count each word in a given string Parameters ---------- text : str words separated by whitespace. Returns ------- dict of word counts. """ print("ro be implemented") test1 = "This is a sentence" test2 = "This is a longer test that has a second clause" """ Next time: - writing a larger program with dictionaries """