From 5f84fd2cebc9a12b7b9b2af1e2b8ce5077cbeae4 Mon Sep 17 00:00:00 2001 From: Sartech-B Date: Sat, 6 Oct 2018 20:45:55 +0400 Subject: [PATCH 1/2] added algorithm knapsack/python --- knapsack/Python/knapsack.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 knapsack/Python/knapsack.py diff --git a/knapsack/Python/knapsack.py b/knapsack/Python/knapsack.py new file mode 100644 index 00000000..67ed31f6 --- /dev/null +++ b/knapsack/Python/knapsack.py @@ -0,0 +1,31 @@ +def knapsack(v, w, n, W): + ''' + Function solves 0/1 Knapsack problem + Function to calculate frequency of items to be added to knapsack to maximise value + such that total weight is less than or equal to W + :param v: set of values of n objects, first element is useless because relevant values are assumed to begin from index 1 + :param w: set of weights of n objects, first element is useless because relevant weights are assumed to begin from index 1 + :param n: number of items + :pram W: maximum weight allowd by knapsack + ''' + m = [[0 for j in range(W+1)] for i in range(n+1)] + for j in range(W+1): + m[0][j] = 0 + + for i in range(1, n+1): + for j in range(W+1): + if w[i]>j: + m[i][j] = m[i-1][j] + else: + m[i][j] = max(m[i-1][j], m[i-1][j-w[i]]+v[i]) + return m[n][W] + +def main(): + v = [0, 1, 2, 3, 4, 5] + w = [0, 5, 6, 2, 3, 4] + n = 5 + W = 8 + print("Answer to 0/1 Knapsack problem(Maximum value possible in given weight limit): "+str(knapsack(v, w, n, W))) + +if __name__ == '__main__': + main() \ No newline at end of file From 50ce8713cd2b3bd2829050eea9b642eab40b4ef2 Mon Sep 17 00:00:00 2001 From: Sartech-B Date: Sat, 6 Oct 2018 20:54:13 +0400 Subject: [PATCH 2/2] Added bubble sort algorithm for python --- bubble_sort/Python/bubble_sort.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 bubble_sort/Python/bubble_sort.py diff --git a/bubble_sort/Python/bubble_sort.py b/bubble_sort/Python/bubble_sort.py new file mode 100644 index 00000000..f22ed74a --- /dev/null +++ b/bubble_sort/Python/bubble_sort.py @@ -0,0 +1,21 @@ +def bubble_sort(arr): + ''' + Function to sort a list of integers using bubble sort algorithm + ''' + for i in range(len(arr)-1): + for j in range(len(arr)-i-1): + if arr[j]>arr[j+1]: + tmp = arr[j] + arr[j] = arr[j+1] + arr[j+1] = tmp + return arr + +def main(): + arr = [3, 1, 4, 2, 5] + sorted_arr = bubble_sort(arr) + print("Sorted array: ") + for i in sorted_arr: + print(i, end=" ") + +if __name__ == '__main__': + main() \ No newline at end of file