0

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

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
  • You look like you want to sum all of the combinations of a list of size 2. – Eli Sadoff Jan 18 '17 at 16:05
  • take a look at `itertools.combinations()` – Ma0 Jan 18 '17 at 16:06
  • Are these numbers stored as text in a file or are they already in a python list? Either way, you'll want to use [`itertools.combinations`](https://docs.python.org/3/library/itertools.html#itertools.combinations) – Patrick Haugh Jan 18 '17 at 16:07
  • Make two nested for. If the first has index i, the second has j=(i+1). And sum list[i]+list[j] – Andrea Jan 18 '17 at 16:07
  • f=open('test.dat',"r").read() #with open('test.out', 'w') as out_file: sum=0 for k in range (0,2): for j=(k+1): p = f(k)+f(j) print (p) – Shubhadip Chakraborty Jan 18 '17 at 16:13

3 Answers3

2

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]
Eli Sadoff
  • 7,173
  • 6
  • 33
  • 61
  • Can replace map with list comp. `[sum(x) for x in combinations(a, n)]` looks a bit more readable. And is more efficient. – Mohammad Yusuf Jan 18 '17 at 16:39
  • @MYGz How is it more efficient? I thought map and list comp were the same complexity. – Eli Sadoff Jan 18 '17 at 16:40
  • Someone was quoting Guido the other day for being more efficient. I have tested only once, list comp was a bit faster on python3. Will have to do some more digging if that's the case. I'm not 100% sure. – Mohammad Yusuf Jan 18 '17 at 16:43
  • @MYGz That's fine. I'm now very interested in this. I had always assumed that they would be the same because they pretty much act the same, at least in Python 2. I guess in Python 3 you could say there is a bigger difference because `map` creates a `map` object. – Eli Sadoff Jan 18 '17 at 16:44
  • Perhaps I'll write `map(sum, list)` after reading this answer: http://stackoverflow.com/a/6407222/4082217 – Mohammad Yusuf Jan 18 '17 at 17:02
0

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()
niraj
  • 17,498
  • 4
  • 33
  • 48
  • I did something like this f=open('test.dat',"r").read() for i in range(len(f)): for j in range(i+1, len(f)): print (f[i]+f[j]) but not working – Shubhadip Chakraborty Jan 18 '17 at 16:28
  • Can you please explain, what did you get for output? – niraj Jan 18 '17 at 16:45
  • i have a file with list of numbers in a column. The three numbers i mentioned as a test case, practically there are 11 numbers. I want to read those numbers in python and then want to do the operation as you mentioned. I can put all 11 numbers in x =[10, 12, 13, 18, 19...] but I felt it's better to read it from a file and then do the operation. If i put 11 numbers like x =[10, 12, 13, 18, 19...] I am getting the correct output but if i read the same numbers from a file and use the same coe then it's giving some nasty results – Shubhadip Chakraborty Jan 18 '17 at 16:53
  • for i in range(len(results)): TypeError: object of type 'map' has no len() – Shubhadip Chakraborty Jan 18 '17 at 17:08
  • Are you using Python 3? If yes, change the results type as said in comment i.e. `results = map(int, row)` to `results = list(map(int, results))`. – niraj Jan 18 '17 at 17:09
0

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))
CodeCupboard
  • 1,507
  • 3
  • 17
  • 26