dis06_solutions
.pdf
keyboard_arrow_up
School
University of California, Berkeley *
*We aren’t endorsed by this school
Course
8
Subject
Computer Science
Date
Feb 20, 2024
Type
Pages
4
Uploaded by CaptainFinch748
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
Related Questions
Python only* Use recursive function*.
Define concentricCircles with 4 parameters
Use def to define concentricCircles with 4 parameters
here is the specification for concentricCircles function:
It draws a series of concentric circles, where the first parameter specifies the radius of the outermost circle, and the second parameter specifies the number of circles to draw. When viewed as nested rings, all rings should have the same thickness.
The third and fourth parameters specify an outer color and an other color, respectively. The outer color is used for the outermost circle, and then every other circle in to the center alternates between that color and the other color.
We will test both how many circles are drawn as well as whether the correct circles are drawn in the correct order.
Hint: Each function call frame only needs to draw a single circle.
Note that you must use the turtleBeads drawDot function to draw each circle
Do not use any kind of loop
Within the definition of…
arrow_forward
attached
Screenhot
plz
arrow_forward
Artificial Intelligence (Part - 1)
====================
The Towers of Hanoi is a famous problem for studying recursion in computer science and searching in artificial intelligence. We start with N discs of varying sizes on a peg (stacked in order according to size), and two empty pegs. We are allowed to move a disc from one peg to another, but we are never allowed to move a larger disc on top of a smaller disc. The goal is to move all the discs to the rightmost peg (see figure). To solve the problem by using search methods, we need first formulate the problem. Supposing there are K pegs and N disk.
(1) Propose a state representation for the problem?
arrow_forward
Artificial Intelligence (Part - 2)
====================
The Towers of Hanoi is a famous problem for studying recursion incomputer science and searching in artificial intelligence. We start with N discs of varying sizes on a peg (stacked in order according to size), and two empty pegs. We are allowed to move a disc from one peg to another, but we are never allowed to move a larger disc on top of a smaller disc. The goal is to move all the discs to the rightmost peg (see figure). To solve the problem by using search methods, we need first formulate the problem. Supposing there are K pegs and N disk.
(2) What is the size of the state space?
arrow_forward
For the def findOldestDog(DogAges) line from the code below: Define and explain the procedure’s name and purpose. Explain how the parameter sent to the function functionality of the procedure. Explain how the algorithm (your code segment) includes sequencing, selection, and iteration.
def inputValidate():
#read first name before while loop
name = input("Enter dog name or XXX to quit ").upper()
while name != "XXX":
if name == "" or name ==" ":
print("no name entered")
else:
print("Enter Dog Age")
age = int(input())
while age <= 0 or age > 20:
print("Error")
print("Enter Dog Age")
age = int(input())
DogAges.append(age)
mage = age * 7
PersonAges.append(mage)
DogName.append(name)
name = input("Enter dog name or XXX to quit ").upper()
return DogAges, PersonAges, DogName
def findOldestDog(DogAges):
print("")
index = 0
maxAge = DogAges[0]
while index < len(DogAges):
if DogAges[index] > maxAge:
maxAge = DogAges[index]
index = index +1
print('')
print ("Oldest dog age is " +…
arrow_forward
__4___. cS
arrow_forward
Python only** Use recursive function*
Define countBetween with 2 parameters
Use def to define countBetween with 2 parameters
thas two parameters: a starting number and an ending number, and counts up (i.e., prints consecutive integers) from the starting number to the ending number. If the numbers are the same, it just prints that number; if the ending number is lower than the starting number, it prints nothing.
Do not use any kind of loop
Within the definition of countBetween with 2 parameters, do not use any kind of loop.
Call countBetween
Within the definition of countBetween with 2 parameters, call countBetween in at least one place.
Python only** Use recursive function*
Define countThereAndBack with 2 parameters
Use def to define countThereAndBack with 2 parameters
after reaching the ending number, it also counts back down to the starting number. It accepts the same two parameters defining starting and ending numbers it should print nothing if the starting number is…
arrow_forward
Write these in Pseudocode
#1a – In pseudocode, write a call to a function that passes 1 Integer variable and 1 Integer array, and saves a Boolean value in return.
#1b – In pseudocode, write the function that accepts 1 Integer and 1 Integer array and returns a Boolean.
In the function, search the Integer array with a for-loop, and if the Integer parameter is found in the array, return false. If the Integer parameter is not found, return true.
#2a – In pseudocode, write a call to a module that passes 1 Integer variable, 1 Real variable, 1 String constant, and 1 String literal as arguments.
#2b – In pseudocode, write the module header that accepts 1 Integer, 1 Real, and 2 Strings as parameters.
#3 – This pseudocode has multiple problems. Fix the calling statement and the definition below so that the routine accepts 3 grades as parameters and returns the average into a variable.…
arrow_forward
CodeW
For fun X C Solved
https://codeworkou...
臺亂
CodeWorkout
X272: Recursion Programming Exercise: Is
Reverse
For function isReverse, write the two missing base case conditions. Given two strings, this
function returns true if the two strings are identical, but are in reverse order. Otherwise it
returns false. For example, if the inputs are "tac" and "cat", then the function should return true.
Examples:
isReverse("tac", "cat") -> true
Your Answer:
1 public boolean isReverse(String s1, String s2) {
2.
if >
3.
4.
else if >
return true;
return false;
5.
6.
else {
String s1first =
String s2last
return s1first.equals (s2last) &&
51. substring(0, 1);
s2, substring(s2.length() 1);
7.
8.
6.
isReverse(s1.substring(1), s2.substring(0, s2.length() 1));
{
12}
1:11AM
50°F Clear
12/4/2021
arrow_forward
Task using C language
One common way of verifying if the data integrity of a file was preserved during a copy or transmission is to verify if the checksum matches. The checksum is a small piece of data computed from the original data. Your task is to compute a recursive function that maps an integer into a single digit to be used as checksum. Given an input integer in the range from 0 to 1012, the checksum is the sum of the digits of the input number. While the resulting sum has multiple digits, the checksum will be the sum of its digits instead. For instance:
if the input is 34, the checksum is 7 (3+4);
if the input is 99, the sum of its digits is 18 (9+9), so the checksum is 9 (1+8);
if the input is 99999999999, the sum of its digits is 99 (9+9+9+9+9+9+9+9+9+9+9), whose sum of digits is 18 (9+9), so the checksum is 9 (1+8).
Requirements
Follow the format of the examples below.
Make sure your variables and parameters have the correct data types.
You must implement a recursive…
arrow_forward
Course: Algorithm
Project: We will use the defintion of of n-Queens Problem from the chapter Backtracking.
In this project you need to describe Problem and Algorithm and Indicate input and output clearly.
Analyze and prove the time complexity of your algorithm.
Implement the algorithm using backtracking(including writing testing case).illustrate key functions with comments indicating: What it does, what each parameter is used for, how it handles errors etc. Indicate the testing scenarios and testing the results in a clear way. Make sure source is commented appropriately and structured well.
arrow_forward
In this chapter, the rules given for calculating the factorial of a number are as follows:If n = 0 then factorial(n) = 1If n . 0 then factorial(n) = n × factorial(n – 1)If you were designing a function from these rules, what would the base case be? What wouldthe recursive case be?
arrow_forward
Python only* Use recursive function*.
Define colorListCircles with 2 parameters
Use def to define colorListCircles with 2 parameters
The colorListCircles function must draw concentric circles using colors from a list. It has two parameters: the first specifies the radius of the largest circle, and the second is a list of colors. The number of concentric circles drawn is the length of the list, and these circles are colored, from largest to smallest, by the colors in the list from first to last. When viewed as nested rings, all rings should have the same thickness. If the list is empty, nothing should be drawn.
We will test both how many circles are drawn as well as whether the correct circles are drawn in the correct order, you may not use any loops and you must use recursion. Also, you will still need to use drawDot.
For full credit, your function should call drawDot in only one place, and should only contain one recursive call.
Do not use any kind of loop
Within the definition…
arrow_forward
haskell is the programming language
arrow_forward
Recursion in programming is described as when a function/method makes a direct or indirect call to itself. Which of the features is not valid for a recursive function.
Select one:
a.
The Recursive calls can be more then one
b.
The Recursive Call – the function calls itself with an input which is a step closer to the stop condition
c.
The Stoping Conditions can be more than one
d.
The Recursive call is optional.
e.
A Stop Condition – the function returns a value when a certain condition is satisfied, without a further recursive call
arrow_forward
Choose the correc answer in the question below.
arrow_forward
Which of the basic data structures is the most suitable if you only need to implement recursion in a programming language? When you make a recursive call, you need to save the function you are currently in and its parameters values in some data structure, so that when you go out of the recursion you can restore the state. When you go out of the recursive call, you will always need to extract the last element that was put in the data structure.
A. Queue
B. Stack
arrow_forward
Task 06: Use the recursive definition of Fibonacci series and write a function int fib(int
n) that returns Fa (nth element of Fibonacci series). For example, if n= 0, then fib() should
return 0. If n = 1, then it should return 1. For n> 1, it should return Fn-1 + Fn-2
hint: If n is 8, the function should return 21 (that is 8th element in sequence below).
0, 1, i, 2, 3, 5, 8, 13, 21, 34
arrow_forward
True/False 6. A sequence can be viewed as a recursive data collection.
arrow_forward
Please solve
arrow_forward
Q1: A positive integer is entered through the keyboard, write a function to display the Fibonacci series upto ‘n’ positive integer
(1) Without using recursion
(2) Using recursion .
Q2: To fully define a variable one needs to mention not only its ‘type’ but also its ‘other properties’. In other words, not only do all variables have a data type, they also contain other properties. Explain the concept that will help us to describe the properties of any variable.
arrow_forward
Perform in C#
arrow_forward
How much storage and processing power does % say recursive functions need?
arrow_forward
Implement the Function has_error
Implement the function according to the specification. Use the test script testcurrency.py to aid your development before checking your answer below. CANNOT USE IF/CONDITIONAL STATEMENTS Instead, you should use what you know about boolean expressions
def has_error(json):"""Returns True if the response to a currency query encountered an error.
Given a JSON string provided by the web service, this function returns True if thequery failed and there is an error message. For example, if the json is '{"success":false,"src":"","dst":"","error":"Source currency code is invalid."}'
then this function returns True (It does NOT return the error message'Source currency code is invalid'). On the other hand if the json is '{"success": true, "src": "2 United States Dollars", "dst": "1.772814 Euros", "error": ""}'
then this function returns False.
The web server does NOT specify the number of spaces after the colons. The JSON '{"success":true, "src":"2 United…
arrow_forward
SEE MORE QUESTIONS
Recommended textbooks for you
C++ Programming: From Problem Analysis to Program...
Computer Science
ISBN:9781337102087
Author:D. S. Malik
Publisher:Cengage Learning
Related Questions
- Python only* Use recursive function*. Define concentricCircles with 4 parameters Use def to define concentricCircles with 4 parameters here is the specification for concentricCircles function: It draws a series of concentric circles, where the first parameter specifies the radius of the outermost circle, and the second parameter specifies the number of circles to draw. When viewed as nested rings, all rings should have the same thickness. The third and fourth parameters specify an outer color and an other color, respectively. The outer color is used for the outermost circle, and then every other circle in to the center alternates between that color and the other color. We will test both how many circles are drawn as well as whether the correct circles are drawn in the correct order. Hint: Each function call frame only needs to draw a single circle. Note that you must use the turtleBeads drawDot function to draw each circle Do not use any kind of loop Within the definition of…arrow_forwardattached Screenhot plzarrow_forwardArtificial Intelligence (Part - 1) ==================== The Towers of Hanoi is a famous problem for studying recursion in computer science and searching in artificial intelligence. We start with N discs of varying sizes on a peg (stacked in order according to size), and two empty pegs. We are allowed to move a disc from one peg to another, but we are never allowed to move a larger disc on top of a smaller disc. The goal is to move all the discs to the rightmost peg (see figure). To solve the problem by using search methods, we need first formulate the problem. Supposing there are K pegs and N disk. (1) Propose a state representation for the problem?arrow_forward
- Artificial Intelligence (Part - 2) ==================== The Towers of Hanoi is a famous problem for studying recursion incomputer science and searching in artificial intelligence. We start with N discs of varying sizes on a peg (stacked in order according to size), and two empty pegs. We are allowed to move a disc from one peg to another, but we are never allowed to move a larger disc on top of a smaller disc. The goal is to move all the discs to the rightmost peg (see figure). To solve the problem by using search methods, we need first formulate the problem. Supposing there are K pegs and N disk. (2) What is the size of the state space?arrow_forwardFor the def findOldestDog(DogAges) line from the code below: Define and explain the procedure’s name and purpose. Explain how the parameter sent to the function functionality of the procedure. Explain how the algorithm (your code segment) includes sequencing, selection, and iteration. def inputValidate(): #read first name before while loop name = input("Enter dog name or XXX to quit ").upper() while name != "XXX": if name == "" or name ==" ": print("no name entered") else: print("Enter Dog Age") age = int(input()) while age <= 0 or age > 20: print("Error") print("Enter Dog Age") age = int(input()) DogAges.append(age) mage = age * 7 PersonAges.append(mage) DogName.append(name) name = input("Enter dog name or XXX to quit ").upper() return DogAges, PersonAges, DogName def findOldestDog(DogAges): print("") index = 0 maxAge = DogAges[0] while index < len(DogAges): if DogAges[index] > maxAge: maxAge = DogAges[index] index = index +1 print('') print ("Oldest dog age is " +…arrow_forward__4___. cSarrow_forward
- Python only** Use recursive function* Define countBetween with 2 parameters Use def to define countBetween with 2 parameters thas two parameters: a starting number and an ending number, and counts up (i.e., prints consecutive integers) from the starting number to the ending number. If the numbers are the same, it just prints that number; if the ending number is lower than the starting number, it prints nothing. Do not use any kind of loop Within the definition of countBetween with 2 parameters, do not use any kind of loop. Call countBetween Within the definition of countBetween with 2 parameters, call countBetween in at least one place. Python only** Use recursive function* Define countThereAndBack with 2 parameters Use def to define countThereAndBack with 2 parameters after reaching the ending number, it also counts back down to the starting number. It accepts the same two parameters defining starting and ending numbers it should print nothing if the starting number is…arrow_forwardWrite these in Pseudocode #1a – In pseudocode, write a call to a function that passes 1 Integer variable and 1 Integer array, and saves a Boolean value in return. #1b – In pseudocode, write the function that accepts 1 Integer and 1 Integer array and returns a Boolean. In the function, search the Integer array with a for-loop, and if the Integer parameter is found in the array, return false. If the Integer parameter is not found, return true. #2a – In pseudocode, write a call to a module that passes 1 Integer variable, 1 Real variable, 1 String constant, and 1 String literal as arguments. #2b – In pseudocode, write the module header that accepts 1 Integer, 1 Real, and 2 Strings as parameters. #3 – This pseudocode has multiple problems. Fix the calling statement and the definition below so that the routine accepts 3 grades as parameters and returns the average into a variable.…arrow_forwardCodeW For fun X C Solved https://codeworkou... 臺亂 CodeWorkout X272: Recursion Programming Exercise: Is Reverse For function isReverse, write the two missing base case conditions. Given two strings, this function returns true if the two strings are identical, but are in reverse order. Otherwise it returns false. For example, if the inputs are "tac" and "cat", then the function should return true. Examples: isReverse("tac", "cat") -> true Your Answer: 1 public boolean isReverse(String s1, String s2) { 2. if > 3. 4. else if > return true; return false; 5. 6. else { String s1first = String s2last return s1first.equals (s2last) && 51. substring(0, 1); s2, substring(s2.length() 1); 7. 8. 6. isReverse(s1.substring(1), s2.substring(0, s2.length() 1)); { 12} 1:11AM 50°F Clear 12/4/2021arrow_forward
- Task using C language One common way of verifying if the data integrity of a file was preserved during a copy or transmission is to verify if the checksum matches. The checksum is a small piece of data computed from the original data. Your task is to compute a recursive function that maps an integer into a single digit to be used as checksum. Given an input integer in the range from 0 to 1012, the checksum is the sum of the digits of the input number. While the resulting sum has multiple digits, the checksum will be the sum of its digits instead. For instance: if the input is 34, the checksum is 7 (3+4); if the input is 99, the sum of its digits is 18 (9+9), so the checksum is 9 (1+8); if the input is 99999999999, the sum of its digits is 99 (9+9+9+9+9+9+9+9+9+9+9), whose sum of digits is 18 (9+9), so the checksum is 9 (1+8). Requirements Follow the format of the examples below. Make sure your variables and parameters have the correct data types. You must implement a recursive…arrow_forwardCourse: Algorithm Project: We will use the defintion of of n-Queens Problem from the chapter Backtracking. In this project you need to describe Problem and Algorithm and Indicate input and output clearly. Analyze and prove the time complexity of your algorithm. Implement the algorithm using backtracking(including writing testing case).illustrate key functions with comments indicating: What it does, what each parameter is used for, how it handles errors etc. Indicate the testing scenarios and testing the results in a clear way. Make sure source is commented appropriately and structured well.arrow_forwardIn this chapter, the rules given for calculating the factorial of a number are as follows:If n = 0 then factorial(n) = 1If n . 0 then factorial(n) = n × factorial(n – 1)If you were designing a function from these rules, what would the base case be? What wouldthe recursive case be?arrow_forward
arrow_back_ios
SEE MORE QUESTIONS
arrow_forward_ios
Recommended textbooks for you
- C++ Programming: From Problem Analysis to Program...Computer ScienceISBN:9781337102087Author:D. S. MalikPublisher:Cengage Learning
C++ Programming: From Problem Analysis to Program...
Computer Science
ISBN:9781337102087
Author:D. S. Malik
Publisher:Cengage Learning