I have a list of numbers in a column like
10,12,13
I wanted to write a python program which can add these numbers in the following way: 10+12=22, 10+13=23, 12+13=25
Can anybody give any suggestion how to do it.
Thanks
I have a list of numbers in a column like
10,12,13
I wanted to write a python program which can add these numbers in the following way: 10+12=22, 10+13=23, 12+13=25
Can anybody give any suggestion how to do it.
Thanks
Using combinations
from itertools
this can be done rather trivially. For a list a
, you can get all of the sums of n
elements like this
from itertools import combinations
def sum_of_size(a, n):
return map(sum, combinations(a, n))
Edit: If you are using python 3, then use this instead
from itertools import combinations
def sum_of_size(a, n):
return list(map(sum, combinations(a, n)))
With your example
sum_of_size([10, 12, 13], 2)
# => [22, 23, 25]
This might work (Using Python 2.7):
x = [10,12,13]
for i in range(len(x)):
for j in range(i+1, len(x)):
print x[i],' + ', x[j], ' = ', x[i]+x[j]
Output:
10 + 12 = 22
10 + 13 = 23
12 + 13 = 25
Updated: Assuming the file has a line: 10, 12, 13
import csv
f = open("test.dat", 'r')
try:
reader = csv.reader(f)
for row in reader:
# convert array of string to int
# http://stackoverflow.com/a/7368801/5916727
# For Python 3 change the below line as explained in above link
# i.e. results = list(map(int, results))
results = map(int, row)
for i in range(len(results)):
for j in range(i+1, len(results)):
print (results[i]+results[j])
finally:
f.close()
If you didnt want to use itertools for some reason you could achieve this, this way. I have assumed what you want to do by the example result you have given:-
ColumnOfNumbers = [10,12,13]
def ListAddition(ColumnOfNumbers):
#check if the list is longer than one item
if len(ColumnOfNumbers)<=1:
return "List is too short"
#Define an output list to append results to as we iterate
OutputList = []
#By removing a number from the list as we interate we stop double results
StartNumber = 0
#Create a function to iterate - this is one less than the length of the list as we need pairs.
for x in range(len(ColumnOfNumbers)-1):
#Remove the first number from the list and store this number
StartNumber = ColumnOfNumbers[0]
ColumnOfNumbers.pop(0)
#Iterate through the list adding the first number and appending the result to the OutputList
for y in ColumnOfNumbers:
OutputList.append(StartNumber + y)
return OutputList
#Call the List Addition Function
print (ListAddition(ColumnOfNumbers))
If you want to get python to generate this list from a file which is a column of numbers then try this:-
ColumnOfNumbers = []
file1 = open('test.dat','r')
for line in file1:
ColumnOfNumbers.append(int(line))