Reputation: 15
Here is my code in python:
from array import *
date = array('I', [11, 11, 12, 11, 2, 7, 2])
saleAmount = array('I', [500, 25000, 51000, 100000, 125999, 126000, 202000])
for x in range(0,7):
if date[x] == 1:
totalsale = saleAmount[x]
print(date[x], totalsale)
if date[x] == 2:
totalsale = saleAmount[x]
print(date[x], totalsale)
if date[x] == 3:
totalsale = saleAmount[x]
print(date[x], totalsale)
if date[x] == 4:
totalsale = saleAmount[x]
print(date[x], totalsale)
if date[x] == 5:
totalsale = saleAmount[x]
print(date[x], totalsale)
if date[x] == 6:
totalsale = saleAmount[x]
print(date[x], totalsale)
if date[x] == 7:
totalsale = saleAmount[x]
print(date[x], totalsale)
if date[x] == 8:
totalsale = saleAmount[x]
print(date[x], totalsale)
if date[x] == 9:
totalsale = saleAmount[x]
print(date[x], totalsale)
if date[x] == 10:
totalsale = saleAmount[x]
print(date[x], totalsale)
if date[x] == 11:
totalsale = saleAmount[x]
print(date[x], totalsale)
if date[x] == 12:
totalsale = saleAmount[x]
print(date[x], totalsale)
I have found the duplicates in the data. Now I want to add the duplicates (e.g. if 11 occurs more than once, to add the corresponding values of all the 11's)
The output would be something like this:
11, 12550
How can I do it?
Upvotes: 0
Views: 46
Reputation: 3805
Your question is not very clear, but you show your effort this should grant you a few points.
First, a few remark about your code :
you seem to have 12 different conditions that lead to the same result. I don't know what you're trying to do exactly, but it is clear that you could reduce your code. You could for example replace your 12 conditions by the single
if date[x] in range(1,13)
It seems your code is not indented properly, you need to indent all lines that are within the for loop, and to add an additional indentation for lines of code that are subject to the if condition. This is how python is written, indentation is very important.
To answer your question, I believe the simplest way to make the sum of all sales that have the same date is to use a dictionary structure. It can keep the values of sales indexed by the date, and will not have empty values :
#we declare a dictionary
SalesByDate={}
#we fill the dictionary using a for loop
for x in range(0,7):
#if the entry for the date is not in the dictionary, you create it
if date[x] not in SalesByDate:
SalesByDate[date[x]]=0
#you then add the value of the sale to the corresponding date
SalesByDate[date[x]]+=saleAmount[x]
Then you have your dictionnary. you can print it directly :
print(SalesByDate)
but it's not very good looking. To print each line of it :
for entry in sorted(SalesByDate.keys()):
print(entry,SalesByDate[entry])
To access to the total sales for the date 11, you would need to use the syntax
SalesByDate[11]
which would yield with your data the result
125500
Upvotes: 1