Re: [Tutor] csv DictReader/Writer question
Peter, Thank you for your response. I did try reading the documentation but I missed something (or several somethings in this case). So what I see in the code you supplied is: with open(source, rb) as instream: reader = csv.DictReader(instream, skipinitialspace=True) destfieldnames = list(reader.fieldnames) destfieldnames.remove(Species2) destfieldnames.remove(Protein ID2) So this reads the csv file in but I need to run it to see what skipinitialspace does. Then it reads in the header line and removes the Species2 and Protein ID2. Does this remove all the data associated with those columns? For some reason I thought I had to bring these into a dictionary to manipulate them. with open(dest, wb) as outstream: writer = csv.DictWriter(outstream, destfieldnames,extrasaction=ignore) writer.writer.writerow(destfieldnames) writer.writerows(reader) I think the first line after the open writes the field names to the file and the follow lines write the data is that correct? I am going to run the code as soon as I get home. ara -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] csv DictReader/Writer question
Hello all, I have a csv file (from a previous code output). It looks like this: Species2, Protein ID, E_value, Length, Hit From, Hit to, Protein ID2, Locus Tag, Start/Stop, Species Streptomyces sp. AA4, ZP_05482482, 2.82936001e-140, 5256, 1824, 2249\n, ZP_05482482, StAA4_0101000304844, complement(NZ_ACEV0178.1:25146..40916)4, Streptomyces sp. AA4: 0\n Streptomyces sp. AA4, ZP_05482482, 8.03332997e-138, 5256, 123, 547\n, ZP_05482482, StAA4_0101000304844, complement(NZ_ACEV0178.1:25146..40916)4, Streptomyces sp. AA4: 0\n Streptomyces sp. AA4, ZP_05482482, 1.08889e-124, 5256, 3539, 3956\n, ZP_05482482, StAA4_0101000304844, complement(NZ_ACEV0178.1:25146..40916)4, Streptomyces sp. AA4: 0\n I want to removing certain sections in each line so I wrote this code using csv.DictWriter: import csv data = csv.DictReader(open('strep_aa.txt')) for x in data: del x['Species2'] del x[' Protein ID2'] print x When it prints to the screen everything works great: {' Hit From': ' 1824', ' Hit to': ' 2249\\n', ' Protein ID': ' ZP_05482482', ' Locus Tag': ' StAA4_0101000304844', ' Start/Stop': ' complement(NZ_ACEV0178.1:25146..40916)4', ' Species': ' Streptomyces sp. AA4: 0\\n', ' Length': ' 5256', ' E_value': ' 2.82936001e-140'} {' Hit From': ' 123', ' Hit to': ' 547\\n', ' Protein ID': ' ZP_05482482', ' Locus Tag': ' StAA4_0101000304844', ' Start/Stop': ' complement(NZ_ACEV0178.1:25146..40916)4', ' Species': ' Streptomyces sp. AA4: 0\\n', ' Length': ' 5256', ' E_value': ' 8.03332997e-138'} What I don't know how to do is the export this back out a csv file and rearrange each key as a column header so it work look like this: Species Protein ID E Value . I thought csv.DictWriter would be the way to go since it writes dictionaries to text files. I was wondering how do I go about doing this? I don't really understand the syntax. Thank you! Ara -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Merging Text Files
Morning all, I took the pseudocode that Emile provided and tried to write a python program. I may have taken the pseudocode to literally. So what I wrote was this: xml = open(final.txt,'r') gen = open(final_gen.txt,'r') PIDS = {} for proteinVals in gen: ID = proteinVals.split()[0] PIDS[ID] = proteinVals print PIDS for line in xml: ID = proteinVals.split()[1] rslt = %s,%s% (line,PIDS[ID]) print rslt So the first part I get. I read in gen that has this format as a text file: *Protein ID, Locus Tag, Start/Stop* ZP_05482482, StAA4_010100030484, complement(NZ_ACEV0178.1:25146..40916) ZP_07281899, SSMG_05939, complement(NZ_GG657746.1:6565974..6581756) ZP_05477599, StAA4_01015861, NZ_ACEV0113.1:86730..102047 ... Put that into a dictionary with a key that is the Protein ID at position 0 in the dictionary. The second part reads in the file xml which has this format: *Species, Protein ID, E Value, Length* Streptomyces sp. AA4, ZP_05482482, 2.82936001e-140, 5256, Streptomyces sp. AA4, ZP_05482482, 8.03332997e-138, 5256, Streptomyces sp. AA4, ZP_05482482, 1.08889e-124, 5256, Streptomyces sp. AA4, ZP_07281899, 2.92539001e-140, 5260, Streptomyces sp. AA4, ZP_07281899, 8.23695995e-138, 5260, *same protein id multiple entries The program splits the file and does something with the 1 position which is the proten id in the xml file. After that I am not really sure what is happening. I can't remember what the %s means. Something with a string? When this runs I get the following error: Traceback (most recent call last): File /Users/ara/Desktop/biopy_programs/merge2.py, line 18, in module rslt = %s,%s% (line,PIDS[ID]) KeyError: 'StAA4_010100017400,' From what I can tell it's not happy about the dictionary key. In the end I am looking for a way to merge these two files and for each protein ID add the locus tag and start/stop like this: *Species, Protein ID, Locus Tag, E Value, Length*, *Start/Stop* Streptomyces sp. AA4, ZP_05482482, StAA4_010100030484, 2.82936001e-140, 5256, complement(NZ_ACEV0178.1:25146..40916) Streptomyces sp. AA4, ZP_05482482, StAA4_010100030484, 8.03332997e-138, 5256, complement(NZ_ACEV0178.1:25146..40916) Streptomyces sp. AA4, ZP_05482482, StAA4_010100030484, 1.08889e-124, 5256, complement(NZ_ACEV0178.1:25146..40916) Streptomyces sp. AA4, ZP_07281899, SSMG_05939, 2.92539001e-140, 5260, complement(NZ_GG657746.1:6565974..6581756) Streptomyces sp. AA4, ZP_07281899, SSMG_05939, 8.23695995e-138, 5260, complement(NZ_GG657746.1:6565974..6581756) Do you have any suggestions for how to proceed. It feels like I am getting closer. :) Note: When I change this part of the code to 0 for line in xml: ID = proteinVals.split()[0] rslt = %s,%s% (line,PIDS[ID]) print rslt I get the following output: Streptomyces sp. AA4, ZP_05482482, 8.03332997e-138, 5256, ,ZP_05479896, StAA4_010100017400, NZ_ACEV0143.1:241968..242983 Streptomyces sp. AA4, ZP_05482482, 1.08889e-124, 5256, ,ZP_05479896, StAA4_010100017400, NZ_ACEV0143.1:241968..242983 Streptomyces sp. AA4, ZP_07281899, 2.92539001e-140, 5260, ,ZP_05479896, StAA4_010100017400, NZ_ACEV0143.1:241968..242983 Which seems closer but all it's doing is repeating the same Locus Tag and Start/Stop for each entry. Thank you! Ara -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Merging Text Files
Morning all, I took the pseudocode that Emile provided and tried to write a python program. I may have taken the pseudocode to literally. So what I wrote was this: xml = open(final.txt,'r') gen = open(final_gen.txt,'r') PIDS = {} for proteinVals in gen: ID = proteinVals.split()[0] PIDS[ID] = proteinVals print PIDS for line in xml: ID = proteinVals.split()[1] rslt = %s,%s% (line,PIDS[ID]) print rslt So the first part I get. I read in gen that has this format as a text file: *Protein ID, Locus Tag, Start/Stop* ZP_05482482, StAA4_010100030484, complement(NZ_ACEV0178.1:25146..40916) ZP_07281899, SSMG_05939, complement(NZ_GG657746.1:6565974..6581756) ZP_05477599, StAA4_01015861, NZ_ACEV0113.1:86730..102047 ... Put that into a dictionary with a key that is the Protein ID at position 0 in the dictionary. The second part reads in the file xml which has this format: *Species, Protein ID, E Value, Length* Streptomyces sp. AA4, ZP_05482482, 2.82936001e-140, 5256, Streptomyces sp. AA4, ZP_05482482, 8.03332997e-138, 5256, Streptomyces sp. AA4, ZP_05482482, 1.08889e-124, 5256, Streptomyces sp. AA4, ZP_07281899, 2.92539001e-140, 5260, Streptomyces sp. AA4, ZP_07281899, 8.23695995e-138, 5260, *same protein id multiple entries The program splits the file and does something with the 1 position which is the proten id in the xml file. After that I am not really sure what is happening. I can't remember what the %s means. Something with a string? When this runs I get the following error: Traceback (most recent call last): File /Users/ara/Desktop/biopy_programs/merge2.py, line 18, in module rslt = %s,%s% (line,PIDS[ID]) KeyError: 'StAA4_010100017400,' From what I can tell it's not happy about the dictionary key. In the end I am looking for a way to merge these two files and for each protein ID add the locus tag and start/stop like this: *Species, Protein ID, Locus Tag, E Value, Length*, *Start/Stop* Streptomyces sp. AA4, ZP_05482482, StAA4_010100030484, 2.82936001e-140, 5256, complement(NZ_ACEV0178.1:25146..40916) Streptomyces sp. AA4, ZP_05482482, StAA4_010100030484, 8.03332997e-138, 5256, complement(NZ_ACEV0178.1:25146..40916) Streptomyces sp. AA4, ZP_05482482, StAA4_010100030484, 1.08889e-124, 5256, complement(NZ_ACEV0178.1:25146..40916) Streptomyces sp. AA4, ZP_07281899, SSMG_05939, 2.92539001e-140, 5260, complement(NZ_GG657746.1:6565974..6581756) Streptomyces sp. AA4, ZP_07281899, SSMG_05939, 8.23695995e-138, 5260, complement(NZ_GG657746.1:6565974..6581756) Do you have any suggestions for how to proceed. It feels like I am getting closer. :) Note: When I change this part of the code to 0 for line in xml: ID = proteinVals.split()[0] rslt = %s,%s% (line,PIDS[ID]) print rslt I get the following output: Streptomyces sp. AA4, ZP_05482482, 8.03332997e-138, 5256, ,ZP_05479896, StAA4_010100017400, NZ_ACEV0143.1:241968..242983 Streptomyces sp. AA4, ZP_05482482, 1.08889e-124, 5256, ,ZP_05479896, StAA4_010100017400, NZ_ACEV0143.1:241968..242983 Streptomyces sp. AA4, ZP_07281899, 2.92539001e-140, 5260, ,ZP_05479896, StAA4_010100017400, NZ_ACEV0143.1:241968..242983 Which seems closer but all it's doing is repeating the same Locus Tag and Start/Stop for each entry. Thank you! Ara -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Merging Text Files
Emile, I modified the code to this: for line in xml: ID = line.split()[1] rslt = %s,%s% (line,PIDS[ID]) print rslt and ended up with this error: Traceback (most recent call last): File /Users/ara/Desktop/biopy_programs/merge2.py, line 16, in module rslt = %s,%s% (line,PIDS[ID]) KeyError: 'sp.' Ara -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Merging Text Files
Adam, I am going to try and sort through the pseudocode you provided to see if I can get things up and running that way has well. This a part of a larger workflow thing and needs to be in the format that I have. Sticking all this into a database is down the road a ways. *for every line in ONE:* *make a dictionary with a key = to the protein ID and the value, the rest* I am pretty sure I have this correct by doing this: xml = open(final.txt,'r') gen = open(final_gen.txt,'r') PIDS = {} for proteinVals in xml: ID = proteinVals.split()[0] PIDS[ID] = proteinVals print PIDS For this part: *for every line in TWO:* *if the dictionary has the same protein ID:* *perform the string merging and write to the file* For this part I would need to do something like: for line in gen: ID = proteinVals.split()[0] if ID in PIDS: (I need to check for the key?) ???How do you merge lines being read in to a previous dictionary else: move on to next number Thanks! ara -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Merging Text Files
Hey all, It's mostly solved. The program prints out to the screen just fine except for the new line return. Here is what I ended up using: #Merges two files into one using dictionaries xml = open(final.txt,'r') gen = open(final_gen.txt,'r') PIDS = {} for proteinVals in gen: ID = proteinVals.split(',')[0] PIDS[ID] = proteinVals print PIDS for line in xml: ID = line.split(',')[1] IDs = ID.strip() rslt = %s,%s% (line,PIDS[IDs]) print rslt When I write this to a file what's the best way to take out the new line? Thanks again for everyone's help and pseudocode. It's been about 4 years since my last programming project! ara -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Merging Text Files
Hello all, I am working on merging two text files with fields separated by commas. The files are in this format: File ONE: *Species, Protein ID, E value, Length* Streptomyces sp. AA4, ZP_05482482, 2.82936001e-140, 5256, Streptomyces sp. AA4, ZP_05482482, 8.03332997e-138, 5256, Streptomyces sp. AA4, ZP_05482482, 1.08889e-124, 5256, Streptomyces sp. AA4, ZP_07281899, 2.92539001e-140, 5260, File TWO: *Protein ID, Locus Tag, Start/Stop* ZP_05482482, StAA4_010100030484, complement(NZ_ACEV0178.1:25146..40916) ZP_07281899, SSMG_05939, complement(NZ_GG657746.1:6565974..6581756) I looked around for other posts about merging text files and I have this program: one = open(final.txt,'r') two = open(final_gen.txt,'r') merge = open(merged.txt,'w') merge.write(Species, Locus_Tag, E_value, Length, Start/Stop\n) for line in one: print(line.rstrip() + two.readline().strip()) merge.write(str([line.rstrip() + two.readline().strip()])) merge.write(\n) merge.close() inc = file(merged.txt,r) outc = open(final_merge.txt,w) for line in inc: line = line.replace('[','') line = line.replace(']','') line = line.replace('{','') line = line.replace('}','') outc.write(line) inc.close() outc.close() one.close() two.close() This does merge the files. Streptomyces sp. AA4, ZP_05482482, 2.82936001e-140, 5256,ZP_05482482, StAA4_010100030484, complement(NZ_ACEV0178.1:25146..40916) Streptomyces sp. AA4, ZP_05482482, 8.03332997e-138, 5256,ZP_05477599, StAA4_01015861, NZ_ACEV0113.1:86730..102047 But file one has multiple instances of the same Protein ID such as ZP_05482482. So the data doesn't line up anymore. I would like the program to search for each Protein ID number and write the entry from file 2 in each place and then move on to the next ID number. Example of desired output: Streptomyces sp. AA4, ZP_05482482, StAA4_010100030484, 2.82936001e-140, 5256, complement(NZ_ACEV0178.1:25146..40916) Streptomyces sp. AA4, ZP_05482482, StAA4_010100030484, 8.03332997e-138, 5256, complement(NZ_ACEV0178.1:25146..40916) I was thinking about writing the text files into a dictionary and then searching for each ID and then insert the content from file TWO into where the IDs match. But I am not sure how to start. Is there a more pythony way to go about doing this? Thank you for your time and help. Regards, Ara -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Merging Text Files
Thank you for all of the advice. I am going to try the dictionary route first thing tomorrow. This code is a part of larger code theat: 1) quires the BLAST database using BioPython 2) parses the data using BioPython, 3) dumps to text files 4) then merges the text files and sorts them. Somewhere down stream this goes into a spreadsheet. Regards, Ara -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] CSV question for getting data from a text file
Hello all, I fell off the python programming wagon for awhile and I am quite rusty. I a text file that looks like this *a bunch of stuff above* O(-2)/O(0) 12.5731 0.7181 Distribution of species Log Log Log SpeciesMolalityActivity Molality Activity Gamma OH- 4.121e-06 3.489e-06-5.385-5.457-0.072 H+1.437e-09 1.259e-09-8.843-8.900-0.057 H2O 5.551e+01 9.994e-01 1.744-0.000 0.000 C(4) 5.334e-03 HCO3- 4.517e-03 3.877e-03-2.345-2.411-0.066 *stuff below* I wrote this program: import string import csv, sys import matplotlib.pyplot as plt import numpy as np filein = raw_input(What is the name of your file?) testreader = csv.reader(open(filein)) for row in testreader: print(row) The output looks like this: [] ['Distribution of species'] [] ['\t Log Log Log '] ['\tSpeciesMolalityActivity Molality Activity Gamma'] [] ['\tOH- 4.121e-06 3.489e-06-5.385-5.457-0.072'] ['\tH+1.437e-09 1.259e-09-8.843-8.900-0.057'] ['\tH2O 5.551e+01 9.994e-01 1.744-0.000 0.000'] What I am interested in is the species column and the activity column. The eventual goal is do do a bunch of calculations on the activties and plot it up using matplotlib. How do ignore everything before and after the Distribution of species and then pull out the species and activties so I can perform calculations on them? Is csv the best for that or am I better off using split and dumping into a dictionary? I think I need to specify white space as the delimiter, is that correct? Thank you very much. Ara -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Learning Python (Ara Kooser)
Fred, I've been learning python off and on for a couple years now. I recommend: Alan Gauld's Learning to Program http://www.freenetpages.co.uk/hp/alan.gauld/ and How to Think Like a Computer Scientist http://www.ibiblio.org/obp/thinkCSpy/ Also find a project you are passionate about and try to program it in Python. I like Traveller (an old rpg) and text adventure games. So I used Python to create some utilities and then a game. Hope this helps. Ara -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] remove instances from a list
Hello all, On my continuing quest to grapple with OO programming Kent showed me that I could call instances and store them in a list like: yeasts = [Yeast(Red_1,Red,ade,lys),Yeast(Yellow_1,Yellow,lys,ade), Yeast(Red_2,Red,ade,lys),Yeast(Yellow_2,Yellow,lys,ade)] Give certain conditions I want the yeast cell to die. Kent suggested I use something this: yeasts = [yeast for yeast in yeasts if yeast.isAlive()] to clear out dead yeast. Is the translation for the above line of code into pseudocode? yeast for every yeast in the list yeasts if the yeast method returned isAlive() Or is this meant to be a true or false return? I have included the code below. Thank you again. Ara ### CODE BELOW ### # # Yeast Model # By Ara Kooser # Version beta # #Thanks to Kent, Michael, and Alan for suggestions and help ## import random chemicals = [] class Yeast: def __init__(self,name,group,need,release): #name can be any, group is either red or yellow, need/release lys or ade self.name = name self.group = group self.need = need self.release = release self.growth = 0 self.life = 0 self.starve = 0 self.alive = True #METHODS def setup(self): #Sets up the random variable for each yeast before the game logic loop if self.group == Red: a = random.randrange(40,160) self.life = a self.growth = 5 aa = random.randrange(20,50) self.starve = aa elif self.group == Yellow: b = random.randrange(20,80) self.life = b self.growth = 3 bb = random.randrange(10,30) elif self.group == Defect: pass else: pass def chem_need(self): if self.need == ade: if self.need in chemicals: print self.name,is taking ade self.life = self.life+1 chemicals.remove(self.need) print chemicals print Life, self.life print else: print self.name, found no ade present self.life = self.life-1 elif self.need == lys: if self.need in chemicals: print self.name, is taking lys self.life = self.life+1 chemicals.remove(self.need) print chemicals print Life,self.life print else: print self.name, found no lys present self.life = self.life-1 else: pass def near_death(self): #release of aa in the environment near cell death if self.life = self.starve: c = random.randrange(1,3) if c == 1: print self.name, -- Releasing, self.release chemicals.append(self.release) if c == 2: print self.name, -- Releasing, self.release chemicals.append(self.release) chemicals.append(self.release) if c == 3: print self.name, -- Releasing, self.release chemicals.append(self.release) chemicals.append(self.release) chemicals.append(self.release) def isAlive(self): if self.life 0: self.alive = True else: self.alive = False def growth(self): pass ### #Program Starts Here ### #Stores the instances in a list for easier use. Later versions will allow the user to add #instances #Instance are called: Yeast, name, group, aa need, aa release yeasts = [Yeast(Red_1,Red,ade,lys),Yeast(Yellow_1,Yellow,lys,ade), Yeast(Red_2,Red,ade,lys),Yeast(Yellow_2,Yellow,lys,ade)] print Welcome to the red/yellow yeast simulation environment. printRed yeast cells need adenine to grow and they release lysine. printYellow yeast cells ned lysine to grow and release adenine. print raw_input(Please press return or enter to start the game.) rounds = raw_input(How many rounds to you wish to play through?) print Starting environment, chemicals rounds =int(rounds) count = 0 ###Game logic for yeast in yeasts: yeast.setup() while count rounds: print ## print Round number,count print for yeast in yeasts: yeast.chem_need() print print Chemicals in the environment,chemicals print #Calls the growth code that in not yet functioning #for yeast in yeasts: #yeast.growth() #The line below will eventually clean out dead
[Tutor] Killing an instance
I have two instances called and running. They interact with each other and I would like one of the instances to cease to exist in the second round based on a given condition. How do you kill an instance? The code is below. I have Red and Yellow as my instances and I want them to die when life = 0 and not show up in the preceding rounds of the game. Thank you. Ara CODE HERE: ## #Red and Yellow yeast model # #Both yeast start out cooperating. #If the yeast detect that there is no ade or lys present they will defect #but die. ## import time chemicals = [] #0 cooperates #1 defects class RedYeast: #Needs adenine to grow, releases lysine def __init__(self,name,group): self.name = name self.group = group self.life = 1 self.hate_tolerance = 0 self.choice = 0 #METHODS def lys_re(self,stuffa): #release of lys in the environment if self.choice == 0: print self.name, -- Releasing lys chemicals.append(stuffa) elif self.choice == 1: print self.name, -- Withholds lys def ade_need(self,stuffb): if stuffb != chemicals: print self.name,is taking ade self.life = self.life+1 chemicals.remove(stuffb) print chemicals print Life, self.life else: print No ade presents self.life = self.life-1 self.choice = 1 class YellowYeast: #Needs lysine to grow, releases adenine def __init__(self,name,group): self.name = name self.group = group self.life = 1 self.hate_tolerance = 0 self.choice = 0 #METHODS def ade_re(self,stuffa): #release of lys in the environment if self.choice == 0: print self.name, -- Releasing ade chemicals.append(stuffa) elif self.choice == 1: print self.name, -- Withholds ade def lys_need(self,stuffb): if stuffb != chemicals: print self.name, is taking ade self.life = self.life+1 chemicals.remove(stuffb) print chemicals print Life,self.life print else: print No ade presents self.life = self.life-1 self.choice = 1 def death(self): ## #Start of program ## rounds = raw_input(How many rounds to you wish to play through?) print Starting environment, chemicals rounds =int(rounds) count = 0 #Creates the instances for RedYeast and YellowYeast one = RedYeast(Red,alpha) two = YellowYeast(Yellow,alpha) #Game logic while count rounds: print ## print one.lys_re(lys) two.ade_re(ade) print print Chemicals in the environment,chemicals print time.sleep(1) one.ade_need(ade) two.lys_need(lys) print ## print count = count+1 print Ending environment, chemicals -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Classes: global name not defined
So taking the advice given my John, Kent, and Michael I reworked the program and created a class for world. I was able to solve the first several errors that came up as a I moved functions into class methods but this one stumps me. The error I am getting is: Traceback (most recent call last): File /Users/ara/Documents/yeast/oop_yeast_nocaps.py, line 87, in module first_instance.print_world() File /Users/ara/Documents/yeast/oop_yeast_nocaps.py, line 40, in print_world m, n = world['dimensions'] NameError: global name 'world' is not defined I understand that the error refers to the method print_world(). In the instance before first_instance.print_world() I define what world is but that is not being carried over to the print_world method. In the print world method do I need to refer back to the random_world method so it knows what world is? Thank you. CODE STARTS HERE: import random import copy YEAST = '@' EMPTY = '.' GROUP = 'Q' class World: #What makes this a world def __init__(self,name): self.name = name #Add other things later #Methods def percolation(self,perc): #Sets up a percolation threshold value perc = float(perc) randval = random.random() if randval perc: return EMPTY else: return YEAST def random_world(self): #Constructs random world of size MxN world = {} for j in range(n): for i in range(m): world[i, j] = self.percolation(perc) world['dimensions'] = (m, n) return world def print_world(self): #Prints out a string representation of a world. m, n = world['dimensions'] for j in range(n): for i in range(m): print world[i, j], print def add_yeast(self): #Allows the user to add a yeast cell at point m,n m,n = world['dimensions'] new_world = copy.copy(world) counta = 0 print The upper left corner is the point (0,0) yy = raw_input(How many yeast cells do you wish to add?) yy = int(yy) while countayy: i = int(raw_input(Please enter a m value for the yeast cell.)) j = int(raw_input(Please enter a n value for the yeast cell.)) new_world[i,j] = YEAST for j in range(n): for i in range(m): world[i,j]=new_world[i,j] counta = counta+1 def debug(self): print self.name ## #Start of prgram ## first_instance = World(small_world) #first_instance.debug() raw_input(Please press return to start the program.) perc = raw_input(Please enter a thresold between 0-1 for the population.) first_instance.percolation(perc) n = int(raw_input(Please enter a n dimension. )) m = int(raw_input(Please enter a m dimension. )) first_instance.random_world() first_instance.print_world() first_instance.add_yeast() -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] calling class instances in functions
Thank you for your help on classes. I am working on an old program I started in 2005. This time around I am trying to model cell behavior using a PD model. I have the main program and then a file called yeast_cell.py that contains the classes I want to instance. In the main program at the function def add_yeast(world): I want to instance the class GoodYeast and have the global variable @ change to G on the world. I tried just creating an instance but that did not go over so well. I was wondering what is the proper and pythonic way to create an instance that the user will be selecting in a function. I eventually want to add a bunch of different cell classes. Thank you for your help. Ara Kooser Main Program #Yeast Cooperation Model #by Ara Kooser #Version 1.0 no PD, 070906 # #This code contain just the world setup and not the actually PD code #for copperation behavior. This is better left to classes not functions # #TO DO LIST: Add error handling, dump to text file, data gathering, #different classes of yeast # #Many thanks to: Danny Yoo, Lee Haar, Max Noel, Kent Johnson import random import copy import textwrap import yeast_cell # #This section of the code sets up and prints out the starting conditions #of the world and the yeast YEAST, EMPTY, GROUP = '@', '.', 'Q' def percolation(perc): #Sets up a percolation threshold value randval = random.random() if randval perc: return EMPTY else: return YEAST def random_world(M, N): #Constructs random world of size MxN world = {} for j in range(N): for i in range(M): world[i, j] = percolation(perc) world['dimensions'] = (M, N) return world def print_world(world): #Prints out a string representation of a world. M, N = world['dimensions'] for j in range(N): for i in range(M): print world[i, j], print def add_yeast(world): #Allows the user to add a yeast cell at point m,n M,N = world['dimensions'] new_world = copy.copy(world) counta = 0 yy = raw_input(How many yeast cells do you wish to add?) yy = int(yy) while countayy: zz = raw_iput(What kind of yeast cell do you want to add? Options:GoodYeast) #Here I want to call this instace of GoodYeast from yeast_cell.py print Please place this yeast cell using an m,n point print The upper left hand corner is (0,0) i = int(raw_input(Please enter a m value for the yeast cell.)) j = int(raw_input(Please enter a n value for the yeast cell.)) new_world[i,j] = YEAST for j in range(N): for i in range(M): world[i,j]=new_world[i,j] counta = counta+1 print_world(small_world) ## #The following code gets the state of the world and determines #what is next to each cell, sensing # def get_state(world,i,j): #Returns the state of the cell at position (i,j) return world.get((i,j), EMPTY) def count_neighbors(world,i,j): #Returns the number of cells next to this one live_count = 0 for i_delta in [-1,0,1]: for j_delta in [-1,0,1]: if(i_delta,j_delta)==(0,0): continue if get_state(world, i+i_delta, j+j_delta)==YEAST: live_count+=1 return live_count def is_grouped(world,i,j): #Returns a true value if the cell at (i,j) is connected by 1-8 others return(get_state(world,i,j)==YEAST and (1 =count_neighbors(world,i,j)=8)) def next_world(world): #Shows which yeast are in a group using Q M,N = world['dimensions'] new_world=copy.copy(world) for j in range(N): for i in range(M): if is_grouped(world,i,j): new_world[i,j] = GROUP for j in range(N): for i in range(M): world[i,j]=new_world[i,j] def AddYeast(): print If you selected 0 for your percolation you may now add yeast to the world. print The upper left hand corner is point (0,0). zz = raw_input(Do you want to add a yeast cell? y or n) if zz == y: add_yeast(small_world) elif zz == n: print_world(small_world) raw_input(Please press return to group your yeast cells.) # #This is where the PD portion of the program starts # def PD_yeast(): print textwrap.fill (The PD will added later in the OOP version) printREFERENCES print textwrap.fill (Learning to program. By Alan Gauld) print textwrap.fill (How to Think Like a Computer Scientist. By Downey, Elkner, and Meyers
[Tutor] More class questions
Hello again, Thank you again for your help. I have classes somewhat figured out and I am beginning to understand the syntax involved in using them. What I have so far is a very simple text adventure with two rooms, two items, and some exits. Two question which relates directly to classes: Do you create all your instances at the end of the program or just as needed? Can you call functions from other classes within a class (So I create an Object class for items and I want then instances to appear in the Room class as they are called). Third question. Using function I understand how to move a player around in different rooms using raw_input and if statements but how do you do that with classes. I created a player class and I want one of the methods to be moving from room to room. Or should movement be a separate class? I am looking at the code that Paul McGuire wrote for using pyparsing and I don't quite understand how it all works. I have to book Game Programming: The L line coming in two weeks. I am just trying to get a head start. Thank you. Ara CODE BELOW # #Text Advenuture - Roguelike #By Ara Kooser #Thanks to Chris, e.,Tino and Steven at python tutor class Player: #What makes this a player. pass #def Move(self): class Area: #What makes it an area? def __init__(self, name, description): #Number of arguements in the _init_ there must be defined self.name = name self.description = description self.contents = [] self.paths = [None,None,None,None] #Methods. What you can do. def AddObject(self,thing): self.contents.append(thing) def AddPaths(self,direction): self.paths.append(direction) def look(self): print Look around the place you are in print You are in the,self.name print self.description print Your exits are: print self.paths def search(self): print You search the area and find... print self.contents ### # MAIN #Start of program ### first_instance = Area(Outside, You are standing outside) first_instance.AddObject(Stick) first_instance.AddPaths(North) first_instance.look() first_instance.search() print print second_instance = Area(Inside, You are standing inside) second_instance.AddObject(Iron pot) second_instance.AddPaths(South) second_instance.look() second_instance.search() -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Further into classes
Thank you for the help on getting started on classes. I have a basic understanding of how they are used and I reread the tutorials again. So I have a class set up and running. My question is how you append a list (such as self.contents = [ ]) using a method like def AddObject? The code I am trying is below but it is not working. I am really sure I am not going about this the right way. Thank you. Ara # #Text Advenuture #By Ara Kooser #Thanks to Chris, e., and Steven at python tutor class Area: #What makes it an area? def __init__(self, name, description): #Number of arguements in the _init_ must be defined self.name = name self.description = description self.contents = [] #Methods. What you can do. def AddObject(self,thing): #pass self.contents.append() def look(self): print Look around the place you are in print You are in the,self.name print self.description def search(self): print You search the area and find... print self.contents first_instance = Area(Outside, You are standing outside) first_instance.AddObject(Stick) first_instance.look() first_instance.search() second_instance = Area(Inside, You are standing inside) second_instance.AddObject(Iron pot) second_instance.look() second_instance.search() -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Starting classes
Hello, I read Alan Gauld's and How to Think Like a Computer Scientist section on classes. So I tried to write a simple room class. My goal is to write a short text adventure using classes. Here is the code: class Area: def _init_(self, name, description): self.name = name def look(here): Look around the place you are in print here.description outside1 = Area(Outside) outside1.description = You are standing outside with the town gate to your back self.contents.append(dirt) look(bedroom) I get the following error. Traceback (most recent call last): File /Users/ara/Documents/text_advent.py, line 11, in module outside1 = Area(Outside) TypeError: this constructor takes no arguments Do the outside1 = Area(Outside) need to be nested in the class or can they be outside of it? Thank you. Ara -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Question about calling functions
Hello, After taking some suggestions from bhaaluu my program for generating a character works except for one part. You have a choice of excepting a set of numbers. If you choose n then the program dumps you into: def navy() instead of going back to def upp(). I am guessing this has to do with how I am calling the functions at the end of the program: ### # start program here ### print Welcome to the Classic Traveller character generator. Written in Python print Press return to generate a character raw_input() print upp() print You have a chance to reroll if needed. reroll() navy() I see that after reroll() it goes to navy(). What I don't understand is why when you have a choose n it won't go back to upp(). Thanks. Ara PROGRAM BELOW ## # Version:0.3 # By: Ara Kooser # import random strength = 0 dexterity = 0 endurance = 0 intelligence = 0 education = 0 social = 0 print \nGenerating your UPP. print def upp(): global strength global dexterity global endurance global intelligence global education global social strength = random.randrange(2,12) dexterity = random.randrange(2,12) endurance = random.randrange(2,12) intelligence = random.randrange(2,12) education = random.randrange(2,12) social = random.randrange(2,12) return strength, dexterity, endurance, intelligence, education, social def reroll(): a = raw_input(Are you satisfied with your UPP? Choose yes or no.).lower() try: if a[0] == y: career() elif a[0] == n: upp() else: print Please choose a valid option. print out = reroll() except: print Please choose a valid option. print out = reroll() return def career(): print You will now choose a career path for your character. print Please choose your career path. print b = raw_input(Navy, Marines, Army, Scouts, Merchants).lower() try: if b[0] == navy: out = navy() elif b[0] == marines: marines() elif b[0] == army: army() elif b[0] == scouts: scouts() elif b[0] == merchants: merchants() except: print Please choose a valid option. print career() return def navy(): global strength global dexterity global endurance global intelligence global education global social print You have selected a naval career. c = raw_input(How many terms of service do you want? 1,2,3,4,5) enlist = int(c) count = 0 rank = 0 age = 18 benefits = [] cash = [] skills = [] commission = False while countenlist: age=age+4 count=count+1 if commission == False: comm = random.randrange(2,12) if comm=10: commission = True print You made commission else: print You did not make comission if commission == True: prom = random.randrange(2,12) if prom=8: rank=rank+1 print Your rank is now print rank else: print You did not make promotion pskill = random.randrange(1,6) if pskill == 1: strength=strength+1 elif pskill == 2: dexterity=dexterity+1 elif pskill == 3: endurance=endurance+1 elif pskill == 4: intelligence=intelligence+1 elif pskill == 5: education=education+1 elif pskill == 6: social=social+1 sskill = random.randrange(1,6) if sskill == 1: skills[1:1]=['Ships Boat'] elif sskill == 2: skills[1:1]=['Vacc Suit'] elif sskill == 3: skills[1:1]=['Fwd Obsvr'] elif sskill == 4: skills[1:1]=['Gunnery'] elif sskill == 5: skills[1:1]=['Blade Cbt'] elif sskill == 6: skills[1:1]=['Gun Cbt'] if education8: aeskill = random.randrange(1,6) if aeskill == 1: skills[1:1]=['Vacc Suit'] elif aeskill == 2: skills[1:1]=['Mechanical'] elif aeskill == 3: skills[1:1]=['Electronic'] elif aeskill == 4: skills[1:1]=['Engineering'] elif aeskill == 5: skills[1:1]=['Gunnery'] elif aeskill == 6: skills[1:1]=['Jack-o-T'] if education=8: ae8skill = random.randrange(1,6) if ae8skill == 1: skills[1:1]=['Medical'] elif ae8skill == 2: skills[1:1]=['Navigation'] elif ae8skill == 3: skills[1:1
[Tutor] Question about classes
Hello all, I am working on trying to understand classes by creating a character generator for a rpg. I know I am doing something silly but I am not sure what. When I run the program I and type no when prompted I get the following message: Traceback (most recent call last): File /Users/ara/Documents/ct_generator.py, line 10, in module class Main: File /Users/ara/Documents/ct_generator.py, line 68, in Main reroll() File /Users/ara/Documents/ct_generator.py, line 53, in reroll upp() NameError: global name 'upp' is not defined I guess it doesn't recognize that I want to call the function upp() again. I think I might be using the wrong syntax here. My code is below. Thank you any help or guidance. Ara ### #Version: not even 0.1 #By: Ara Kooser # import random class Main: print Welcome to the Classic Traveller character generator. Written in Python print Press return to generate a character raw_input() def upp(): print Generating your UPP. print strength = 0 dexterity = 0 endurance = 0 intelligence = 0 education = 0 social = 0 strength = random.randrange(2,12) dexterity = random.randrange(2,12) endurance = random.randrange(2,12) intelligence = random.randrange(2,12) education = random.randrange(2,12) social = random.randrange(2,12) return strength, dexterity, endurance, intelligence, education, social print upp() def reroll(): a = raw_input(Are you satisfied with your UPP? Choose yes or no.).lower() try: if a == yes: career() elif a == no: upp() else: print Please choose a valid option. print reroll() except ValueError: print Please choose a valid option. print reroll() return print You have a chance to reroll if needed. reroll() def career(): print You will now choose are career path for your character. -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] global question
Hello, I am back working on a text adventure game using functions. I broke down the game into areas (modules) but I am having trouble getting the other modules to recognize the globals I have set in the main program. My main program looks like this: #A sample text adventure game using functions #Version 1.0 #By Ara Kooser # import random import sys import string import outside1 import town1 import items # #Contains the character's information # stre = 9 con = 8 inte = 11 agl = 14 app = 10 mag = 6 sz = 9 hp = 17 reputation = 0 stealth = False # Grass quest quest1 = False # Mushroom quest quest2 = False # Orc quest quest3 = False cursed = False poison = False diseased = False equipment = {'Sword': 1, 'Dagger': 1, 'Walking staff': 1, 'Leather Armor':1} backpack = {'Flint and steel': 1, 'Rations': 7, 'dressing kit': 6, 'waterskin': 2} belt_pouch = {} money = {'ducats': 50} Forage = 45 Haggle = 33 Stealth = 28 Fishing = 58 Herbalism = 48 Climb = 52 Sword = 34 Staff = 47 Dagger = 42 Field_Dressing = 62 # # help function that will give you a list of commands def help(): print look, examine (object), n, w, e, s, take (item) print climb, stealth, fishing, herbalism, forage, haggle print aid (applies first aid) print wield (object), attack, flee, close, withdraw, maintain print inv (returns inventory list), cs print Example: examine book, take ducats, attack orc def character_sheet(): print \ Name: Profession: Apprentice Social Class: Low Race: Human Strength 9 Constitution 8 Intelligence 11 Agility 14 Appearance10 Magic 6 Size 9 Skills: Forage, Haggle, Stealth, Fishing, Herbalism, Climb, Sword, Staff, Dagger, Field Dressing The other modules are outside1, etc.. outside1 looks like this def outside1(): print Current Hit Points = ,hp print Current Reputation = ,reputation print equipment print backpack .. When I run this I get: Traceback (most recent call last): File /Users/ara/Desktop/text_advent/outside1.py, line 452, in module outside1() File /Users/ara/Desktop/text_advent/outside1.py, line 26, in outside1 print Current Hit Points = ,hp NameError: global name 'hp' is not defined I kind of suspect the global name I set on main wouldn't work for the outside1 module. Is there a way to do this. I don't want to copy the globals into each area file because they need to be updated during this course of the game. Thanks for any help or suggestions. Ara -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] simple list question
Hello all, First off thank you to all the folks that gave input on a smallpox percolation model my students were working on last year. They won first place in the computation division at the science fair and took home the Intel Programming award. I can post or e-mail the code if anyone wants it. This should be simple but I've haven't programmed in python since I started my new job. I am running Python 2.4 on a Windows XP machine (my linux laptop crashed). Editing is done in Idle. # # Test of a room as list # room.py # room = [' ', ' ', ' ', ' ', '', '#.#', '#.#', '#.#', '#.#', '#.##'] print room, When the program runs my output is this: [' ', ' ', ' ', ' ', '', '#..#', '#..#', ''] Why is that? I thought that adding , after the print command would allow the format to stay the same. Is there a better way of doing this (I like lists because I can edit them easily)? Thanks. Ara -- Fatti non foste per viver come bruti, ma per seguir virtute e canoscenza - Dante AlighieriYou were not made to live like brutes, but to pursue virtue and knowledge ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] simple list question
Thanks Kent for your help. Right now I am trying to get one room working with just a character and movement. Then on to creatures, multiple rooms and tracking. Ara On 2/20/06, Kent Johnson [EMAIL PROTECTED] wrote: Ara Kooser wrote: But really, what are you trying to do? Kent I am trying to create rooms/tiles for a roguelike game in python. I have some of the game coded out but I am having trouble with the map and character movement.OK, so maybe you want something like this (I don't know what the initialrow of spaces is for in your post): room = ['',...'#.#', ...'#.#',...'#.#',...'#.#',...'#.##'] for line in room: ... print line...#.##.##.##.##.##Well, not quite like that. It looks like your original post is formatted for a proportional font; you will probably have better luck sticking toa fixed width font: room = ['',... '#..#',... '#..#',... '#..#', ... '#..#',... '#.##'] for line in room: print line...#..##..##..##..# #.##That looks more like a room. You will have to figure out how to organizeand print multiple rooms but maybe this will get you started on theright track...Kent -- Fatti non foste per viver come bruti, ma per seguir virtute e canoscenza - Dante AlighieriYou were not made to live like brutes, but to pursue virtue and knowledge ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor