python - Finding the maximum sum of elements of a given array -
i have find maximum sum of elements in array (or permuted form), value of elements depends upon position in array
an algorithm finding sum of particular array follows
int taste = 0 (int i= 0; <= n; i++){ if (p[i]) - p[i-1]) >= 0): taste += * (p[i]) - p[i - 1]) else: taste += * (p[i - 1] - p[i])
my solution in python getting result 0
from itertools import permutations def sum_permuatations (): t = int(input()) taste = 0 maxtaste = 0 while ( t!=0): t = t-1 lent = input() lis = input() p in permutations(lis, len(lent)): in range(2,len(p)+1): if (int(p[i]) - int(p[i-1]) >= 0): taste += i*(int(p[i])-int(p[i-1])) else: taste += i*(int(p[i-1])- int(p[i])) if taste > maxtaste: maxtaste = taste return maxtaste
please me resolving error in code.
this solution uses itertools
library generate various permutations. each of max adjacent sum formula calculated using zip
give consecutive pairs of numbers in list. enumerate
function used give position of each pair.
import itertools input_list = [10, 15, 16] result = [] perm in itertools.permutations(input_list): sum_diff = 0 i,pair in enumerate(itertools.izip(perm[:-1], perm[1:])): sum_diff += abs(pair[0]-pair[1]) * (i+2) result.append((sum_diff, perm)) result.sort() print result[-1]
which give following result:
(28, (15, 10, 16))
or if print whole list:
[(13, (10, 15, 16)), (15, (10, 16, 15)), (17, (16, 15, 10)), (20, (15, 16, 10)), (27, (16, 10, 15)), (28, (15, 10, 16))]
your solution has couple of minor issues, using range
start 0. taste
needs zeroed each permutation follows:
from itertools import permutations def sum_permuatations(lis): maxtaste = 0 p in permutations(lis): taste = 0 in range(1,len(p)): if (int(p[i]) - int(p[i-1]) >= 0): taste += (i+1)*(int(p[i]) - int(p[i-1])) else: taste += (i+1)*(int(p[i-1]) - int(p[i])) if taste > maxtaste: maxtaste = taste return maxtaste input_list = [10, 15, 16] print sum_permuatations(input_list)
you need edit prompt input, made easier test. edit use abs
command avoid needing subtraction in different order.
Comments
Post a Comment