Home > OS >  Passing a list of list instead of a list in Python
Passing a list of list instead of a list in Python

Time:05-11

I am writing a code to mutate a list of strings, where the list contains 6 elements, where the first 4 are the attributes and the fifth one is the class, and the last one is the fitness. Now I want to pick a random attribute position and mutate that positions attribute which will be picked from a value_range.

Below is the code :

import random, math

prob_mut = 0.1
no_of_attr = 4

def mutate(pos):
    pos_random = random.randint(0, value_range[pos])
    if pos_random == 0:
        pos_random = '*'
    return pos_random
       
# p stands for probability of mutation
# a stands for the number of attributes
# c is the list from which the attributes will be mutated

def mutation(p, a, c):
    result = []
    if isinstance(c, list):
        range_ = math.ceil(a * p)
        for _ in range(range_):
            pos = random.randint(0, a - 1)
            value = mutate(pos)
            c[pos] = value
        c = [str(i) for i in c]
        result = c
        
res = mutation(prob_mut, no_of_attr, ['1', '*', '1', '2', '1', '0.57'])

My value_range looks like: {0: 3, 1: 3, 2: 3, 3: 4}

Here I am passing a list only, and it is giving me correct output for this case(a list), but I want to pass a list of list as the 3rd argument of mutation and want to get back a list of list as well. How can I do it?

My desired function call :

res = mutation(prob_mut, no_of_attr, [['1', '*', '1', '2', '1', '0.57'],['1', '*', '2', '*', '1', '0.97']])

CodePudding user response:

The requirement is quite confusing, but I'll answer with the following understanding: You want to pass a list of lists, and get mutation for each list in the list. If this understanding is wrong, you'll have to explain your requirement better. From purely a code perspective you can simple change your mutation function as following:

def mutation(p, a, cs):
    results = []
    for c in cs
        if isinstance(c, list):
            range_ = math.ceil(a * p)
            for _ in range(range_):
                pos = random.randint(0, a - 1)
                value = mutate(pos)
                c[pos] = value
            c = [str(i) for i in c]
            results.append(c)
    return results
  • Related