pythonpython-3.xgeneralization

How to to generalizing of the code for more variables?


In the code making up the graph I have blocks with similar conditions for four variables.

Block 1:

a =''.join(map(str, ['a1' if x%4==0 else 'a2' if x%4==1 else 'a3' if x%4==2 else 'a3' if x%4==3 else 'a4' for x in comb_3bit[i]]))

Block 2:

good=[]
all=[]

for j in range(comb_3bit_without[0].count('a1')):
    k = j*4
    all.append(k)
    good.append(k)
for j in range(kombinacje_3bit_bez_powtorzen[0].count('a2')):
    k = j*4 + 1
    all.append(k)
    good.append(k)
for j in range(kombinacje_3bit_bez_powtorzen[0].count('a3')):
    k = j*4 + 2
    all.append(k)
    good.append(k)
for j in range(kombinacje_3bit_bez_powtorzen[0].count('a4')):
    k = j*4 + 3
    all.append(k)
    good.append(k)

Block 3:

if len([i for i in good2 if i%4==0 ])==0:
   good2.insert(0,0)
if len([i for i in good2 if i%4==1 ])==0:
   good2.insert(1,1)
if len([i for i in good2 if i%4==2 ])==0:
   good2.insert(2,2)
if len([i for i in good2 if i%4==3 ])==0:
   good2.insert(3,3)

Block 4:

p0 = [i for i in good2 if i%4 ==0 ]
p1 = [i for i in good2 if i%4 ==1 ]
p2 = [i for i in good2 if i%4 ==2 ]
p3 = [i for i in good2 if i%4 ==3 ]

z0 = p0[-1]
z1 = p1[-1]          
z2 = p2[-1]
z3 = p3[-1]

Block 5:

g.add_node(z0+h*4)
g.add_node(z1+h*4)
g.add_node(z2+h*4)
g.add_node(z3+h*4)

good2.append(z0+h*4)
good2.append(z1+h*4)
good2.append(z2+h*4)
good2.append(z3+h*4)

Block 6:

a1 = [i for i in good2 if i%4 ==0 ]
a2 = [i for i in good2 if i%4 ==1 ]
a3 = [i for i in good2 if i%4 ==2 ]
a4 = [i for i in good2 if i%4 ==3 ]

sources = {
           'a1': a1,
           'a2': a2,
           'a3': a3,
           'a4': a4,
          }

However, now I would like to generalize the above fragments so that all the code could be easily used for more variables a[i]. I will be grateful for any help and guidance.


Solution

  • Are you just looking for functions? Your second block for example can be rewritten as follows:

    def appender(all_list, good_list, array, count_by, increment):
        for j in range(array[0].count(count_by)):
            k = j*4 + increment
            all_list.append(k)
            good_list.append(k)
        return all_list, good_list
    
    good = []
    all = []
    
    appender(all, good, comb_3bit_without, "a1", 0)
    appender(all, good, kombinacje_3bit_bez_powtorzen, "a2", 1)
    appender(all, good, kombinacje_3bit_bez_powtorzen, "a3", 2)
    appender(all, good, kombinacje_3bit_bez_powtorzen, "a4", 3)
    

    Your other blocks can also be rewritten to use functions.

    The key idea to realize here is that if you have code that is repeating you can probably use functions to make code reuse easier.