Skip to content

Instantly share code, notes, and snippets.

@rebeccajae
Created December 24, 2018 20:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rebeccajae/ae1e5bbd2133810f41d0ea1fb8cea03a to your computer and use it in GitHub Desktop.
Save rebeccajae/ae1e5bbd2133810f41d0ea1fb8cea03a to your computer and use it in GitHub Desktop.
import random
def solution(N, L):
#Given budget of integer N, and a list of items of length S
#each with their own cost C, return the sub-list that uses
#the highest value <=N.
res = (0, 0, 0)
for idx, item in enumerate(L):
i = 0
l = 0
for item in L[idx:]:
if i + item <= N:
i += item
l += 1;
else:
break;
if i > res[2]:
res = (idx, l, i)
return res
budget = 60
x = [random.randint(1,50) for x in range(30)]
print("Budget of", str(budget))
print("In list", str(x))
res = solution(budget, x)
print("Solution at index", str(res[0]), "with contents", str(x[res[0]:res[0]+res[1]]), "having sum", str(res[2]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment