Re: [Tutor] The Best Way to go About with Self Modifying Code/Code Generation?
Aaron Tp, 07.07.2012 23:19: > I have a question on using self-modifying code/code generation > in Python; namely how to do it. Don't. Seriously, the answer you should ask yourself is: why do you think the genetic algorithm (or whatever you are trying to do exactly) would come up with any reasonable code constructs other than what you already anticipated? And if you anticipated them, you can just write them down statically in the code and only care about recombining them. Make your code configurable instead, and then change the configuration. I agree with Alan that a state machine could be a suitable approach (but it's a bit hidden in his long answer). In any case, think in terms of modifying data, not code. Stefan ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] The Best Way to go About with Self Modifying Code/Code Generation?
On 07/07/12 22:19, Aaron Tp wrote: Hey all, I have a question on using self-modifying code/code generation in Python; namely how to do it. Self generating code is hard to do. Writing code is hard for intelligent humans, writing code to generate code is even harder. To write code that modifies itself increases the difficulty even further (and debugging it by an order of magnitude because you no longer know what the code you are debugging is!) If you are going to do it, its best if you use a language where the code and data are interchangeable, and that mainly means some kind of Lisp type language. To use a traditional language like Python just makes it even more complex. So in short you have bitten off a huge challenge. But there are ways and means to do some basic things depending on what you need to do. If its just changing the sequencing or control flow of a pre-existing set of functions then that's not too bad. Or if its just varying some parameters in an existing algorithm again it is doable. If its dynamically creating new functions or completely changing an existing algorithm then you are into really murky waters! then using 'exec' to execute the statements... exec or more likely eval() is pretty essential if you truly are writing new functions/algorithms. But its not needed if just changing control sequences. The first problem here, of course, is that it isn't a self-modifying system at allsecond being there'd be no way to edit pre-existing > code, and getting it all to be deleted wouldn't...make any sense. That depends on what you are trying to do. But one thing that will help a lot is to express your program ass a state machine. Then express the state machine as a data table with each state represented as an index into the table and with functions to transition between states. Then write the functions and put them in a dispatch table accessed via indexes. Now your programs behaviour can be expressed as a series of integers(the function indexes) and a state machine expressed as a table. Now we have code as data, albeit a limited set of code. And you can modify the behaviour by modifying the index corresponding to a state change and by modifying the next state index. People have recommended the use of Python's AST module, along with > the Compile module, Thats probably the best bet if you really need to generate/.modify existing functions. ...Or am I jst being overly-ambitious? You don't tell us anything about your Python coding experience (or even you're coding experience in other languages) but it is a big challenge. Especially in a language like Python (although much easier than in a compiled language like C!! And even that is possible: I did once implement a state machine solution as above in C for a remote controlled network traffic-routing switch) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] The Best Way to go About with Self Modifying Code/Code Generation?
Hey all, I have a question on using self-modifying code/code generation in Python; namely how to do it. I've posted on Stack Overflow and a python forum on this topic, and apparently the current approach I'd devised wastoo difficult. The idea was, for every Python operator and statement and whatnot, having a corresponding class/block of code with which to use it, and then using 'exec' to execute the statements... The first problem here, of course, is that it isn't a self-modifying system at allsecond being there'd be no way to edit pre-existing code, and getting it all to be deleted wouldn't...make any sense. People have recommended the use of Python's AST module, along with the Compile module, to be able to programatically edit/change pre-existing code, but there are two problems here. One being I'm not familiar at all with the AST/Compile modules, and two being that to the best of my understanding the AST module is very difficult for a user, let alone a Python code, to manipulate to yield useful results. (in case your wondering, I was hoping to hook up whatever form of modification/generation to a genetic algorithim or backprop algorithim and hopefully get something that can automatically write simple codesidk) My question iswhat should I be doing? Would the AST module work? Or am I jst being overly-ambitious? -Aaron ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] While loops
On 07/07/12 13:57, myles broomes wrote: I am currently coding a 'text-based adventure game', and im having a bit of trouble with while loops. Here is my code so far: What kind of trouble? You have lots of while loops, which loop? And do you get an error message? If so please post it - all of it! And looking through the code I see lots of potential problems, I have highlighted a few below... class Main_char(object): def __init__(self,name,invent,level=1,health=30,mana=15): def __str__(self): def town_chcklist(self): self.checklist=[] if town1==YES: self.checklist.append(town1) This method always resets the list to empty and then appends town1. You should move the initialisation of the list into __init__. But I see no variable defined anywhere called 'town1' so you would get an error... Fortunately you don't seem to call this method so no error is ever produced... def use_item(item): """Allows the player to use an item in their inventory.""" if item in ('Medicine','Mana Potion'): Hero.invent.delete(item) if item=='Medicine': Hero.hp+20 Here you add 20 to the value of Hero.hp but then throw thecresult away. I suspect you mean: Hero.hp += 20 elif item=='Mana Potion': Hero.mana+10 What is Hero.mana? It does not appear in the MainChar class definition? And as above I suspect you mean += 10? class Shopkeep(object): def __init__(self,inv,money): self.inv=inv self.money=money def __str__(self): print("Shopkeeper: Here are my wares: \n\n",self.inv+". \nI currently have",self.money,"gold.") #Create the towns/ dungeons/ areas in different functions def Embark(): Its usual practice to keep names startingt with a captial letter for Clas names. It gets confusing for the reader(whio might be you!) otherwise. """The town in which the player begins there journey.""" if emb_town_visit==None: print("Welcome to Embark Town",player_name+"!") while True: print("\n",hero) print(""" \n\t\tPress '1' to exit the town... \n\t\tPress '2' to enter the local shop...""") user_choice=input('What would you like to do?: ') if user_choice=='1': shop() continue You don't need 'continue' here because the loop drops out here anyway. But it won't do any harm. elif user_choice=='2': if emb_town_visit==None: print("\n\t\t\tAs you leave your home of Embark Town, you look back with a smile, then proceed North.") break else: print("\n\t\t\tThat is not a valid choice...") continue same here. You only need continue if you are jumping out of the code block back to the start of the loop. It should be a relatively rare event in well structured code! #The player has visited Embark Town if emb_town_visit==None: emb_town_visit=YES #Exit the function and change the players location variable return 'Left Embark Town',emb_town_visit This is broken due to some bad use of variable names. You define emb_town_visit as a global with value None. First time into Embark you test the global and if its set to None you *create a new local variable* of the same name. You then return it to main which sets *yet another local variable* of the same name to YES. But this does not change the global so next time you visit Embark the global is still None and you go through the same routine. If you want to use the global value (and especially if you want to change it) you must specify it as global in each function . But frankly it should probably not be global anyhow since you want to track that per player so it should really be part of your character class. def shop(): """A generic shop that is placed in each town.""" In that case it should probably be a class and you create an instance in each town. while True: print(""" \nWhat would you like to do? \nPress '1' to buy an item... \n...Press '2' to exit the shop... \n...Or press '3' to ask about the town...""") user_choice=input(">") if user_choice=='1': print("Shopkeeper: Goodbye.") break elif user_choice=='2': print(emb_shopkeep) user_choice=None print("Enter the name of the item you would like to pur
Re: [Tutor] While loops
On 7/7/2012 5:57 AM myles broomes said... I am currently coding a 'text-based adventure game', and im having a bit of trouble with while loops. Here is my code so far: Please paste in the traceback you're getting, and please set your mail client program for plain text when posting. What I see here has the indentation stripped out of your script so that before I can even test your code I'll have to guess at how you have it indented, and I'm more likely than you to get it right and may inadvertently fix your bug and never know it even before getting a chance to see the bug. Emile #Text-based Adventure RPG #The player travels through different towns and dungeons #The overall goal of the game is simple; the player must make it to the final town, #Battling various monsters and overcoming several challenges along the way import time player_name = None player_invent = [30] emb_town_visit=None YES='yes' NO='no' user_choice=None plyr_location='Embark' shopkeep_mny=100 shopkeep_invent=['Bronze Sword (10)','Steel Sword (100)','Rounded Shield (10)','Kite Shield (50)','Medicine (5)','Mana Potion (5)'] class Main_char(object): """A class for the main character object.""" def __init__(self,name,invent,level=1,health=30,mana=15): self.name=name self.level=level self.invent=invent self.hp=health self.mana=mana print("\nYour journey begins here in Embark town,"+self.name) def __str__(self): print("\nName: ",self.name, "\nLevel: ",self.level, "\nYour inventory: ",self.invent) def town_chcklist(self): """A checklist showing a list of the towns the player has already visited.""" self.checklist=[] if town1==YES: self.checklist.append(town1) def use_item(item): """Allows the player to use an item in their inventory.""" if item in ('Medicine','Mana Potion'): Hero.invent.delete(item) if item=='Medicine': Hero.hp+20 elif item=='Mana Potion': Hero.mana+10 class Shopkeep(object): """A blueprint for the shopkeeper objects.""" def __init__(self,inv,money): self.inv=inv self.money=money def __str__(self): print("Shopkeeper: Here are my wares: \n\n",self.inv+". \nI currently have",self.money,"gold.") #Create the towns/ dungeons/ areas in different functions def Embark(): """The town in which the player begins there journey.""" if emb_town_visit==None: print("Welcome to Embark Town",player_name+"!") while True: print("\n",hero) print(""" \n\t\tPress '1' to exit the town... \n\t\tPress '2' to enter the local shop...""") user_choice=input('What would you like to do?: ') if user_choice=='1': shop() continue elif user_choice=='2': if emb_town_visit==None: print("\n\t\t\tAs you leave your home of Embark Town, you look back with a smile, then proceed North.") break else: print("\n\t\t\tThat is not a valid choice...") continue #The player has visited Embark Town if emb_town_visit==None: emb_town_visit=YES #Exit the function and change the players location variable return 'Left Embark Town',emb_town_visit def shop(): """A generic shop that is placed in each town.""" while True: print(""" \nWhat would you like to do? \nPress '1' to buy an item... \n...Press '2' to exit the shop... \n...Or press '3' to ask about the town...""") user_choice=input(">") if user_choice=='1': print("Shopkeeper: Goodbye.") break elif user_choice=='2': print(emb_shopkeep) user_choice=None print("Enter the name of the item you would like to purchase.") user_choice=title(input(">")) for item in emb_shopkeep.inv: if user_choice in emb_shopkeep.inv: message=handle_pur(user_choice) print(message) emb_shopkeep.inv.delete(user_choice) else: print("\n\t\t\tThat is not a valid choice!") def handle_pur(item): """Handles purhchases made by the player in the shop.""" if item=='Bronze Sword': if Hero.invent[0] >= 10: Hero.invent[0]-10 Hero.invent.append(item) msg='You now own a',item elif Hero.invent[0] < 10: msg='You cannot afford that item.' elif item=='Steel Sword': if Hero.invent[0] >= 100: Hero.invent[0] - 100 Hero.invent.append(item) msg='You now own a',item elif Hero.invent[0] < 100: msg='You cannot afford that item.' elif item =='Rounded Shield': if Hero.invent[0] >= 10: Hero.invent[0] - 10 Hero.invent.append(item) msg='You now own a',item elif Hero.invent < 10: msg='You cannot afford that item.' elif item=='Kite Shield': if Hero.invent[0] >= 50: Hero.invent[0] - 50 Hero.invent.append(item) msg='You now own a',item elif Hero.invent < 50: msg='You cannot afford that item.' elif item=='Medicine': if Hero.invent[0] >= 5: Hero.invent[0] - 5 Hero.invent.append(item) msg='You now own a',item elif Hero.invent[0] < 5: msg='You cannot afford that item.' elif item=='Mana Potion': if Hero.invent[0] >= 5: Hero.invent[0] - 5 Hero.invent.append(item) msg='You now own a',item elif Hero.invent[0] < 5: msg='You cannot afford that item.' #Informs the program of which message to tell the player return msg emb_shopkeep=Shopkeep(shopkeep_invent,shopkeep_mny) #Player creation loop while True: print(""" \nValiant hero, your quest begins here in Embark Town.""", time.sleep(200
[Tutor] While loops
I am currently coding a 'text-based adventure game', and im having a bit of trouble with while loops. Here is my code so far: #Text-based Adventure RPG #The player travels through different towns and dungeons #The overall goal of the game is simple; the player must make it to the final town, #Battling various monsters and overcoming several challenges along the wayimport timeplayer_name = None player_invent = [30] emb_town_visit=None YES='yes' NO='no' user_choice=None plyr_location='Embark' shopkeep_mny=100 shopkeep_invent=['Bronze Sword (10)','Steel Sword (100)','Rounded Shield (10)','Kite Shield (50)','Medicine (5)','Mana Potion (5)'] class Main_char(object): """A class for the main character object.""" def __init__(self,name,invent,level=1,health=30,mana=15): self.name=name self.level=level self.invent=invent self.hp=health self.mana=mana print("\nYour journey begins here in Embark town,"+self.name) def __str__(self): print("\nName: ",self.name, "\nLevel: ",self.level, "\nYour inventory: ",self.invent)def town_chcklist(self): """A checklist showing a list of the towns the player has already visited.""" self.checklist=[] if town1==YES: self.checklist.append(town1) def use_item(item): """Allows the player to use an item in their inventory.""" if item in ('Medicine','Mana Potion'): Hero.invent.delete(item) if item=='Medicine': Hero.hp+20 elif item=='Mana Potion': Hero.mana+10class Shopkeep(object): """A blueprint for the shopkeeper objects.""" def __init__(self,inv,money): self.inv=inv self.money=moneydef __str__(self): print("Shopkeeper: Here are my wares: \n\n",self.inv+". \nI currently have",self.money,"gold.") #Create the towns/ dungeons/ areas in different functionsdef Embark(): """The town in which the player begins there journey.""" if emb_town_visit==None: print("Welcome to Embark Town",player_name+"!")while True: print("\n",hero) print(""" \n\t\tPress '1' to exit the town... \n\t\tPress '2' to enter the local shop...""") user_choice=input('What would you like to do?: ') if user_choice=='1': shop() continue elif user_choice=='2': if emb_town_visit==None: print("\n\t\t\tAs you leave your home of Embark Town, you look back with a smile, then proceed North.") break else: print("\n\t\t\tThat is not a valid choice...") continue #The player has visited Embark Town if emb_town_visit==None: emb_town_visit=YES#Exit the function and change the players location variable return 'Left Embark Town',emb_town_visit def shop(): """A generic shop that is placed in each town.""" while True: print(""" \nWhat would you like to do? \nPress '1' to buy an item... \n...Press '2' to exit the shop... \n...Or press '3' to ask about the town...""") user_choice=input(">") if user_choice=='1': print("Shopkeeper: Goodbye.") break elif user_choice=='2': print(emb_shopkeep) user_choice=None print("Enter the name of the item you would like to purchase.") user_choice=title(input(">")) for item in emb_shopkeep.inv: if user_choice in emb_shopkeep.inv: message=handle_pur(user_choice) print(message) emb_shopkeep.inv.delete(user_choice) else: print("\n\t\t\tThat is not a valid choice!")def handle_pur(item): """Handles purhchases made by the player in the shop.""" if item=='Bronze Sword': if Hero.invent[0] >= 10: Hero.invent[0]-10 Hero.invent.append(item) msg='You now own a',item elif Hero.invent[0] < 10: msg='You cannot afford that item.' elif item=='Steel Sword': if Hero.invent[0] >= 100: Hero.invent[0] - 100
Re: [Tutor] Program gets stuck after a creating a list from dictinary items!
On 07/07/2012 09:34, Alan Gauld wrote: On 07/07/12 04:35, Steven D'Aprano wrote: I find it ironic that you are suggesting removing the debugger to make it easier to debug the code :) But the pdb.trace() calls are not needed for debugging. The interactive debugger will work just fine without them. They are for very specialised use. (ie I've never found a need for them! ;-) I'd either add some more print statements or I'd run it inside a debugger. Which is what pdb is :) Yes but it doesn't need the trace() calls to use it and winpdb (or even IDLE) is much easier to use! Nevertheless, if the Original Poster is not actually using the debugger, he should remove the debugger calls. And that really was the point I was making. I don't use a debbuger much but when I do winpdb is superb. -- Cheers. Mark Lawrence. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Program gets stuck after a creating a list from dictinary items!
On 07/07/12 04:35, Steven D'Aprano wrote: I find it ironic that you are suggesting removing the debugger to make it easier to debug the code :) But the pdb.trace() calls are not needed for debugging. The interactive debugger will work just fine without them. They are for very specialised use. (ie I've never found a need for them! ;-) I'd either add some more print statements or I'd run it inside a debugger. Which is what pdb is :) Yes but it doesn't need the trace() calls to use it and winpdb (or even IDLE) is much easier to use! Nevertheless, if the Original Poster is not actually using the debugger, he should remove the debugger calls. And that really was the point I was making. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor