WEEK 3:: PYTHON CRASH COURSE : LOOPS, WHILE LOOPS

¡Supera tus tareas y exámenes ahora con Quizwiz!

In math, the factorial of a number is defined as the product of an integer and all the integers below it. For example, the factorial of four (4!) is equal to 1*2*3*4=24. Fill in the blanks to make the factorial function return the right number.

def factorial(n): result = 1 for i in range(1, n+1): result *= i return result

How are while loops and for loops different in Python?

While loops iterate while a condition is true. For loops iterate through a sequence of elements

What are while loops in Python?

While loops let the computer execute a set of instruction while the condition is true (Using while loops we can keep executing the same group of instructions until the condition stops being true.)

Write a script that prints the multiples of 7 between 0 and 100. Print one multiple per line and avoid printing any numbers that aren't multiples of 7. Remember that 0 is also a multiple of 7.

for i in range(0,100,7): print(i)

Write a script that prints the first 10 cube numbers (x**3), starting with x=1 and ending with x=10.

for x in range(1,11): print(x**3)

How many times will "Not there yet" be printed? x = 0 while x < 5: print("Not there yet, x=" + str(x)) x = x + 1 print("x=" + str(x))

5 (The variable x starts at 0 and gets incremented once per iteration, so there are 5 iterations for which x is smaller than 5.)

Which of these activities are good use cases for recursive programs? Check all that apply.

Going through a file system collecting information related to directories and files. (Because directories can contain subdirectories that can contain more subdirectories, going through these contents is a good use case for a recursive program.) Managing permissions assigned to groups inside the company, when each group can contain both subgroups and users. (As the groups can contain both groups and users, this is the kind of problem that is a great use case for a recursive solution.)

RECURSIVE: What is recursion used for?

Recursion lets us tackle complex problems by reducing the problem to a simples one .

RECURSIVE: Which of the following scenarios would benefit the most from using a recursive function to solve the problem?

You need to create a family tree, showing several generations of your ancestors, with all of their children. (You're getting the concept of recursion and when it's a better solution than the traditional looping techniques.)

n this code, there's an initialization problem that's causing our function to behave incorrectly. Can you find the problem and fix it? def count_down(start_number): while current > 0: print (current) current -= 1 print ("Zero!") count_down(3)

def count_down(current): while current > 0: print (current) current -= 1 print ("Zero!") count_down(3)

The count_users function recursively counts the amount of users that belong to a group in the company system, by going through each of the members of a group and if one of them is a group, recursively calling the function and counting the members. But it has a bug! Can you spot the problem and fix it?

def count_users(group): count = 0 for member in get_members(group): count += 1 if is_group(member): count -=1 count += count_users(member) return count ------------------------------------------- print(count_users("sales")) # Should be 3 print(count_users("engineering")) # Should be 8 print(count_users("everyone")) # Should be 18

Fill in the blanks to make the factorial function return the factorial of n. Then, print the first 10 factorials (from 0 to 9) with the corresponding number. Remember that the factorial of a number is defined as the product of an integer and all integers before it. For example, the factorial of five (5!) is equal to 1*2*3*4*5=120. Also recall that the factorial of zero (0!) is equal to 1.

def factorial(n): result = 1 for x in range(1,n): result = result * x return result for n in range(0,10): print(n, factorial(n+1))

Fill in the blanks to make the is_power_of function return whether the number is a power of the given base. Note: base is assumed to be a positive number. Tip: for functions that return a boolean value, you can return the result of a comparison.

def is_power_of(number, base): # Base case: when number is smaller than base. if number ==1: return True if number < base: # If number is equal to 1, it's a power (base**0). return False number /= base # Recursive case: keep dividing number by base. return is_power_of(number, base) ---------------------------------------- print(is_power_of(8,2)) # Should be True print(is_power_of(64,4)) # Should be True print(is_power_of(70,10)) # Should be False

The following code can lead to an infinite loop. Fix the code so that it can finish successfully for all numbers. Note: Try running your function with the number 0 as the input, and see what you get!

def is_power_of_two(n): # Check if the number can be divided by two without a remainder while n % 2 == 0 and n != 0: n = n / 2 # If after dividing by two the number is 1, it's a power of two if n == 1: return True n += 1 return False

Fill in the blanks to make the print_prime_factors function print all the prime factors of a number. A prime factor is a number that is prime and divides another without a remainder.

def print_prime_factors(number): # Start with two, which is the first prime factor = 2 # Keep going until the factor is larger than the number while factor <= number: # Check if factor is a divisor of number if number % factor == 0: # If it is, print it and divide the original number print(factor) number = number / factor else: # If it's not, increment the factor by one factor += 1 return "Done"

The following code causes an infinite loop. Can you figure out what's missing and how to fix it? def print_range(start, end): # Loop through the numbers from start to end n = start while n <= end: print(n)

def print_range(start, end): # Loop through the numbers from start to end n = start while n <= end: print(n) n += 1 Loop (cycle) begins from start number to the stop number. In example we have 1 and 5 respectively. Start = 1 to the end 5. At the while-loop's body you can see print(n) function to print number, after printing number will increase to the 1 and the loop will start again until the condition n<=end is met

The retry function tries to execute an operation that might fail, it retries the operation for a number of attempts. Currently the code will keep executing the function even if it succeeds. Fill in the blank so the code stops trying after the operation succeeded.

def retry(operation, attempts): for n in range(attempts): if operation(): print("Attempt " + str(n) + " succeeded") if n==1: break else: print("Attempt " + str(n) + " failed") --------------------------------------------- retry(create_user, 3) retry(stop_service, 5)

Fill in the gaps of the sum_squares function, so that it returns the sum of all the squares of numbers between 0 and x (not included). Remember that you can use the range(x) function to generate a sequence of numbers from 0 to x (not included).

def square(n): return n*n def sum_squares(x): sum = 0 for n in range(x): sum += square(n) return sum

Fill in the empty function so that it returns the sum of all the divisors of a number, without including it. A divisor is a number that divides into another without a remainder.

def sum_divisors(n): i = 1 sum = 0 # Return the sum of all divisors of n, not including n while i < n: if n % i == 0: sum += i i +=1 else: i+=1 return sum

RECURSIVE : The function sum_positive_numbers should return the sum of all positive numbers between the number n received and 1. For example, when n is 3 it should return 1+2+3=6, and when n is 5 it should return 1+2+3+4+5=15. Fill in the gaps to make this work:

def sum_positive_numbers(n): # The base case is n being smaller than 1 if n < 1: return n # The recursive case is adding this number to # the sum of the numbers smaller than this one. return n + sum_positive_numbers(n-1)

Implement the sum_positive_numbers function, as a recursive function that returns the sum of all positive numbers between the number n received and 1. For example, when n is 3 it should return 1+2+3=6, and when n is 5 it should return 1+2+3+4+5=15.

def sum_positive_numbers(n): if n<1: return n return n + sum_positive_numbers(n-1) return 0 -------------------------------------------- print(sum_positive_numbers(3)) # Should be 6 print(sum_positive_numbers(5)) # Should be 15

The validate_users function is used by the system to check if a list of users is valid or invalid. A valid user is one that is at least 3 characters long. For example, ['taylor', 'luisa', 'jamaal'] are all valid users. When calling it like in this example, something is not right. Can you figure out what to fix?

def validate_users(users): for user in users: if is_valid(user): print(user + " is valid") else: print(user + " is invalid") validate_users(["purplecat"]) <---- !!!!!!! (square bracket it!)

The multiplication_table function prints the results of a number passed to it multiplied by 1 through 5. An additional requirement is that the result is not to exceed 25, which is done with the break statement. Fill in the blanks to complete the function to satisfy these conditions.

def multiplication_table(number): # Initialize the starting point of the multiplication table multiplier = 1 # Only want to loop through 5 while multiplier <= 5: result = multiplier * number # What is the additional condition to exit out of the loop? if result > 25: break print (str(number) + "x" + str(multiplier) + "=" + str(result)) # Increment the variable for the loop multiplier += 1


Conjuntos de estudio relacionados

Chapter 8 - Management Structures & Organization - Complete

View Set

05.F BIO, HN The Calvin Cycle (PART F)

View Set

Lesson 9/Chapter 21: The Respiratory System

View Set