Extending an item to the list used in .pop

I am trying to create a pseudo-random sequence generator. There are a couple of limitations, the first of which is that there must be 24 instances of each sequence and that there should never be a consistent occurrence of a sequence as a result. This is my code:

import random
def rgen():
    block_list =[]
    while len(block_list) != 96:
        sequences = ['seq1','seq2','seq3','seq4']
        block_list.extend(random.sample(sequences, 4))
    for x,y in enumerate(block_list):
        count = 'repeat'
        while count == 'repeat':
            if block_list[x] == block_list[x-1]:
                block_list.pop(x)
                block_list.extend(y)
                count = 'repeat'
            else:
                count = 'no repeat'
    sequence_counts = {'seq1':0,'seq2':0,'seq3':0,'seq4':0}
    for i in block_list:
        for k,v in sequence_counts.items():
            if k == i:
                v += 1
                sequence_counts[k] = v          
    print 'counts for each sequence: ', sequence_counts
    print block_list

The end result of this, however, is that at the end of the list I get something like this:

's', 'e', 'q', '1', 's', 'e', 'q', '1', 's', 'e', 'q', '2', 's', 'e', 'q', '4'

when I really want to just expand the entire list item, not individual characters.

so I want to expand all the lines that really are:

'seq1','seq1','seq2','seq4'
+4
source share
2 answers

extend() append(). extend() , y block_list. count , while else, break(). . , , x. , , , , x, . , block_list[x] pop()

while 1:
    if block_list[x] == block_list[x-1]:
       y = block_list.pop(x)
       block_list.append(y)
       #Alternatively, but not recommended, is to do .extend([y])
       #That treats y as an element of a list rather than a list itself 
    else:
       break

, , . for 0 -1. , range()

for x in xrange(1,len(block_list)):
    while 1:
        if block_list[x] == block_list[x-1]:
            y = block_list.pop(x)
            block_list.append(y)
        else:
            break

['seq2', 'seq1', 'seq3', 'seq4', 'seq1', 'seq2', 'seq4', 'seq3',
 ...,
 'seq3', 'seq1', 'seq2', 'seq4', 'seq3', 'seq2', 'seq3', 'seq4']
+2

, sequences, , seq sequences block_list. , sequences .

def rgen():
    sequences = [seq1, seq2, seq3, seq4]
    random.shuffle(sequences)

    for i in range(24):
        random.shuffle(sequences)
        if sequences[:1] != block_list[-1:]:
            block_list.extend(sequences[:])
        else:
            block_list.extend(sequences[::-1])

    return block_list

: rgen() ( ) . , :

[seq1 seq2 seq1 .... seq4 seq3 seq4]
0

Source: https://habr.com/ru/post/1626422/


All Articles