I have a CSV file (out.txt) with the following format
red,green,blue
banana,apple,orange
I am trying to generate all two combinations so that the output is put to output.csv like the following
[red,green][red,blue][green,blue]
[banana,apple][banana,orange][apple,orange]
My code that works for single line is
import csv
with open('out.txt', newline='') as csvfile:
csvdata = list(csv.reader(csvfile))
print(csvdata)
r = 2;
n = len(csvdata);
print(n)
def printCombination(csvdata, n, r):
data = [0]*r;
print (data)
combinationUtil(csvdata, data, 0,
n - 1, 0, r);
def combinationUtil(csvdata, data, start,
end, index, r):
if (index == r):
for j in range(r):
print(data[j], end = " ");
print();
return;
i = start;
while(i <= end and end - i + 1 >= r - index):
data[index] = csvdata[i];
combinationUtil(csvdata, data, i + 1,
end, index + 1, r);
i += 1;
printCombination(csvdata, n, r);
The csvdata prints as
[['red', 'green', 'blue'], ['banana', 'apple', 'orange']]
However, if I manually define an array like so
[1,2,3]
it returns the correct answer. How do I do this with lists ?
Also how would I write the output to a csv ?