473,320 Members | 1,856 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

an error in run python code

4
good day,
I try to run the following code gen.py in python 2.5 in order to resolve the STP with genetic algorithm, but i find an error:
Traceback (most recent call last):
File "C:\Python25\gen.py", line 55, in <module>
class population:
File "C:\Python25\gen.py", line 61, in population
for v in range(self.nombre_initial_population):
NameError: name 'self' is not defined
the code: gen.py
please any one help me.
Expand|Select|Wrap|Line Numbers
  1. # -*- coding: cp1252 -*-
  2. import random, sys, os, time
  3. class individu:
  4.  def __init__ (self,nombre_genes,random=-1):
  5.      self.genes = []
  6.      self.nombre_genes = nombre_genes
  7.      if random == -1 : self.random ()
  8. """
  9. random : initialise aleatoirement les genes
  10. """
  11. def random (self):
  12.     self.genes = []
  13.     f = range(0,self.nombre_genes)
  14.     for v in range(self.nombre_genes):
  15.         val = random.choice (f)
  16.         f.remove (val)
  17.         self.genes.append (val)
  18. """
  19. evaluation : compare l'individu avec un tableau d'autres individus
  20. retourne le nombre d'individus auquel l'individu self est superieur et de meilleure
  21. qualité
  22. """
  23. def evalutation (self,autres_individus,distances):
  24.     valeur_individu = 0
  25.     for v in autres_individus:
  26.         if self.compare(v,distances) > 0 : valeur_individu = valeur_individu + 1
  27.         self.valeur_individu = valeur_individu
  28.     return valeur_individu
  29. """
  30. compare : compare l'individu self avec un autre individu
  31. retourne un nombre positif s'il est superieur
  32. un nombre negatif s'il est inferieur
  33. le nombre 0 s'il est égal
  34. """
  35. def calcul_distance (self,distance):
  36.     a = self.genes[0]
  37.     dist = 0
  38.     for b in self.genes[1:]:
  39.         min=0
  40.         max=0
  41.         if a > b :
  42.             min = b
  43.             max = a
  44.         else :
  45.             min = a
  46.             max = b
  47.         dist = dist + (distance[min])[max-min-1]
  48.         a = b
  49.         self.distance = dist
  50.     return dist
  51. def compare (self,individu,distance):
  52.     individu.calcul_distance (distance)
  53.     self.calcul_distance (distance)
  54.     return self.distance - individu.distance
  55. class population:
  56.     def __init__ (self,nombre_genes,nombre_initial_population=50):
  57.         self.nombre_genes = nombre_genes
  58.         self.distances = [[]] * nombre_genes
  59.         self.individus = []
  60.         self.nombre_initial_population = nombre_initial_population
  61.     for v in range(self.nombre_initial_population):
  62.         self.individus.append (individu(nombre_genes))
  63. """
  64. selection : methode de selection des meilleurs N individus
  65. """
  66. def selection (self , N=-1):
  67.         if N == -1 : N = len(self.individus)
  68.         for v in self.individus:
  69.             v.evalutation (self.individus,self.distances)
  70.             self.individus.sort (lambda a,b : a.valeur_individu - b.valeur_individu)
  71.         if N <= len(self.individus) : self.individus = self.individus[0:N]
  72. """
  73. croisement : selectionne deux individus et croise leur gênes pour en creer de nouveaux
  74. """
  75. def croisement_deux (self , i1 , i2):
  76.         i = individu (self.nombre_genes)
  77.         l = len(i1.genes)
  78.         a = l / 2
  79.         p2 = i2.genes[a:l]
  80.         p1 = i1.genes[0:a]
  81.         choices = range(0,l)
  82.         for v in p1:
  83.             try:choices.remove (v)
  84.             except : pass
  85.         for v in p2:
  86.             try : choices.remove (v)
  87.             except : pass
  88.         idc = 0
  89.         for id in range(len(p2)):
  90.             if p2[id] in p1:
  91.                 p2[id] = choices[idc]
  92.                 idc = idc + 1
  93.                 i.genes = p1 + p2
  94.         return i
  95. """ croise tous les individus entre eux"""
  96. def croisement_all (self):
  97.     new = []
  98.     for v1 in range(len(self.individus)):
  99.         for v2 in range(v1,len(self.individus)):
  100.             new.append ( self.croisement_deux (self.individus[v1] , self.individus[v2]))
  101.             self.individus = self.individus + new
  102. """ croise nombre_croisement individus aleatoires entre eux """
  103. def croisement_nombre (self , nombre_croisement):
  104.     new = []
  105.     for r in range(nombre_croisement):
  106.         v1 = random.randint (0 , len(self.individus)-1)
  107.         v2 = random.randint (0 , len(self.individus)-1)
  108.         new.append (self.croisement_deux (self.individus[v1] , self.individus[v2]) )
  109.         self.individus = self.individus + new
  110. if __name__ == "__main__" :
  111.    p = population (10,50) # population de 50 individus puis on initialise les distances
  112.    p.distances[0] = [2,3,4,5,6,7,8,9,10 ] # distance de la premiere ville avec la 2eme , 3eme , ... , 10eme
  113.    p.distances[1] = [11,12,13,14,15,16,17,18 ] # distance de la deuxieme ville avec la 3eme , 4eme , ... ,10eme
  114.    p.distances[2] = [19,20,21,22,23,24,25] #etc...
  115.    p.distances[3] = [26,27,28,29,30,31]
  116.    p.distances[4] = [32,33,34,35,36]
  117.    p.distances[5] = [37,38,39 ,40]
  118.    p.distances[6] = [41,42,43]
  119.    p.distances[7] = [44,45]
  120.    p.distances[8] = [46] # distance de la 9eme ville avec la 10eme ville
  121. """
  122. 10 generations
  123. a chaque fois fait 100 croisements
  124. et selectionne les 10 premiers
  125. """
  126. for i in range(10):
  127.     p.croisement_nombre (100)
  128.     p.selection (10)
  129.     for v in p.individus:
  130.         print v.genes,v.calcul_distance (p.distances)
  131.  
  132.  
Jan 19 '13 #1
3 1805
Anas Mosaad
185 128KB
You need that line to be properly space line 61 to be on the same level as the previous lines.
Jan 19 '13 #2
dooja
4
hay,
I have a an other errorin the run of the code gen.py
the error:
Traceback (most recent call last):
File "C:\Python25\gen.py", line 111, in <module>
p = population (10,50) # population de 50 individus puis on initialise les distances
File "C:\Python25\gen.py", line 62, in __init__
self.individus.append (individu(nombre_genes))
File "C:\Python25\gen.py", line 7, in __init__
if random == -1 : self.random ()

Expand|Select|Wrap|Line Numbers
  1. # -*- coding: cp1252 -*-
  2. import random, sys, os, time
  3. class individu:
  4.  def __init__ (self,nombre_genes,random=-1):
  5.          self.genes = []
  6.          self.nombre_genes = nombre_genes
  7.          if random == -1 : self.random ()
  8. """
  9. random : initialise aleatoirement les genes
  10. """
  11. def random (self):
  12.     self.genes = []
  13.     f = range(0,self.nombre_genes)
  14.     for v in range(self.nombre_genes):
  15.         val = random.choice (f)
  16.         f.remove (val)
  17.         self.genes.append (val)
  18. """
  19. evaluation : compare l'individu avec un tableau d'autres individus
  20. retourne le nombre d'individus auquel l'individu self est superieur et de meilleure
  21. qualité
  22. """
  23. def evalutation (self,autres_individus,distances):
  24.     valeur_individu = 0
  25.     for v in autres_individus:
  26.         if self.compare(v,distances) > 0 : valeur_individu = valeur_individu + 1
  27.         self.valeur_individu = valeur_individu
  28.     return valeur_individu
  29. """
  30. compare : compare l'individu self avec un autre individu
  31. retourne un nombre positif s'il est superieur
  32. un nombre negatif s'il est inferieur
  33. le nombre 0 s'il est égal
  34. """
  35. def calcul_distance (self,distance):
  36.     a = self.genes[0]
  37.     dist = 0
  38.     for b in self.genes[1:]:
  39.         min=0
  40.         max=0
  41.         if a > b :
  42.             min = b
  43.             max = a
  44.         else :
  45.             min = a
  46.             max = b
  47.         dist = dist + (distance[min])[max-min-1]
  48.         a = b
  49.         self.distance = dist
  50.     return dist
  51. def compare (self,individu,distance):
  52.     individu.calcul_distance (distance)
  53.     self.calcul_distance (distance)
  54.     return self.distance - individu.distance
  55. class population:
  56.     def __init__ (self,nombre_genes,nombre_initial_population=50):
  57.         self.nombre_genes = nombre_genes
  58.         self.distances = [[]] * nombre_genes
  59.         self.individus = []
  60.         self.nombre_initial_population = nombre_initial_population
  61.         for v in range(self.nombre_initial_population):
  62.             self.individus.append (individu(nombre_genes))
  63. """
  64. selection : methode de selection des meilleurs N individus
  65. """
  66. def selection (self , N=-1):
  67.         if N == -1 : N = len(self.individus)
  68.         for v in self.individus:
  69.             v.evalutation (self.individus,self.distances)
  70.             self.individus.sort (lambda a,b : a.valeur_individu - b.valeur_individu)
  71.         if N <= len(self.individus) : self.individus = self.individus[0:N]
  72. """
  73. croisement : selectionne deux individus et croise leur gênes pour en creer de nouveaux
  74. """
  75. def croisement_deux (self , i1 , i2):
  76.         i = individu (self.nombre_genes)
  77.         l = len(i1.genes)
  78.         a = l / 2
  79.         p2 = i2.genes[a:l]
  80.         p1 = i1.genes[0:a]
  81.         choices = range(0,l)
  82.         for v in p1:
  83.             try:choices.remove (v)
  84.             except : pass
  85.         for v in p2:
  86.             try : choices.remove (v)
  87.             except : pass
  88.         idc = 0
  89.         for id in range(len(p2)):
  90.             if p2[id] in p1:
  91.                 p2[id] = choices[idc]
  92.                 idc = idc + 1
  93.                 i.genes = p1 + p2
  94.         return i
  95. """ croise tous les individus entre eux"""
  96. def croisement_all (self):
  97.     new = []
  98.     for v1 in range(len(self.individus)):
  99.         for v2 in range(v1,len(self.individus)):
  100.             new.append ( self.croisement_deux (self.individus[v1] , self.individus[v2]))
  101.             self.individus = self.individus + new
  102. """ croise nombre_croisement individus aleatoires entre eux """
  103. def croisement_nombre (self , nombre_croisement):
  104.     new = []
  105.     for r in range(nombre_croisement):
  106.         v1 = random.randint (0 , len(self.individus)-1)
  107.         v2 = random.randint (0 , len(self.individus)-1)
  108.         new.append (self.croisement_deux (self.individus[v1] , self.individus[v2]) )
  109.         self.individus = self.individus + new
  110. if __name__ == "__main__" :
  111.        p = population (10,50) # population de 50 individus puis on initialise les distances
  112.        p.distances[0] = [2,3,4,5,6,7,8,9,10 ] # distance de la premiere ville avec la 2eme , 3eme , ... , 10eme
  113.        p.distances[1] = [11,12,13,14,15,16,17,18 ] # distance de la deuxieme ville avec la 3eme , 4eme , ... ,10eme
  114.        p.distances[2] = [19,20,21,22,23,24,25] #etc...
  115.        p.distances[3] = [26,27,28,29,30,31]
  116.        p.distances[4] = [32,33,34,35,36]
  117.        p.distances[5] = [37,38,39 ,40]
  118.        p.distances[6] = [41,42,43]
  119.        p.distances[7] = [44,45]
  120.        p.distances[8] = [46] # distance de la 9eme ville avec la 10eme ville
  121. """
  122. 10 generations
  123. a chaque fois fait 100 croisements
  124. et selectionne les 10 premiers
  125. """
  126. for i in range(10):
  127.     p.croisement_nombre (100)
  128.     p.selection (10)
  129.     for v in p.individus:
  130.         print v.genes,v.calcul_distance (p.distances)
  131.  
  132.  
Jan 19 '13 #3
Anas Mosaad
185 128KB
Your code is not properly indented. The class has only one method (__init__) as it's the only indented one (with one space). So it's unable to see random as a member.
Jan 19 '13 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: Chris McKeever | last post by:
I am trying to modify the Mailman Python code to stop mapping MIME-types and use the extension of the attachment instead. I am pretty much clueless as to what I need to do here, but I think I have...
9
by: F. GEIGER | last post by:
I've dev'ed a Python prototype of an app, that besides the internals making it up has a gui. While test-driven dev'ing the app's internals in Python is fun as usual, dev'ing the GUI is not so...
9
by: Robey Holderith | last post by:
Does anybody know of a tool that can tell me all possible exceptions that might occur in each line of code? What I'm hoping to find is something like the following: given all necessary python...
7
by: Hansan | last post by:
Hi all, I hope you have time to help me out a little. My problem is that I want to combine some python code I have made with some html templates, I found a tutorial at dev shed:...
11
by: sushant.sirsikar | last post by:
hi, I am new to Python programming.I am not getting exactly pdb.Can anyone tell me effective way to debug python code? Please give me any example. Looking for responce. Thank You. Sushant
14
by: mistral | last post by:
Need compile python code, source is in html and starts with parameters: #!/bin/sh - "exec" "python" "-O" "$0" "$@" I have installed ActivePython for windows.
3
by: kaens | last post by:
Hey everyone, I'm relatively new to python - I actually picked it up to see how quickly I could start building non-trivial apps with it. Needless to say, I was quite pleased. Anyhow, I'm...
23
by: Python Maniac | last post by:
I am new to Python however I would like some feedback from those who know more about Python than I do at this time. def scrambleLine(line): s = '' for c in line: s += chr(ord(c) | 0x80)...
0
by: Marcin Krol | last post by:
Right, I didn't realize before that Python interpreter has its own signal handling routines. Now I am able to handle signals in Python code, but it still barfs on exit: import time import...
1
by: Jalindar Gat | last post by:
Hi all, I am new bee in Python programming... I am trying to download web page using python code code: import urllib # Get a file-like object for the Python Web site's home page. f =...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.