CodeBlanks Logo Icon CodeBlanks

Summary - Approximation and randomized

Print a randomized approximate solution in a mini task.

Summary - Approximation and randomized

In this group you learned approximation and randomized algorithms. Approximation ratio, Las Vegas and Monte Carlo combine to give practical approaches to NP-complete problems.

Now you will write a function that brings all pieces together. This summary unites the group's concepts in a single piece of code.

Practice is_within_factor function

Write is_within_factor(approx, optimal, factor). Return True if approx <= optimal * factor. Print True with print(is_within_factor(9, 9, 2)).

Starter code

solution.py
def is_within_factor(approx, optimal, factor):
    # Is solution within factor

Sample solution

solution.py
def is_within_factor(approx, optimal, factor):
    # Is solution within factor
    if approx <= optimal * factor:
        return True
    return False
print(is_within_factor(9, 9, 2))

Expected output

True

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does a 2-approximation algorithm give in the worst case?

  • At most twice optimal Correct answer
  • Optimal
  • Exponential time
  • No solution

Explanation: A 2-approximation gives at most twice the optimum.

2 Comparison

Question
if approx <= optimal * ____:
Answer
if approx <= optimal * factor:

Explanation: factor is right.

3 Summary - Approximation and randomized: match the terms

Term Meaning
find_max Maximum
sample_max Sample
approx_ratio Ratio
factor Factor

All lessons in Expert