0

I need to sort a lists of organisms according to fitness. This is probably the easiest thing but I'm having trouble. Super amateur here.

This is my code:

import random as randint

pop_size = int(raw_input('Enter a population size:'))
length = int(raw_input('Enter an orgnaism length:'))

for i in range(pop_size):
    org = []
    for a in range(length):
        org.append(randint.randint(0,1))
    print org 
    fitness = sum(org)

print sorted(org, key=fitness)

I get the error:

Traceback (most recent call last):
  File "<stdin>", line 16, in <module>
TypeError: 'int' object is not callable

An explanation would be really helpful :)

Edit: This is Python 2.7.2

3
  • do you want a list of lists sorted by the sum of their values? In your code you are overwriting the org list multiple times and then only trying to print the list from the last iteration. Commented Jul 17, 2017 at 14:34
  • Yes, I need a list of lists sorted by their values Commented Jul 17, 2017 at 14:38
  • Check my answer to see if that's what you mean. Commented Jul 17, 2017 at 14:49

2 Answers 2

1

You aren't collecting the lists generated in each iteration through the population size:

import random as randint

pop_size = int(input('Enter a population size:'))
length = int(input('Enter an orgnaism length:'))

orgs = []
for i in range(pop_size):
    org = []
    for a in range(length):
        org.append(randint.randint(0,1))
    orgs.append(org)

print sorted(orgs, key=sum)

This can be a bit cleaner using a list comprehension:

import random as randint

pop_size = int(input('Enter a population size:'))
length = int(input('Enter an orgnaism length:'))

orgs = [[randint.randint(0,1) for a in range(length)] for i in range(pop_size)]

print sorted(orgs, key=sum)
Sign up to request clarification or add additional context in comments.

Comments

0

the key key word argument needs to be a function. So if you had a list of dicts you would use something like fitness = lambda x: x['fitness'] to sort the dicts by the fitness key. Also, maybe it's just an error from copy/pasting, but you're redefining fitness every time you go through the loop.

4 Comments

Do I have to use dictionaries or can I use a list?
You can use a list of lists if you'd like. list.sort(key=lambda x: x[1]) Or really a list of anything, as long as you call the key to sort by with a callable function like this. Another example of a callable function(that wouldn't work here) is datetime.now.
org.sort(key=lambda fitness: fitness[1]) Like that?
Yes, like that. However, you'll probably encounter a TypeError still, so I would suggest extracting the lambda to a separate function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.