rory
rory

Reputation: 19

python3, how to multiply element in a list of list

Good morning! I have a function with a bug, the following function

def frequency(couple2, pair_no_change, fq):
updated_pairs = list(list())
for pair in couple2[0:5]:
    if pair != pair_no_change:
        pair[0] *= fq
        pair[1] *= fq
        updated_pairs.append([pair[0], pair[1]])
    else:
        continue
return updated_pairs

is been used in:

for x in sorted_couple[0:78]:
    c = randrange(78)
    couple2.append(sorted_couple[c])
updated_pairs = frequency(couple2, pair_no_change, fq)

for t in updated_pairs:
    for i ,j in zip(list(t[0]), list(t[1])):
        #print ([i,j])
        couple.append([i,j])

and return a list(list()) called updated_pairs. the output is:

[['CCCCCCCCCC', 'SSSSSSSSSS'], ['LLLLLLLLLL', 'AAAAAAAAAA'], ['FFFFFFFFFF', 'YYYYYYYYYY'], ['NNNNNNNNNN', 'LLLLLLLLLL'], ['GGGGGGGGGG', 'NNNNNNNNNN']]

the problem is that when two identical couples are selected randomly, the output diverges giving me something like:

[['GGGGGGGGGG', 'NNNNNNNNNN'], ['PPPPPPPPPP', 'MMMMMMMMMM'], ['KKKKKKKKKK', 'DDDDDDDDDD'], ['DDDDDDDDDD', 'YYYYYYYYYY'], ['DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD', 'YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY']]

I'm trying to fix this problem from yesterday...any help would be great! thank you

Upvotes: 0

Views: 61

Answers (1)

TheBlackCat
TheBlackCat

Reputation: 10298

Doing something like pair[0] *= fq changes in the value in-place, so if you use the value again later it will be different. For safety it is probably better doing something like pair0 = pair[0]*fq, and using the new pair0 variable to append.

So change it to this:

def frequency(couple2, pair_no_change, fq):
    updated_pairs = list(list())
    for pair in couple2[0:5]:
        if pair != pair_no_change:
            pair0 = pair[0] * fq
            pair1 = pair[1] * fq
            updated_pairs.append([pair0, pair1])
        else:
            continue
    return updated_pairs

Or better yet this:

def frequency(couple2, pair_no_change, fq):
    updated_pairs = list(list())
    for pair0, pair1 in couple2[0:5]:
        if [pair0, pair1] == pair_no_change:
            continue
        updated_pairs.append([pair0*fq, pair1*fq])
    return updated_pairs

Upvotes: 1

Related Questions