counting keys for dictionary, python -


//edit - i'm trying find pairs of sum, excluding duplicated pairs such (n1,n2) , (n2,n1) [one of them ignored]

so part of code, im trying achieve here is

  1. from input -> number_list of int split() -> double loops
  2. count +=1 everytime finds same [sum] key in count_dict
  3. count_dict[sum]=count records of how many of same sum different int pairs gets recorded.

but can't seem figure out how increment count variable correctly please advice me, thank you!

count=1 n1 in number_list:     n2 in number_list:          sum=n1+n2          if (n2,n1) not in pair_dict , n1!=n2:             pair_dict[(n1,n2)]=sum             sum_dict[sum]=(n1,n2)             if sum_dict[sum]==(n2,n1):                 count_dict[sum]=count             else:                 count+=1                 count_dict[sum]=count         else:             pass 

test case

2 1 3 4

5

10 20 40 45 5 15 25

25

24 23 8 29 31 5

none

from top part of question, looks trying find sum of each pair of elements in list , count number of times each sum occurs.

from itertools import combinations collections import counter  number_list = [1, 2, 3, 4, 5] sum_counter = counter(map(sum, combinations(number_list, 2)))  print(sum_counter) # {3: 1, 4: 1, 5: 2, 6: 2, 7: 2, 8: 1, 9: 1} 

this can readily generalized count sums of triplets, quadruplets, , on, changing 2 in arugment combinations.


Comments

Popular posts from this blog

javascript - Create a stacked percentage column -

Optimising Firebase database by automatically overwriting data -

javascript - Angular UI-Grid customTemplate directive causing rows to load slowly/? -