Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added algorithm knapsack/python #329

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions bubble_sort/Python/bubble_sort.py
Original file line number Diff line number Diff line change
@@ -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()
31 changes: 31 additions & 0 deletions knapsack/Python/knapsack.py
Original file line number Diff line number Diff line change
@@ -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()