dis06_solutions

.pdf

School

University of California, Berkeley *

*We aren’t endorsed by this school

Course

8

Subject

Computer Science

Date

Feb 20, 2024

Type

pdf

Pages

4

Uploaded by CaptainFinch748

Report
Data 8 Fall 2023 Iteration, Conditionals Week 06 September 2023 Welcome to the Week 6 Discussion Worksheet! This week we will be discussing conditional statements and iteration, which are powerful computational tools that we will use throughout the course. Conditional statements allow data scientists to make more complex decisions with their code, while for loops allow us to repeat the same action many times. 1. Funky Function What does the mystery function do? Write a sentence below describing what the function’s inputs should be and what the function does. Hint: Try out the function on a few different inputs and see what happens! def mystery(n1, n2): if n2 - n1 > 0: return n2 - n1 elif n2 - n1 < 0: return n1 - n2 else: return 0 The function takes in two different numbers and computes the absolute difference between them. 1
2. Getting Even a. The % operator returns the remainder if you divide by a certain number (e.g. 11%5 = 1 ). If a number n is odd, what will n %2 return? 1. If a number is even, n %2 will return 0. b. The count evens function takes in an array of integers and returns the number of even integers in the array. Use a combination of iteration and conditionals to complete the skeleton code below. def count evens(n array): num evens = 0 for : if : return def count evens(n array): num evens = 0 for num in n array: if num % 2 == 0: num evens = num evens + 1 return num evens c. Now let’s see how we can write the same function using array operations instead of iteration. def count evens(n array): remainder array = return def count evens(n array): remainder array = n array % 2 return np.count nonzero(remainder array == 0) Alternate Solution: def count evens(n array): remainder array = n array % 2 return len(remainder array) - sum(remainder array) 2
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help