Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

PYTHON QUESTION Problem 2 Consider the following function: def contains two fives (n) sig: int>bool Give a four-digit positive decimal integer, the function will return

PYTHON QUESTION

image text in transcribed

Problem 2 Consider the following function: def contains two fives (n) sig: int>bool Give a four-digit positive decimal integer, the function will return True if the number contains at least two ftes, or False otherusse f n % 10..5and n % 100 // 10-5: return True if n % 10..5and n % 1000 // 100-5: return True if n % 10-. 5 and n % 10000 // 1000-. 5: return True f n % 100 // 10-5and n % 1000 // 100-5: return True if n % 100 // 10__ 5 and n % 10000 // 1000 __ 5: return True if n % 1000 // 100-. 5 and n % 10000 // 1000-. 5: return True return False The function determines if a four-digit number contains at least two fives. For example: contains two fives (1234)False because the number contains no fives contains_two_fives (1534)False because the number contains only one five contains two fives (1535)True because the number contains exactly two fives contains two fives (5505)True because the number contains at least two As you can see, the function uses modulus and division to extract each digit individualy. For example, the expression n % 100 // 10 evaluates to the second least-significant digit in n. Read the program and make sure you underestand how it works. The function is correct, however it is too verbose and repetitive. A lot of code in t is nearly the same thing, repeated. As programmers, we strive to avoid repetitive code. This principle is referred to as DRY: "Don't repeat yourself." Rewrite the function contains two fives so that the code is less repetitive. Use a loop Your improved version should behave exactly the same as the above version; that is, given the same input, it should produce the same result Hint: try using a loop to look at the least-significant digit of n, then remove that digit, and repeat unl n becomes zero. Count the umber of fives that you encounter Your professor's solution is only six lines. Can you do as well? Even better, can you ensure that your function will work for any arbitrary positive integer n (i.e. potentially more than four digits)

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access with AI-Powered Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions