Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

loops - How to concatenate first row with each remaining rows and second row with below each remaining rows for 7 cycles in Python?

I've been messing around with a few different solutions for how to concatenate

  1. Iterate 1st row with each row until last(n).
  2. After step1, Iterate 2nd row with each of remaining rows. So on 3rd row and till n(last row)-1 which is called as first cycle.
  3. Similarly for second cycle which is combination of first two rows with 3rd row.

Below is sample output which I want to be loaded in Excel or CSV when I give input ['A','B','C','D','E','F','G'].

1_cycle     2_cycle     3_cycle     4_cycle       5_cycle         6_cycle
 A&B          A,B&C     A,B,C&D    A,B,C,D&E     A,B,C,D,E&F    A,B,C,D,E,F&G
 A&C          A,B&D     A,B,C&E    A,B,C,D&F     A,B,C,D,E&G    
 A&D          A,B&E     A,B,C&F    A,B,C,D&G     B,C,D,E,F&G    
 A&E          A,B&F     A,B,C&G    B,C,D,E&F        
 A&F          A,B&G     A,B,C&E    B,C,D,E&G        
 A&G          A,C&D     A,B,C&F    C,D,E,F&G        
 B&C          A,C&E     A,B,C&G         
 B&D          A,C&F     A,B,C&F         
 B&E          A,C&G     A,B,C&G         
 B&F          A,D&E     B,C,D&E         
 B&G          A,D&F     B,C,D&F         
 C&D          A,D&G     B,C,D&G         
 C&E          A,E&F     C,D,E&F         
 C&F          A,E&G     C,D,E&G         
 C&G          A,F&G     D,E,F&G         
 D&E          B,C&D             
 D&F          B,C&E             
 D&G          B,C&F             
 E&F          B,C&G             
 E&G          C,D&E             
 F&G          C,D&F             
              C,D&G             
              D,E&F             
              D,E&G             
              E,F&G

So far, I am able to crack the first cycle. It's just when it comes to second cycle and third cycle I'm having trouble.

At the moment, I have this code below that is working for first cycle.

import pandas as pd
import time
import os
import csv

links=['A','B','C','D','E','F','G']
len = len(links)

A=0
B=1
csvfile = open('permutation_loop.csv', 'a',encoding='utf-8')
csvwriter = csv.writer(csvfile)

for i in links:
    first = i
    A+=1
    #print(first)
    for j in links[A:]:
        second = j
        B+=1
        first_cycle = first+second
        #print(second)
        #csvwriter.writerow([first_cycle.strip()])
        for k in links[B:]:
            third = k
            #print(third)
            second_cycle = first+second+third
            print(second_cycle)
            csvwriter.writerow([first_cycle,second_cycle])
question from:https://stackoverflow.com/questions/65870390/how-to-concatenate-first-row-with-each-remaining-rows-and-second-row-with-below

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
import csv


def one_cycle(original_inputs, previous_step):
    for i, x in previous_step:
        for j in range(i + 1, len(original_inputs)):
            yield (j, x + [original_inputs[j]])


def many_cycles(original_inputs, num_cycles):
    strings = [(i, [letter]) for i,letter in enumerate(original_inputs)]
    for i in range(num_cycles):
        strings = list(one_cycle(original_inputs, strings))
        yield (letter for index, letter in strings)


def insert_comma_ampersand(inp):
    # transforms ['A','B','C','D'] to 'A,B,C&D'
    comma_part = ','.join(inp[:-1])
    return f'{comma_part}&{inp[-1]}'


def make_permutations_csv(letters, num_cycles):
    csv_file = open('permutation_loop.csv', 'w', encoding='utf-8')
    csv_writer = csv.writer(csv_file, lineterminator='
')

    csv_writer.writerow([f'{i+1}_cycle' for i in range(num_cycles)])

    columns = list(many_cycles(letters, num_cycles))
    while not all(column is None for column in columns):
        row = []
        for i, column in enumerate(columns):
            if column is None:
                row.append('')
                continue

            try:
                row.append(insert_comma_ampersand(next(column)))
            except StopIteration:
                row.append('')
                columns[i] = None
        csv_writer.writerow(row)

    csv_file.close()


make_permutations_csv(['A', 'B', 'C', 'D', 'E', 'F', 'G'], 6)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...