Question

I have a list of integers, representing the yearly profit (in kilo euro) of n businesses (shops) along the high street in the City centre. I am given 4 (four) businesses ("for free"), that neighbour one another. The problem is to calculate which 4 I should take to maximize my yearly profit. Given these numbers, write a PYTHON program to calculate which 4 I should take. As examples: If the profits were 52, 67, -8, 43, -20 I should take the first 4 businesses. If the profits were -20, 36, -10, -30, 3, 21 I would take no business (this is also allowed)

I'm not great at programming so any help would be appreciated, Cheers!

Initial attempt:

mylist=[52,67,-8,-43,-20]
>>> m=0
>>> for i in range(len(mylist)):
if m<mylist[i]:
    m=mylist[i]    

I'm not sure about the last line though so I tried this too which wont work?: if mylist[i]>m: print mylist[i]

Était-ce utile?

La solution

  1. Separate your list of profits into adjacent groups of 4

    groups = zip(mylist,mylist[1:],mylist[2:],mylist[3:]) #there are many ways of doing this i picked this way
    
  2. Pick the group with the largest sum

    print "I want :",max_sum(groups) #i will leave the implementation of this up to you
    
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top