Skip to content

Commit b0f4602

Browse files
committed
Greedy Algorithm examples
1 parent 56f98ca commit b0f4602

File tree

5 files changed

+254
-0
lines changed

5 files changed

+254
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import sys
2+
3+
"""Prints a maximum set of activities that can be done by a
4+
single person, one at a time"""
5+
# n --> Total number of activities
6+
# start--> An array that contains start time of all activities
7+
# finish --> An array that contains finish time of all activities
8+
9+
#utility function
10+
def compare(a):
11+
return a[1] #creturn finish time of that activity
12+
13+
14+
15+
def printMaxActivities(arr,n):
16+
17+
s_arr=sorted(arr,key=compare) #sorting the array on the basis of finish time, using the key function we have just created above
18+
19+
20+
print("The following activities are selected")
21+
22+
# The first activity is always selected
23+
i = 0
24+
print(s_arr[i])
25+
26+
# Consider rest of the activities
27+
for j in range(n):
28+
29+
# If this activity has start time greater than
30+
# or equal to the finish time of previously
31+
# selected activity, then select it
32+
if s_arr[j][0] >= s_arr[i][1]:
33+
print(s_arr[j])
34+
i = j
35+
36+
# Driver code
37+
if __name__ == '__main__':
38+
print('enter the number of activities')
39+
n=int(input())
40+
41+
print('enter the start time and end time of activities')
42+
print('start time___end time')
43+
arr=[]
44+
for i in range(n):
45+
arr.append(list(map(int,input().split()))) #example list [[1,3],[2,4],[4,6]]
46+
47+
printMaxActivities(arr,n)
48+
49+
50+
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import sys
2+
import math
3+
4+
5+
6+
# define a function egyptianFraction
7+
# which receive parameter nr as
8+
# numerator and dr as denominator
9+
def egyptianFraction(nr, dr):
10+
11+
print("\nThe Egyptian Fraction " +
12+
"Representation of {0}/{1} is".
13+
format(nr, dr), end=" ")
14+
15+
# empty list ef to store
16+
# denominator
17+
ef = []
18+
19+
# while loop runs until
20+
# fraction becomes 0 i.e,
21+
# numerator becomes 0
22+
while nr != 0:
23+
24+
# taking ceiling
25+
x = math.ceil(dr / nr)
26+
27+
# storing value in ef list
28+
ef.append(x)
29+
30+
# updating new nr and dr
31+
nr = x * nr - dr
32+
dr = dr * x
33+
34+
# printing the values
35+
for i in range(len(ef)):
36+
if i != len(ef) - 1:
37+
print(" 1/{0} +" .
38+
format(ef[i]), end = " ")
39+
else:
40+
print(" 1/{0}" .
41+
format(ef[i]), end = " ")
42+
43+
if __name__ == '__main__':
44+
print('enter the fraction you want to find egyptian fraction of')
45+
46+
nr,dr=input().split('/') #enter the number in fraction form and then take the numerator and denominator part
47+
nr,dr=int(nr),int(dr)
48+
49+
egyptianFraction(nr,dr)
50+
51+
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import sys
2+
import os
3+
4+
# print the optimal value
5+
6+
def get_optimal_value(capacity,weights, v_w):
7+
value = 0.
8+
weight=0
9+
10+
while weight<capacity:
11+
12+
13+
temp=max(v_w)
14+
15+
p=v_w.index(temp)
16+
q=v_w.pop(p)
17+
r=weights.pop(p)
18+
19+
if r<=capacity:
20+
value +=(r*q)
21+
weight+=r
22+
else:
23+
value+=(capacity-weight)*q
24+
weight+=capacity-weight
25+
26+
27+
return value
28+
29+
30+
31+
if __name__ == "__main__":
32+
print('enter the input in format [n, capacity, value1, weight1, value2, weight2.....]')
33+
data = list(map(int, input().split())) #example input format [n, capacity, value1, weight1, value2, weight2.....]
34+
n, capacity = data[0:2]
35+
values = data[2:(2 * n + 2):2]#extracting values from data
36+
weights = data[3:(2 * n + 2):2] #extracting weights from data
37+
v_w= [ i/j for i,j in zip(values,weights)] #storing them in value1/weight1 format
38+
opt_value = get_optimal_value(capacity, weights, v_w)
39+
print("max value one can take {:.4f}".format(opt_value))
40+
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import sys
2+
3+
# Python3 program to find maximum
4+
# number of thieves caught
5+
6+
# Returns maximum number of thieves
7+
# that can be caught.
8+
def policeThief(arr, n, k):
9+
i = 0
10+
l = 0
11+
r = 0
12+
res = 0
13+
thi = []
14+
pol = []
15+
16+
# store indices in list
17+
while i < n:
18+
if arr[i] == 'P':
19+
pol.append(i)
20+
elif arr[i] == 'T':
21+
thi.append(i)
22+
i += 1
23+
24+
# track lowest current indices of
25+
# thief: thi[l], police: pol[r]
26+
while l < len(thi) and r < len(pol):
27+
28+
# can be caught
29+
if (abs( thi[l] - pol[r] ) <= k):
30+
res += 1
31+
l += 1
32+
r += 1
33+
34+
# increment the minimum index
35+
elif thi[l] < pol[r]:
36+
l += 1
37+
else:
38+
r += 1
39+
40+
return res
41+
42+
# Driver program
43+
if __name__=='__main__':
44+
45+
print('enter the array containing position of policeman and thief exa:["P","T","P"....]')
46+
arr=list(input().split())
47+
print('enter the max distance unit police can catch thief')
48+
k = int(input())
49+
n = len(arr)
50+
print(("Maximum thieves caught: {}".
51+
format(policeThief(arr, n, k))))
52+
53+
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
Problem : Fractional Knapsack
2+
3+
Information:
4+
Given weights and values of n items, we need to put these items in a knapsack of capacity W to get the maximum total value in the knapsack.
5+
Example:
6+
Items as (value, weight) pairs
7+
arr[] = {{60, 10}, {100, 20}, {120, 30}}
8+
Knapsack Capacity, W = 50;
9+
Output:
10+
Maximum possible value = 240
11+
by taking items of weight 10 and 20 kg and 2/3 fraction
12+
of 30 kg. Hence total price will be 60+100+(2/3)(120) = 240
13+
14+
Problem : Policeman_Thief
15+
16+
Information :
17+
Given an array of size n that has the following specifications:
18+
19+
Each element in the array contains either a policeman or a thief.
20+
Each policeman can catch only one thief.
21+
A policeman cannot catch a thief who is more than K units away from the policeman.
22+
23+
We need to find the maximum number of thieves that can be caught.
24+
25+
Examples:
26+
27+
Input : arr[] = {'P', 'T', 'T', 'P', 'T'},
28+
k = 1.
29+
Output : 2.
30+
Here maximum 2 thieves can be caught, first
31+
policeman catches first thief and second police-
32+
man can catch either second or third thief.
33+
'
34+
35+
36+
Problem : Activity Selection problem
37+
38+
Information:
39+
You are given n activities with their start and finish times. Select the maximum number of activities that can be performed by a single person, assuming that a person can only work on a single activity at a time.
40+
41+
Example :
42+
Consider the following 3 activities sorted by
43+
by finish time.
44+
start[] = {10, 12, 20};
45+
finish[] = {20, 25, 30};
46+
A person can perform at most two activities. The
47+
maximum set of activities that can be executed
48+
is {0, 2} [ These are indexes in start[] and
49+
finish[] ]
50+
51+
52+
53+
Problem : Egyptian Fraction
54+
55+
Information:
56+
Every positive fraction can be represented as sum of unique unit fractions. A fraction is unit fraction if numerator is 1 and denominator is a positive integer, for example 1/3 is a unit fraction. Such a representation is called Egyptian Fraction as it was used by ancient Egyptians.
57+
58+
Example:
59+
60+
Egyptian Fraction Representation of 2/3 is 1/2 + 1/6

0 commit comments

Comments
 (0)