Python_M4
Python_M4
Randomized Approach
Randomized Approach
Brute Force guarantees finding a solution if one exists but can be inefficient
for large sets due to its exponential time complexity.
1. Generate subsets: Iterate over all possible subsets of the given set of
numbers.
2. Calculate sums: For each subset, calculate the sum of its elements.
3. Check target: Compare the sum of each subset with the target value.
4. Return result: If a subset’s sum matches the target, return that subset.
Otherwise, conclude that no such subset exists.
Use brute force approach and demonstrate how to find the subsets that
sums up to 9 in the list [3, 34, 4, 12, 5, 2].
Randomized Approach
Step-by-Step Solution :
1. Initial Setup:
Begin with the entire array and determine the range to process. Initially, this
range includes the entire array from the first element to the last element.
2. Divide
If the array contains more than one element, split it into two approximately
equal halves. This splitting continues recursively until each subarray has
only one element.
Huda Noor Dean College of Engineering Trikaripur 24 / 79
Finding the Maximum Element in an Array
3. Conquer:
-For subarrays with only one element, that element is trivially the maximum
for that subarray.
- For larger subarrays, recursively apply the same process to each half of
the subarray.
4.Combine:
- After finding the maximum element in each of the smaller subarrays,
combine the results by comparing the maximum values from each half.
Return the largest of these values as the maximum for the original array.
1. Initial Setup:
Array starts with indices 0 and len(array) - 1.
i.e 0 and 6
2. Divide:
- Calculate the middle index mid of the current array segment.
mid would be (0 + 6) // 2 = 3.
Split the array into two halves based on this mid index
– Left half: [3, 6, 2, 8] and Right half: [7, 5, 1]
Huda Noor Dean College of Engineering Trikaripur 26 / 79
Step by step explanation
Split into [3, 6] and [2, 8]
– Further split [3, 6] into [3] and [6]
3. Conquer
For subarrays with only one element, that element is trivially the maximum
for that subarray.
4. Combine
After finding the maximum element in each of the smaller subarrays,
combine the results by comparing the maximum values from each half.
- from [3, 6] , max is 6 and from [2, 8] , max is 8.
- from [7,5] , max is 7 and [1] is 1 itself.
- from [3,6] and [2, 8] , max is 8. - from [7,5] and [1] , max is 7
- from [3, 6, 2, 8] and [7, 5, 1] , max is 8
Randomized Approach
Wherever we see a recursive solution that has repeated calls for same
inputs, we can optimize it using Dynamic Programming.
if n == 1:
return 0
elif n == 2:
return 1
else:
return (Fibonacci(n-1)+Fibonacci(n-2))
x=int(input(’enter
Huda Noor Dean number’)) College of Engineering Trikaripur 33 / 79
Nth fibnocci term using Recursion
This is a bottom-up approach. We start from the bottom, finding fib(0) and
fib(1), add them together to get fib(2) and so on until we reach fib(5).
Huda Noor Dean College of Engineering Trikaripur 36 / 79
Nth fibnocci term program
def Fibonacci(n):
if (n == 1 or n == 2):
return 1
else:
fibNums = [0, 1,1];
print(fibNums)
for i in range(3,n):
fibNums.append (fibNums[i-1] + fibNums[i-2])
print(fibNums)
return fibNums[n-1]
x=int(input(’enter
Huda Noor Dean number’)) College of Engineering Trikaripur 37 / 79
Recursion vs Dynamic Programming
Dynamic programming is mostly applied to recursive algorithms. This is not
a coincidence, most optimization problems require recursion and dynamic
programming is used for optimization. But not all problems that use
recursion can use Dynamic Programming. Unless there is a presence
of overlapping sub-problems like in the Fibonacci sequence problem, a
recursion can only reach the solution using a divide and conquer approach.
This is the reason why a recursive algorithm like Merge Sort cannot use
Dynamic Programming, because the subproblems are not overlapping in
any way.
Randomized Approach
Being a very busy person, you have exactly T time to do some interesting
things and you want to do maximum such things.
You are given an array A of integers, where each element indicates the
time a thing takes for completion. You want to calculate the maximum
number of things that you can do in the limited time that you have.
Randomized Approach
▶ Simplicity in implementation.
▶ Robust performance for many cases.
▶ Lower time complexity in expected scenarios.
▶ Widely used in algorithms such as quicksort, Monte Carlo methods,
and others.
No definite answer
The answer is random:
If lucky, then n purchases are enough.
If unlucky, then no purchases will be enough.
More suitable question:
How many purchases needed on average to collect all coupons?
1. Initialize Variables:
- Total Jeans Bought: Start with a counter set to zero to track how many
pairs of jeans you have bought.
- Coupons Collected: Use a set to keep track of the different types of
coupons you have received.(to avoid duplicates use set)
- Number of Coupons: The total number of different coupon types is n.
# Example usage:
n = 10 # number of different coupons
expected_num_jeans = expected_jeans(n)
print(f"Expected number of jeans before getting a free one with {n} co
4. Calculate Average:
- Divide total_correct by 100,000 to get the average number of people who
receive their own hat.