Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Stop Iteration in Python

Hi, I am newbie in python and I dont know how to solve this..

population={'list_1':[0,2,3,4],'list_2':[2,0,4,1],'list_3':[1,6,0,8],'list_4':[3,5,6,0]}

item = [3,4,2,1]

def get_fitness(items):
    g= iter(items)
    temp=[]
    fitness_point=0
    try:
        for i in items:
            temp=population['list_{}'.format(i)]
            fitness_point+=temp[next(g)-1]
            print(temp[next(g)-1])
    except StopIteration:
        pass

    return fitness_point

print(get_fitness(item))

when I print, the result will be 8,3,5 but it is supposed to be 8,5,2 and 15 for fitness_point..

I dont know what to do, please help..

Hi Piyut

How is the fitness points meant to be calculated??

population={'list_1':[0,2,3,4],'list_2':[2,0,4,1],'list_3':[1,6,0,8],'list_4':[3,5,6,0]}

item = [3,4,2,1]

def get_fitness(items):
    g= iter(items)
    temp=[]
    fitness_point=0
    try:
        for i in items:
            temp=population['list_{}'.format(i)] # till here i get what you are doing 
            fitness_point+=temp[next(g)-1] # not sure whats going on here. You seem to be getting the next line of the             #iteration ??
            print(temp[next(g)-1])
    except StopIteration:
        pass

    return fitness_point

print(get_fitness(item))

1 Answer

srikanth chavvakula
srikanth chavvakula
6,178 Points

Hello Piyut,

Whats your objective in writing this program? It seems like you are a little off track in calculating the fitness points. Any specific criteria that you are using in this calculation? In other words, why are you expecting an output of 8,5,2 and 15? It will be helpful if you can briefly describe the objective of your program. In this process, you might actually solve your own problem.

Also, what are you exactly trying to print using this line - "print(temp[next(g)-1])" - that too in the middle of a function ??