I have a tuple of 50 numbers having digits 0...9 (with repetition), I want to calculate the sum of each repeated digits and create a new tuple for each repeated digits. how can I do that in python. (1,2,2,3,4,6,9,1,3,5,6,9,2,2,2,4,6,8,....9)..so sum of each repeated number like sumof2, sumof3...!!! I do know how to proceed.
Asked
Active
Viewed 1,334 times
-1
-
2Make an example please, your request is ambiguous. – timgeb Jul 01 '14 at 22:12
-
Your input, expected output and the code you tried will help your cause – Padraic Cunningham Jul 01 '14 at 22:14
-
Looks like homework. :-) – Paulo Scardine Jul 01 '14 at 22:15
-
(1,2,2,3,4,6,9,1,3,5,6,9,2,2,2,4,6,8,....9)..so sum of each repeated number like sumof2, sumof3...!!! I do know how to proceed. – A1g Jul 01 '14 at 22:18
-
1@ankit.1g, edit your question and add it there plus what you have tried. – Padraic Cunningham Jul 01 '14 at 22:19
2 Answers
4
try using the groupby()
function in itertools.
data = (1,2,2,2,3,3,...)
for key, group in groupby(data):
print "The sum of ", key, " is ", sum(list(group))
If you wanted to do this without itertools (because reasons), then the best approach would be to use a 'remembering' variable. (This code could probably be cleaned a little)
sums = []
prev = -1
curr_sum = 0
for element in data:
if element != prev:
if prev > 0:
sums.append(curr_sum)
curr_sum = 0
prev = 0
curr_sum += element
sums.append(curr_sum)
This will leave you with an array of the sums.
OR, with dictionaries even!
sums = {}
for element in data:
sums[element] = data.count(element) * element
# sums[4] = sum of 4s

Philip Massey
- 1,401
- 3
- 14
- 24
-
hi Philip thank you, but how can I implement this without using itertools. this is exactly what I wanted .is there a way to create our own groupby method? – A1g Jul 01 '14 at 22:46
-
I can find the count of the digit in the sequence but dont know how to find the sum of each repeated digit in the sequence.I can use for loop and sequence.count(), to find the count but how to separate and get the sum? – A1g Jul 02 '14 at 00:07
1
Maybe collections.Counter might help in this case if I'm reading the question correctly.
From what I understand you want the sum of the repeated elements inside a tuple that is corresponded with the int value?
This is no no means an efficient way of solving this, but hopefully it helps. I found this answer from a different kind of question to help solve yours: How to count the frequency of the elements in a list? Answered by YOU
from collections import Counter
data = (0,1,2,3,4,5,6,7,8,9,2,2,3,4,5,6,......)
results = ()
test = sorted(data)
counter = Counter(data)
values = counter.values()
keys = counter.keys()
for i in range(0,len(keys)):
results += ((keys[i],values[i]*keys[i]),)
print results