Re: [Tutor] Refining Code
On 4/10/2014 6:26 PM, Saba Usmani wrote: My task is : Welcome to the tutor list. In what school are you learning Python? What version of Python? What operating system? What do you use to write and run your code? What Python elements have you studied so far? Your code can be greatly simplified by the application of tuples, lists, dictionaries, functions and/or classes. Requests: post in plain text rather than html (no formatting). This guarantees that all of us will be able to read your posts with ease. Also reply in such a way that a copy goes to tutor@python.org, to keep all of us in the loop. The rest of my comments follow the relevant part of your post. Please also reply in similar fashion. Avoid as much as possible "top posting". A food vending machine accepts 10p, 20p, 50p and £1 coins. One or more coins are inserted and the current credit is calculated and displayed. A product is selected from those available. The system checks to see if there is enough credit to purchase the product chosen. If there is not enough credit the system displays an error message. If there is enough credit it dispenses the product, updates the credit available and displays the remaining credit. Further selections can be made if there is enough credit. The vending machine simulation should have five products and prices. Design, code, test and evaluate a program for this simulation. I am glad to see this problem appear again. Recently it was sent to me privately by someone who claimed it was not homework! Critique of the specification: it is a bit vague (imprecise). I assume the instructor has a broad tolerance for what is delivered. In a business environment I'd want it a lot more precise. Often I have to help the user accomplish this, as many users don't know how to do this. it is a good idea to first develop a sample dialog from the specification, review that with the user, then code to reproduce that sample. Do this. Either review it with the instructor or forget that step. I have designed the following code, but would like to know how to make it more efficient without making it too complex as I am a beginner or is this fine? Efficient? Do you mean execution time? With today's processor speeds that is rarely an issue to be concerned about when first writing code. Complexity does not necessarily create efficiency. Also, how do I add a loop to this so that once one product has been dispensed the program asks the user if they would like to continue and purchase another product? Alan has given a suggestion already. Based on your code you already know how to use a while loop. What is mysterious about using it here? Code: print "Welcome to Snack Attack" snack1 = 0.40 snack2 = 0.75 snack3 = 1.20 snack4 = 0.99 snack5 = 0.50 insert = 0 You never use this variable! change = 0 This machine does not dispense change! currentCredit = 0.00 A = 0.10 B = 0.20 C = 0.50 D = 1.00 a = 0.10 b = 0.20 c = 0.50 d = 1.00 Never Never use floating values for money, as floating point cannot in general represent fractional values exactly. print "Menu" print "Snack 1: Snickers - £0.40" print "Snack 2: Doritos - £0.75 " print "Snack 3: J20 - £1.20" print "Snack 4: Oreos - £0.99" print "Snack 5: M&M's - £0.50" print "Exit?"- how do I make this a Boolean expression, so the user can respond with either yes or no? You don't. Better (as Alan suggested) use raw_input and treat users entries as character. There is no advantage to using input and integers and a lot of room for errors. choice = input("Select your snack: ") This does not agree with the specification - enter coin(s) first. The ensuing dialog also does not agree with the specification. You deposit one or more coins first, see the available credit. then choose a if choice==1: print " " print "You have selected Snickers, which cost £0.40" print "Please insert £0.40" while currentCredit < snack1: print "Please select which of these coins to insert; A:10p,B:20p,C:50p and D:£1" insert_coins = input("Insert coins: ") currentCredit = insert_coins + currentCredit Major problem here. As A user I'd enter (say) 20p. How does that get translated to a numeric value for adding? What should happen if I enter 30p, or 20x, or foo? print "Your current credit is £",currentCredit This assumes that credit less than £1 will be reported as a fraction of a £. How will you handle this fraction? else: change_given=currentCredit-snack1 print " " print "Your change is £",change_given print "Your Snickers have been dispensed...Enjoy!" elif choice==2: print "You have selected Doritos, which cost £0.75" print "Please insert £0.75" while currentCredit print "Please select which of these coins to insert; A:10p,B:20p,C:50p and D:£1" insert_coins = input("Enter coins: ") currentCredit = insert_coins + currentCredit print "Your current
Re: [Tutor] Creating an Invalid message for user
Saba Usmani Wrote in message: > > You posted in html so I can't quote your code, but why aren't you using int() to convert in one call? Second argument is the base to be used. value = int ("10011", 2) othervalue = int ("234") # default to decimal -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Creating an Invalid message for user
On 11/04/2014 21:58, Saba Usmani wrote: Hi, I am meant to design code for a program that converts from binary number to decimal and vice versa. This is what i have so far: print "Welcome to the binary and decimal converter" loop = True while loop: bord = raw_input("Enter b for binary or d decimal or exit to exit") if bord == "b": d = 0 b = 0 factor = 1; b = raw_input ("Enter Binary Number:") b=b.lstrip("0") b = int(b) while(b > 0): if((int(b) % 10) == 1): d += factor b /= 10 factor = factor * 2 print "The Decimal Number is: ", d elif bord == "d": x=0 n=int(input('Enter Decimal Number: ')) x=n k=[] # array while (n>0): a=int(float(n%2)) k.append(a) n=(n-a)/2 k.append(0) string="" for j in k[::-1]: string=string+str(j) print('The binary Number for %d is %s'%(x, string)) elif bord == "exit" : print "Goodbye" loop = False - This code does not recognize invalid inputs e.g in the binary to decimal conversion, if I enter 10021 it will not inform me,the user, that the input is invalid. The same problem occurs with the decimal to binary conversion - if i enter 123&&gf I am not told to try again with a valid input - how do I implement this in the code above Thanks Saba https://docs.python.org/3/tutorial/errors.html#handling-exceptions is as good a starting point as any. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Creating an Invalid message for user
Hi, I am meant to design code for a program that converts from binary number to decimal and vice versa. This is what i have so far: print "Welcome to the binary and decimal converter"loop = Truewhile loop: bord = raw_input("Enter b for binary or d decimal or exit to exit")if bord == "b":d = 0b = 0factor = 1;b = raw_input ("Enter Binary Number:")b=b.lstrip("0")b = int(b) while(b > 0):if((int(b) % 10) == 1):d += factor b /= 10factor = factor * 2print "The Decimal Number is: ", d elif bord == "d":x=0n=int(input('Enter Decimal Number: '))x=nk=[] # arraywhile (n>0): a=int(float(n%2))k.append(a)n=(n-a)/2 k.append(0)string=""for j in k[::-1]: string=string+str(j)print('The binary Number for %d is %s'%(x, string)) elif bord == "exit" :print "Goodbye"loop = False - This code does not recognize invalid inputs e.g in the binary to decimal conversion, if I enter 10021 it will not inform me,the user, that the input is invalid. The same problem occurs with the decimal to binary conversion - if i enter 123&&gf I am not told to try again with a valid input - how do I implement this in the code above ThanksSaba___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] improving speed using and recalling C functions
Ok guys, when I wrote that email I was excited for the apparent speed increasing (it was jumping the bottleneck for loop for the reason peter otten outlined). Now, instead the changes, the speed is not improved (the code still running from this morning and it's at one forth of the dataset). What can I do to speed it up? Thanks Gabriele sent from Samsung Mobile Il giorno 11/apr/2014 17:00, "Danny Yoo" ha scritto: > On Fri, Apr 11, 2014 at 1:01 PM, Gabriele Brambilla > wrote: > > Yes, > > but I want to make a C extension to run faster a function from > > scipy.interpolate (interp1d) > > > Just to emphasis: I believe your goal should be: "I want to make my > program fast." > > Your goal should probably not be: "I want to write a C extension". > I'm not saying that writing a C extension is necessarily wrong, and it > may be that writing a C extension will make your program fast. But > this approach may not be the easiest or most maintainable approach to > improving your program's performance. > > Using C is not without its costs and risks. As soon as you are in C > territory, the seat belts are off. Just recall the craziness that > happened this week with regards to programs written in low-level > languages like C. Explicitly: http://heartbleed.com. If you are > writing with C, you have to be very, very delicate with your code. > Experts get it wrong, with severe consequences. > > This is why the focus on C extensions to get speed disturbs me so > much: it assumes that C is a safe language to use. It's not, > especially for beginners. We should strongly discourage low-level > languages unless there is some overriding concern. For scientific > calculations like the ones you are doing, you should place a premium > on getting a right answer, and not just a fast answer. > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] improving speed using and recalling C functions
On Fri, Apr 11, 2014 at 1:01 PM, Gabriele Brambilla wrote: > Yes, > but I want to make a C extension to run faster a function from > scipy.interpolate (interp1d) > > It woulldn't change anything? This is precisely why you want to drive your optimization based on what the profiler is telling you. Look at the profiler's output again, closely: --- 31594963 function calls in 103.708 seconds Ordered by: internal time List reduced from 47 to 20 due to restriction <20> ncalls tottime percall cumtime percall filename:lineno(function) 1 57.133 57.133 103.692 103.692 skymapsI.py:44(mymain) 1768329.8980.000 11.7100.000 interpolate.py:394(_call_linear) 181010007.8080.0007.8080.000 {method 'write' of 'file' objects} 12378243.7940.0003.7940.000 {numpy.core.multiarray.array} 10010003.6100.000 38.3830.000 instruments.py:10(kappa) 3536643.3140.0003.3140.000 {method 'reduce' of 'numpy.ufunc' [cutting some content] --- About 8% of the time in your program is being spent in interpolate.py. But this is in SciPy code, so it is likely difficult to rewrite. Also note that the amount of time being spent on merely writing the output is about that much time too! That's what the profile is saying, qualitatively. And on the other hand, the code in skymapsI.mymain is still a target worthy of your attention. Compare how much time it was taking before we started investigating it. Before, it took 75% of the total runtime of your program. We improved upon that a lot with a few small changes. But it's still taking 55% of the total time of your program's running. If you look at the rest of the profiler's output, we know that everything else is fairly inconsequential. That's why we're pushing you to look at the data. Trust the profiler. Work on the thing that is contributing most to the cost of your program: continue trying to improve the code in skymapsI.mymain. I am fairly certain there is still some low-hanging fruit there. The profile you want to see, eventually, is one where the computation is being done mostly in numpy code. But as we can see now, the numpy code is barely contributing to the runtime. That's a situation that needs improvement. Peter Otten's offer to help you use NumPy more effectively is one you should take seriously. Good luck! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] improving speed using and recalling C functions
On Fri, Apr 11, 2014 at 1:01 PM, Gabriele Brambilla wrote: > Yes, > but I want to make a C extension to run faster a function from > scipy.interpolate (interp1d) Just to emphasis: I believe your goal should be: "I want to make my program fast." Your goal should probably not be: "I want to write a C extension". I'm not saying that writing a C extension is necessarily wrong, and it may be that writing a C extension will make your program fast. But this approach may not be the easiest or most maintainable approach to improving your program's performance. Using C is not without its costs and risks. As soon as you are in C territory, the seat belts are off. Just recall the craziness that happened this week with regards to programs written in low-level languages like C. Explicitly: http://heartbleed.com. If you are writing with C, you have to be very, very delicate with your code. Experts get it wrong, with severe consequences. This is why the focus on C extensions to get speed disturbs me so much: it assumes that C is a safe language to use. It's not, especially for beginners. We should strongly discourage low-level languages unless there is some overriding concern. For scientific calculations like the ones you are doing, you should place a premium on getting a right answer, and not just a fast answer. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Fwd: improving speed using and recalling C functions
I forget the reply all -- Forwarded message -- From: Gabriele Brambilla Date: 2014-04-11 16:03 GMT-04:00 Subject: Re: [Tutor] improving speed using and recalling C functions To: Peter Otten <__pete...@web.de> you are right. probably this is the problem. thanks Gabriele 2014-04-11 15:35 GMT-04:00 Peter Otten <__pete...@web.de>: Gabriele Brambilla wrote: > > > ok, it seems that the code don't enter in this for loop > > > > for gammar, MYMAP in zip(gmlis, MYMAPS): > > > > I don't understand why. > > You have two variables with similar names, gmlis and gmils: > > >> gmlis = [] > > >> gmils=[my_parts[7], my_parts[8], my_parts[9], > >> my_parts[10], my_parts[11]] > > >> for gammar, MYMAP in zip(gmlis, MYMAPS): > > I assume you wanted > >for gammar, MYMAP in zip(gmils, MYMAPS): > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] improving speed using and recalling C functions
Yes, but I want to make a C extension to run faster a function from scipy.interpolate (interp1d) It woulldn't change anything? thanks Gabriele 2014-04-11 14:47 GMT-04:00 Alan Gauld : > On 11/04/14 09:59, Peter Otten wrote: > >> Gabriele Brambilla wrote: >> >> Anyway I would like to try to speed it up using C functions >>> >> ... >> >> posted looks like it has great potential for speed-up by replacing the >> inner >> loops with numpy array operations. >> > > And in case its not obvious much(most?) of numPy consists > of C functions. So by using NumPy you are usually using > C code not native Python. > > That's what I alluded to in my first post on this thread: > there are other libraries who have trod this route before > and done the work for you. > > HTH > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] improving speed using and recalling C functions
Gabriele Brambilla wrote: > ok, it seems that the code don't enter in this for loop > > for gammar, MYMAP in zip(gmlis, MYMAPS): > > I don't understand why. You have two variables with similar names, gmlis and gmils: >> gmlis = [] >> gmils=[my_parts[7], my_parts[8], my_parts[9], >> my_parts[10], my_parts[11]] >> for gammar, MYMAP in zip(gmlis, MYMAPS): I assume you wanted for gammar, MYMAP in zip(gmils, MYMAPS): ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Range within a range
On 4/11/2014 1:13 PM, Andoni Gorostiza wrote: Hi tutor. I need your help with something I don't understand. In the tutorial, it mentions an example of a range within a range. I'll keep it simplified. How exactly does this work? I'll provide a few examples. >>> for x in range(0,5): ...for n in range(0,5): ... print(x) >>> for x in range(0,5): ...for n in range(0,5) ... print(n) This one comes from the tutorial: >>>for n in range(2, 10): ... for x in range(2, n): ... if n % x == 0: ... print(n, 'equals', x, '*', n//x) ... break ... else: ... # loop fell through without finding a factor ... print(n, 'is a prime number') ... 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3 Can you explain what is going on? We could but that will not help you learn. Instead I recommend with pencil and paper you play computer - "execute" (write) the code one step at a time and write down what happens. Very simple example: execute: change: for x in range(0,2): x == 0 for n in range(0,2): n == 0 print(x) output == 0 next for n n == 1 print(x) output == 0 next for x x == 1 for n in range(0,2): n == 0 print(x) output == 1 keep going - at each step write what executes and what changes or happens When you run into an operation you don't understand stop and either - look it up - ask this list ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to make comparison work
Excellent. I guess I never read through the class stuff in learning python(its a great book, but very detailed) Now I know better! -- http://about.me/greggmartinson On Fri, Apr 11, 2014 at 3:32 AM, Peter Otten <__pete...@web.de> wrote: > Gregg Martinson wrote: > > > I have been working through a fairly simple process to teach myself > python > > and I am running into a problem with a comparison. Can anyone tell me > > where I am going wrong? > > > > #!/usr/bin/env python > > > > class Team(object): > > code = "" > > opponents_debated=[] > > wins=0 > > losses=0 > > competitors=[] > > Defining the 'competitors' list here means that it is shared by all Team > instances. As soon as any team A has debated with a team B B is added to > this list. As any team immediately adds itself to the list no debate will > ever take place. > > Solution: instead of a class attribute make the list an instance attribute > by moving the definition into the initialiser: > > > > > def __init__(self, code): > self.competitors = [] > > self.code = code > > self.competitors.append(code) > > #self.school_teams.append(code) > > Note that the difference between class and instance attributes exists for > all attributes, but may not lead to an error when you rebind instead of > mutating the attribute: > > >>> class T: > ... wins = 0 > ... def win(self): > ... self.wins = self.wins + 1 > ... > >>> a = T() > >>> b = T() > >>> a.win() > >>> a.win() > >>> b.win() > >>> a.wins > 2 > >>> b.wins > 1 > >>> T.wins > 0 > > That is because the first time win() is called on an instance > > self.wins = self.wins + 1 > > The instance attribute is not found and the right side falls back to look > up > self.wins in the class, i. e. the first time you are effectively running > > self.wins = T.wins + 1 > > The left-hand side always denotes an assignment to the instance, so T.wins > will always remain 0. > > It is still good practice to define all attributes that are meant to be > instance attributes in the initialiser: > > class Team: > def __init__(self, code): > self.wins = 0 > self.losses = 0 > ... > > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Range within a range
Hi tutor. I need your help with something I don't understand. In the tutorial, it mentions an example of a range within a range. I'll keep it simplified. How exactly does this work? I'll provide a few examples. >>> for x in range(0,5): ...for n in range(0,5): ... print(x) >>> for x in range(0,5): ...for n in range(0,5) ... print(n) This one comes from the tutorial: >>> for n in range(2, 10): ... for x in range(2, n): ... if n % x == 0: ... >>> print(n, 'equals', x, '*', n//x) ... break ... else: ... # loop fell >>> through without finding a factor ... print(n, 'is a prime number') ... 2 >>> is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 >>> equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3 Can you explain what is going on?___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] improving speed using and recalling C functions
On 11/04/14 09:59, Peter Otten wrote: Gabriele Brambilla wrote: Anyway I would like to try to speed it up using C functions ... posted looks like it has great potential for speed-up by replacing the inner loops with numpy array operations. And in case its not obvious much(most?) of numPy consists of C functions. So by using NumPy you are usually using C code not native Python. That's what I alluded to in my first post on this thread: there are other libraries who have trod this route before and done the work for you. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] improving speed using and recalling C functions
this is the profile for a sample of 1000 elements Fri Apr 11 10:21:21 2014restats 31594963 function calls in 103.708 seconds Ordered by: internal time List reduced from 47 to 20 due to restriction <20> ncalls tottime percall cumtime percall filename:lineno(function) 1 57.133 57.133 103.692 103.692 skymapsI.py:44(mymain) 1768329.8980.000 11.7100.000 interpolate.py:394(_call_linear) 181010007.8080.0007.8080.000 {method 'write' of 'file' objects} 12378243.7940.0003.7940.000 {numpy.core.multiarray.array} 10010003.6100.000 38.3830.000 instruments.py:10(kappa) 3536643.3140.0003.3140.000 {method 'reduce' of 'numpy.ufunc' objects} 1768323.1570.0007.4280.000 interpolate.py:454(_check_bounds) 1768322.0740.000 10.2130.000 interpolate.py:330(__init__) 1768322.0530.000 21.5220.000 interpolate.py:443(_evaluate) 1768321.2530.0004.4040.000 polyint.py:82(_set_yi) 1768320.7690.0000.7690.000 {method 'clip' of 'numpy.ndarray' objects} 3536640.7060.0000.7060.000 {method 'reshape' of 'numpy.ndarra y' objects} 3536640.6670.0001.2050.000 numerictypes.py:735(issubdtype) 7073280.6370.0002.4510.000 numeric.py:392(asarray) 1768320.6010.000 23.5550.000 polyint.py:37(__call__) 3536640.5690.0003.8830.000 _methods.py:31(_any) 1768320.5040.0001.4290.000 polyint.py:74(_reshape_yi) 1768320.4730.0000.4730.000 {method 'searchsorted' of 'numpy.n darray' objects} 1768320.4400.0001.6450.000 polyint.py:102(_set_dtype) 1768320.4260.0004.8300.000 polyint.py:30(__init__) thanks Gabriele 2014-04-11 10:18 GMT-04:00 Gabriele Brambilla < gb.gabrielebrambi...@gmail.com>: > ok > modifying the for in this way (zipping an array of matrix drive it crazy) > it works > > dko=0 > > for gammar in gmils: > > > omC = (1.5)*(gammar**3)*c/(rho*rlc) > > gig = omC*hcut/eVtoErg > > > #check the single emission > > > > for w in eel: > > omega = > (10**(w*stepENE+Lemin))*eVtoErg/hcut > > x = omega/omC > > kap = instruments.kappa(x) > > Iom = (1.732050808/c)*(e**2)*gammar*kap > #jackson dI/domega > > P = Iom*(c/(rho*rlc))/(2*pi) #jackson P > > phps = P/(hcut*omega) #photons per second > > www = phps/(stepPHA*sin(zobs)*stepOB) > > MYMAPS[dko][i,j,w] += www > > dko += 1 > > > > count = count + 1 > > Now I will tell you how much it takes. > > Thanks > > Gabriele > > > > 2014-04-11 10:05 GMT-04:00 Gabriele Brambilla < > gb.gabrielebrambi...@gmail.com>: > > ok, it seems that the code don't enter in this for loop >> >> for gammar, MYMAP in zip(gmlis, MYMAPS): >> >> I don't understand why. >> >> Thanks >> >> Gabriele >> >> >> 2014-04-11 9:56 GMT-04:00 Gabriele Brambilla < >> gb.gabrielebrambi...@gmail.com>: >> >> Hi, I'm sorry but there is a big problem. >>> the code is producing empty file.dat. >>> >>> I think it's because of this that previously I have done that strange >>> trick of myinternet... >>> >>> So: >>> >>> for my_line in open('data.dat'): >>> >>> myinternet = [] >>> >>> gmlis = [] >>> >>> print('reading the line', count, '/599378') >>> >>> my_parts = [float(i) for i in my_line.split()] >>> >>> phase = my_parts[4] >>> >>> zobs = my_parts[5] >>> >>> rho = my_parts[6] >>> >>> >>> >>> gmils=[my_parts[7], my_parts[8], my_parts[9], >>> my_parts[10], my_parts[11]] >>> >>> >>> >>> i = int((phase-phamin)/stepPHA) >>> >>> j = int((zobs-obamin)/stepOB) >>> >>> >>> >>> for gammar, MYMAP in zip(gmlis, MYMAPS): >>> >>> >>> >>> omC = (1.5)*(gammar**3)*c/(rho*rlc) >>> >>> gig = omC*hcut/eVtoErg >>> >>> #check the single emission >>> >>> >>> >>> for w in eel: >>> >>> omega = >>> (10**(w*stepENE+Lemin))*eVtoErg/hcut >>> >>> x = omega/omC >>> >>> kap = instruments.kappa(x) >>> >>> >>> Iom = (1.732050808/c)*(e**2)*gammar*kap >>> #jackson dI/domega >>> >>> P = Iom*(c/(rho*rlc))/(2*pi) #jackson P >>> >>> phps = P/(hcut*omega) #photons per second >>> >>>
Re: [Tutor] improving speed using and recalling C functions
ok modifying the for in this way (zipping an array of matrix drive it crazy) it works dko=0 for gammar in gmils: omC = (1.5)*(gammar**3)*c/(rho*rlc) gig = omC*hcut/eVtoErg #check the single emission for w in eel: omega = (10**(w*stepENE+Lemin))*eVtoErg/hcut x = omega/omC kap = instruments.kappa(x) Iom = (1.732050808/c)*(e**2)*gammar*kap #jackson dI/domega P = Iom*(c/(rho*rlc))/(2*pi) #jackson P phps = P/(hcut*omega) #photons per second www = phps/(stepPHA*sin(zobs)*stepOB) MYMAPS[dko][i,j,w] += www dko += 1 count = count + 1 Now I will tell you how much it takes. Thanks Gabriele 2014-04-11 10:05 GMT-04:00 Gabriele Brambilla < gb.gabrielebrambi...@gmail.com>: > ok, it seems that the code don't enter in this for loop > > for gammar, MYMAP in zip(gmlis, MYMAPS): > > I don't understand why. > > Thanks > > Gabriele > > > 2014-04-11 9:56 GMT-04:00 Gabriele Brambilla < > gb.gabrielebrambi...@gmail.com>: > > Hi, I'm sorry but there is a big problem. >> the code is producing empty file.dat. >> >> I think it's because of this that previously I have done that strange >> trick of myinternet... >> >> So: >> >> for my_line in open('data.dat'): >> >> myinternet = [] >> >> gmlis = [] >> >> print('reading the line', count, '/599378') >> >> my_parts = [float(i) for i in my_line.split()] >> >> phase = my_parts[4] >> >> zobs = my_parts[5] >> >> rho = my_parts[6] >> >> >> >> gmils=[my_parts[7], my_parts[8], my_parts[9], >> my_parts[10], my_parts[11]] >> >> >> >> i = int((phase-phamin)/stepPHA) >> >> j = int((zobs-obamin)/stepOB) >> >> >> >> for gammar, MYMAP in zip(gmlis, MYMAPS): >> >> >> >> omC = (1.5)*(gammar**3)*c/(rho*rlc) >> >> gig = omC*hcut/eVtoErg >> >> #check the single emission >> >> >> >> for w in eel: >> >> omega = >> (10**(w*stepENE+Lemin))*eVtoErg/hcut >> >> x = omega/omC >> >> kap = instruments.kappa(x) >> >> Iom = (1.732050808/c)*(e**2)*gammar*kap >> #jackson dI/domega >> >> P = Iom*(c/(rho*rlc))/(2*pi) #jackson P >> >> phps = P/(hcut*omega) #photons per second >> >> www = phps/(stepPHA*sin(zobs)*stepOB) >> >> MYMAP[i,j,w] += www >> >> >> >> count = count + 1 >> >> when I exit here the MYMAP matrix has all the cells = 0. >> >> Now I will try to fiugre it out why. >> >> Thanks >> >> Gabriele >> >> >> >> 2014-04-11 9:20 GMT-04:00 Gabriele Brambilla < >> gb.gabrielebrambi...@gmail.com>: >> >> Hi Danny, >>> I'm quiet impressed. >>> the program takes near 30 minutes instead of more than 8 hours! >>> >>> this is the profile: >>> Fri Apr 11 09:14:04 2014restats >>> >>> 19532732 function calls in 2105.024 seconds >>> >>>Ordered by: internal time >>> >>>ncalls tottime percall cumtime percall filename:lineno(function) >>> 1 2087.606 2087.606 2105.006 2105.006 skymapsI.py:44(mymain) >>> 18101000 12.7570.000 12.7570.000 {method 'write' of 'file' >>> objects} >>> >>>7158533.4730.0003.4730.000 {method 'split' of 'str' >>> objects} >>>7158541.1620.0001.1620.000 {zip} >>> 10.0180.018 2105.024 2105.024 :1() >>> 60.0060.0010.0060.001 {open} >>> 50.0020.0000.0020.000 {method 'close' of 'file' >>> objects} >>> >>> 10.0000.0000.0000.000 >>> function_base.py:8(linspace) >>> 50.0000.0000.0000.000 >>> {numpy.core.multiarray.zeros} >>> 10.0000.0000.0000.000 >>> function_base.py:93(logspace) >>> 10.0000.0000.0000.000 >>> {numpy.core.multiarray.arange} >>> 30.0000.0000.0000.000 {range} >>> 10.0000.0000.0000.000 {method 'disable' of >>> '_lsprof.Prof >>> iler' objects} >>> >>> I hope to have similar problems in the future to learn better how to do >>> with them! >>> but in the profile I don't see any operation regarding reading the file >>> or the mathematical operations...are them hidden in mymain()? >>> >>> thanks >>> >>> Gabriele >>> >>> >>> >>> >>> 2014-04-10 21:38 GMT-04:00 Danny Yoo : >>> >>> >
Re: [Tutor] improving speed using and recalling C functions
ok, it seems that the code don't enter in this for loop for gammar, MYMAP in zip(gmlis, MYMAPS): I don't understand why. Thanks Gabriele 2014-04-11 9:56 GMT-04:00 Gabriele Brambilla : > Hi, I'm sorry but there is a big problem. > the code is producing empty file.dat. > > I think it's because of this that previously I have done that strange > trick of myinternet... > > So: > > for my_line in open('data.dat'): > > myinternet = [] > > gmlis = [] > > print('reading the line', count, '/599378') > > my_parts = [float(i) for i in my_line.split()] > > phase = my_parts[4] > > zobs = my_parts[5] > > rho = my_parts[6] > > > > gmils=[my_parts[7], my_parts[8], my_parts[9], > my_parts[10], my_parts[11]] > > > > i = int((phase-phamin)/stepPHA) > > j = int((zobs-obamin)/stepOB) > > > > for gammar, MYMAP in zip(gmlis, MYMAPS): > > > > omC = (1.5)*(gammar**3)*c/(rho*rlc) > > gig = omC*hcut/eVtoErg > > #check the single emission > > > > for w in eel: > > omega = > (10**(w*stepENE+Lemin))*eVtoErg/hcut > > x = omega/omC > > kap = instruments.kappa(x) > > Iom = (1.732050808/c)*(e**2)*gammar*kap > #jackson dI/domega > > P = Iom*(c/(rho*rlc))/(2*pi) #jackson P > > phps = P/(hcut*omega) #photons per second > > www = phps/(stepPHA*sin(zobs)*stepOB) > > MYMAP[i,j,w] += www > > > > count = count + 1 > > when I exit here the MYMAP matrix has all the cells = 0. > > Now I will try to fiugre it out why. > > Thanks > > Gabriele > > > > 2014-04-11 9:20 GMT-04:00 Gabriele Brambilla < > gb.gabrielebrambi...@gmail.com>: > > Hi Danny, >> I'm quiet impressed. >> the program takes near 30 minutes instead of more than 8 hours! >> >> this is the profile: >> Fri Apr 11 09:14:04 2014restats >> >> 19532732 function calls in 2105.024 seconds >> >>Ordered by: internal time >> >>ncalls tottime percall cumtime percall filename:lineno(function) >> 1 2087.606 2087.606 2105.006 2105.006 skymapsI.py:44(mymain) >> 18101000 12.7570.000 12.7570.000 {method 'write' of 'file' >> objects} >> >>7158533.4730.0003.4730.000 {method 'split' of 'str' >> objects} >>7158541.1620.0001.1620.000 {zip} >> 10.0180.018 2105.024 2105.024 :1() >> 60.0060.0010.0060.001 {open} >> 50.0020.0000.0020.000 {method 'close' of 'file' >> objects} >> >> 10.0000.0000.0000.000 function_base.py:8(linspace) >> 50.0000.0000.0000.000 >> {numpy.core.multiarray.zeros} >> 10.0000.0000.0000.000 >> function_base.py:93(logspace) >> 10.0000.0000.0000.000 >> {numpy.core.multiarray.arange} >> 30.0000.0000.0000.000 {range} >> 10.0000.0000.0000.000 {method 'disable' of >> '_lsprof.Prof >> iler' objects} >> >> I hope to have similar problems in the future to learn better how to do >> with them! >> but in the profile I don't see any operation regarding reading the file >> or the mathematical operations...are them hidden in mymain()? >> >> thanks >> >> Gabriele >> >> >> >> >> 2014-04-10 21:38 GMT-04:00 Danny Yoo : >> >> > Comment: You are looping over your sliced eel five times. Do you >>> >need to? I like eel salad a great deal, as well, but, how about: >>> > >>> > >>> >for k in eel: >>> >MYMAP1[i, j, k] = MYMAP1[i, j, k] + myinternet[oo] >>> >MYMAP2[i, j, k] = MYMAP2[i, j, k] + myinternet[oo] >>> >MYMAP3[i, j, k] = MYMAP3[i, j, k] + myinternet[oo] >>> >MYMAP4[i, j, k] = MYMAP4[i, j, k] + myinternet[oo] >>> >MYMAP5[i, j, k] = MYMAP5[i, j, k] + myinternet[oo] >>> >oo = oo + 1 >>> >>> >>> Hi Gabriele, >>> >>> Also note that, when Martin looked at this part of the code, he >>> unfortunately misinterpreted its effect; Martin's proposed rewrite >>> here does not preserve the meaning of the original code. But rather >>> than wag my finger at how Martin interpreted the code, I'd rather make >>> the observation that this is a warning sign that the original code >>> here was not easy to understand. >>> >> >> > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] improving speed using and recalling C functions
Hi, I'm sorry but there is a big problem. the code is producing empty file.dat. I think it's because of this that previously I have done that strange trick of myinternet... So: for my_line in open('data.dat'): myinternet = [] gmlis = [] print('reading the line', count, '/599378') my_parts = [float(i) for i in my_line.split()] phase = my_parts[4] zobs = my_parts[5] rho = my_parts[6] gmils=[my_parts[7], my_parts[8], my_parts[9], my_parts[10], my_parts[11]] i = int((phase-phamin)/stepPHA) j = int((zobs-obamin)/stepOB) for gammar, MYMAP in zip(gmlis, MYMAPS): omC = (1.5)*(gammar**3)*c/(rho*rlc) gig = omC*hcut/eVtoErg #check the single emission for w in eel: omega = (10**(w*stepENE+Lemin))*eVtoErg/hcut x = omega/omC kap = instruments.kappa(x) Iom = (1.732050808/c)*(e**2)*gammar*kap #jackson dI/domega P = Iom*(c/(rho*rlc))/(2*pi) #jackson P phps = P/(hcut*omega) #photons per second www = phps/(stepPHA*sin(zobs)*stepOB) MYMAP[i,j,w] += www count = count + 1 when I exit here the MYMAP matrix has all the cells = 0. Now I will try to fiugre it out why. Thanks Gabriele 2014-04-11 9:20 GMT-04:00 Gabriele Brambilla : > Hi Danny, > I'm quiet impressed. > the program takes near 30 minutes instead of more than 8 hours! > > this is the profile: > Fri Apr 11 09:14:04 2014restats > > 19532732 function calls in 2105.024 seconds > >Ordered by: internal time > >ncalls tottime percall cumtime percall filename:lineno(function) > 1 2087.606 2087.606 2105.006 2105.006 skymapsI.py:44(mymain) > 18101000 12.7570.000 12.7570.000 {method 'write' of 'file' > objects} > >7158533.4730.0003.4730.000 {method 'split' of 'str' > objects} >7158541.1620.0001.1620.000 {zip} > 10.0180.018 2105.024 2105.024 :1() > 60.0060.0010.0060.001 {open} > 50.0020.0000.0020.000 {method 'close' of 'file' > objects} > > 10.0000.0000.0000.000 function_base.py:8(linspace) > 50.0000.0000.0000.000 {numpy.core.multiarray.zeros} > 10.0000.0000.0000.000 function_base.py:93(logspace) > 10.0000.0000.0000.000 > {numpy.core.multiarray.arange} > 30.0000.0000.0000.000 {range} > 10.0000.0000.0000.000 {method 'disable' of > '_lsprof.Prof > iler' objects} > > I hope to have similar problems in the future to learn better how to do > with them! > but in the profile I don't see any operation regarding reading the file or > the mathematical operations...are them hidden in mymain()? > > thanks > > Gabriele > > > > > 2014-04-10 21:38 GMT-04:00 Danny Yoo : > > > Comment: You are looping over your sliced eel five times. Do you >> >need to? I like eel salad a great deal, as well, but, how about: >> > >> > >> >for k in eel: >> >MYMAP1[i, j, k] = MYMAP1[i, j, k] + myinternet[oo] >> >MYMAP2[i, j, k] = MYMAP2[i, j, k] + myinternet[oo] >> >MYMAP3[i, j, k] = MYMAP3[i, j, k] + myinternet[oo] >> >MYMAP4[i, j, k] = MYMAP4[i, j, k] + myinternet[oo] >> >MYMAP5[i, j, k] = MYMAP5[i, j, k] + myinternet[oo] >> >oo = oo + 1 >> >> >> Hi Gabriele, >> >> Also note that, when Martin looked at this part of the code, he >> unfortunately misinterpreted its effect; Martin's proposed rewrite >> here does not preserve the meaning of the original code. But rather >> than wag my finger at how Martin interpreted the code, I'd rather make >> the observation that this is a warning sign that the original code >> here was not easy to understand. >> > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] improving speed using and recalling C functions
Hi Danny, I'm quiet impressed. the program takes near 30 minutes instead of more than 8 hours! this is the profile: Fri Apr 11 09:14:04 2014restats 19532732 function calls in 2105.024 seconds Ordered by: internal time ncalls tottime percall cumtime percall filename:lineno(function) 1 2087.606 2087.606 2105.006 2105.006 skymapsI.py:44(mymain) 18101000 12.7570.000 12.7570.000 {method 'write' of 'file' objects} 7158533.4730.0003.4730.000 {method 'split' of 'str' objects} 7158541.1620.0001.1620.000 {zip} 10.0180.018 2105.024 2105.024 :1() 60.0060.0010.0060.001 {open} 50.0020.0000.0020.000 {method 'close' of 'file' objects} 10.0000.0000.0000.000 function_base.py:8(linspace) 50.0000.0000.0000.000 {numpy.core.multiarray.zeros} 10.0000.0000.0000.000 function_base.py:93(logspace) 10.0000.0000.0000.000 {numpy.core.multiarray.arange} 30.0000.0000.0000.000 {range} 10.0000.0000.0000.000 {method 'disable' of '_lsprof.Prof iler' objects} I hope to have similar problems in the future to learn better how to do with them! but in the profile I don't see any operation regarding reading the file or the mathematical operations...are them hidden in mymain()? thanks Gabriele 2014-04-10 21:38 GMT-04:00 Danny Yoo : > > Comment: You are looping over your sliced eel five times. Do you > >need to? I like eel salad a great deal, as well, but, how about: > > > > > >for k in eel: > >MYMAP1[i, j, k] = MYMAP1[i, j, k] + myinternet[oo] > >MYMAP2[i, j, k] = MYMAP2[i, j, k] + myinternet[oo] > >MYMAP3[i, j, k] = MYMAP3[i, j, k] + myinternet[oo] > >MYMAP4[i, j, k] = MYMAP4[i, j, k] + myinternet[oo] > >MYMAP5[i, j, k] = MYMAP5[i, j, k] + myinternet[oo] > >oo = oo + 1 > > > Hi Gabriele, > > Also note that, when Martin looked at this part of the code, he > unfortunately misinterpreted its effect; Martin's proposed rewrite > here does not preserve the meaning of the original code. But rather > than wag my finger at how Martin interpreted the code, I'd rather make > the observation that this is a warning sign that the original code > here was not easy to understand. > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] improving speed using and recalling C functions
I think I have Cython already installed with Anaconda. How it works? Thanks Gabriele 2014-04-11 8:16 GMT-04:00 Albert-Jan Roskam : > > > From: Gabriele Brambilla > >To: Danny Yoo > >Cc: python tutor > >Sent: Friday, April 11, 2014 5:30 AM > >Subject: Re: [Tutor] improving speed using and recalling C functions > > > > > > > >Hi Danny, > >I followed your suggestion. > >Tomorrow morning I will run this new version of the code. > > > > > >Now using a sample of 81 elements (instead of 60) the profile returns: > > > > > >Thu Apr 10 23:25:59 2014restats > > > > > > 18101188 function calls in 1218.626 seconds > > > > > > Ordered by: internal time > > List reduced from 13 to 10 due to restriction <10> > > > > > > ncalls tottime percall cumtime percall filename:lineno(function) > >1 1015.803 1015.803 1218.334 1218.334 skymaps5.py:44(mymain) > > 18101000 202.4900.000 202.4900.000 {method 'write' of 'file' > objects} > > > > > >10.2920.292 1218.626 1218.626 :1() > >60.0290.0050.0290.005 {open} > >50.0100.0020.0100.002 {method 'close' of 'file' > objects} > > > > > > 810.0020.0000.0020.000 {method 'split' of 'str' > objects} > > 820.0010.0000.0010.000 {zip} > >10.0000.0000.0000.000 function_base.py:8(linspace) > >10.0000.0000.0000.000 > function_base.py:93(logspace) > >50.0000.0000.0000.000 > {numpy.core.multiarray.zeros} > > > > > >Anyway I would like to try to speed it up using C functions (and maybe > comparing the resuts of the two profile in the end) > >How can I do it now? Can I use Cython? > > If you have a compiler installed already it's just easy_install cython. > Writing Cython is not hard. That is, you easily get speed improvements. > It's in a .pyx file and once you're done you generate the .c and .so/.dll > files with a setup.py like below. Reason why I am posting this snippet is > the way to generate an annotated html file of your cython code. The whiter, > the more in C, the better. Yellow means stuff might still be improved more. > > * setup.py > from distutils.core import setup > from distutils.extension import Extension > from Cython.Distutils import build_ext > import Cython.Compiler.Options > Cython.Compiler.Options.annotate = True # < really handy > > setup( > cmdclass = {'build_ext': build_ext}, > ext_modules = [Extension("myModule", ["myModule.pyx"])] > > ) > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] improving speed using and recalling C functions
> From: Gabriele Brambilla >To: Danny Yoo >Cc: python tutor >Sent: Friday, April 11, 2014 5:30 AM >Subject: Re: [Tutor] improving speed using and recalling C functions > > > >Hi Danny, >I followed your suggestion. >Tomorrow morning I will run this new version of the code. > > >Now using a sample of 81 elements (instead of 60) the profile returns: > > >Thu Apr 10 23:25:59 2014 restats > > > 18101188 function calls in 1218.626 seconds > > > Ordered by: internal time > List reduced from 13 to 10 due to restriction <10> > > > ncalls tottime percall cumtime percall filename:lineno(function) > 1 1015.803 1015.803 1218.334 1218.334 skymaps5.py:44(mymain) > 18101000 202.490 0.000 202.490 0.000 {method 'write' of 'file' >objects} > > > 1 0.292 0.292 1218.626 1218.626 :1() > 6 0.029 0.005 0.029 0.005 {open} > 5 0.010 0.002 0.010 0.002 {method 'close' of 'file' >objects} > > > 81 0.002 0.000 0.002 0.000 {method 'split' of 'str' objects} > 82 0.001 0.000 0.001 0.000 {zip} > 1 0.000 0.000 0.000 0.000 function_base.py:8(linspace) > 1 0.000 0.000 0.000 0.000 function_base.py:93(logspace) > 5 0.000 0.000 0.000 0.000 {numpy.core.multiarray.zeros} > > >Anyway I would like to try to speed it up using C functions (and maybe >comparing the resuts of the two profile in the end) >How can I do it now? Can I use Cython? If you have a compiler installed already it's just easy_install cython. Writing Cython is not hard. That is, you easily get speed improvements. It's in a .pyx file and once you're done you generate the .c and .so/.dll files with a setup.py like below. Reason why I am posting this snippet is the way to generate an annotated html file of your cython code. The whiter, the more in C, the better. Yellow means stuff might still be improved more. * setup.py from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext import Cython.Compiler.Options Cython.Compiler.Options.annotate = True # < really handy setup( cmdclass = {'build_ext': build_ext}, ext_modules = [Extension("myModule", ["myModule.pyx"])] ) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] improving speed using and recalling C functions
Gabriele Brambilla wrote: > Anyway I would like to try to speed it up using C functions (and maybe > comparing the resuts of the two profile in the end) I can't help you on your chosen path, but let me emphasise that the code you posted looks like it has great potential for speed-up by replacing the inner loops with numpy array operations. If you post a small dataset somewhere and a version of the code that can run standalone (no undefined variables or libraries, no commandline arguments) I might even tinker with it myself to demonstrate this potential... ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to make comparison work
Gregg Martinson wrote: > I have been working through a fairly simple process to teach myself python > and I am running into a problem with a comparison. Can anyone tell me > where I am going wrong? > > #!/usr/bin/env python > > class Team(object): > code = "" > opponents_debated=[] > wins=0 > losses=0 > competitors=[] Defining the 'competitors' list here means that it is shared by all Team instances. As soon as any team A has debated with a team B B is added to this list. As any team immediately adds itself to the list no debate will ever take place. Solution: instead of a class attribute make the list an instance attribute by moving the definition into the initialiser: > > def __init__(self, code): self.competitors = [] > self.code = code > self.competitors.append(code) > #self.school_teams.append(code) Note that the difference between class and instance attributes exists for all attributes, but may not lead to an error when you rebind instead of mutating the attribute: >>> class T: ... wins = 0 ... def win(self): ... self.wins = self.wins + 1 ... >>> a = T() >>> b = T() >>> a.win() >>> a.win() >>> b.win() >>> a.wins 2 >>> b.wins 1 >>> T.wins 0 That is because the first time win() is called on an instance self.wins = self.wins + 1 The instance attribute is not found and the right side falls back to look up self.wins in the class, i. e. the first time you are effectively running self.wins = T.wins + 1 The left-hand side always denotes an assignment to the instance, so T.wins will always remain 0. It is still good practice to define all attributes that are meant to be instance attributes in the initialiser: class Team: def __init__(self, code): self.wins = 0 self.losses = 0 ... ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to make comparison work
On 11/04/14 00:27, Gregg Martinson wrote: I have been working through a fairly simple process to teach myself python and I am running into a problem with a comparison. Can anyone tell me where I am going wrong? #!/usr/bin/env python class Team(object): code = "" opponents_debated=[] wins=0 losses=0 competitors=[] All of these variables are class variables rather than instance variables. That means they are *shared* by all instances. def __init__(self, code): self.code = code self.competitors.append(code) #self.school_teams.append(code) So when you run init() you are changing the values for all your teams. I strongly suspect you want those variables inside init so that each object has its own value? HERE'S THE LOGIC PROBLEM def havedebated(self, otherTeam): print (self.code, "compares ", otherTeam, "is in",self.competitors) if otherTeam in self.competitors: return 1 else: return 0 When you do the comparison you are checking against the shared collection which will, I think, have all the teams in it, so it will always be true. I haven't studied that in detail but that's what a quick glance suggests to me. hth -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] How to make comparison work
I have been working through a fairly simple process to teach myself python and I am running into a problem with a comparison. Can anyone tell me where I am going wrong? #!/usr/bin/env python class Team(object): code = "" opponents_debated=[] wins=0 losses=0 competitors=[] def __init__(self, code): self.code = code self.competitors.append(code) #self.school_teams.append(code) HERE'S THE LOGIC PROBLEM def havedebated(self, otherTeam): print (self.code, "compares ", otherTeam, "is in",self.competitors) if otherTeam in self.competitors: return 1 else: return 0 def giveCode(self): return self.code def debates(self,otherteam): self.competitors.append(otherteam) def make_team(code): team = Team(code) return team #MAIN Program# myTeamCodes = ["a", "aa", "b", "bb", "c", "cc", "d"] # Make teams myTeams = [] #list of teams for x in myTeamCodes: myteam = make_team(x) myTeams.append(myteam) for x in myTeams: x.print_team() for x in myTeams: for y in myTeams: affteam=x.giveCode() negteam=y.giveCode() print (affteam," vs. ",negteam) #have the two teams debated? if x.havedebated(negteam): print("they have debated...") continue else: print("DEBATE!") #NEVER HAPPENS! x.debates(negteam) thiscode=x.giveCode(); othercode=y.giveCode(); print(thiscode,"debates ",othercode) -- http://about.me/greggmartinson ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Fwd: Refining Code
Forwarding to tutor; need to sleep tonight. -- Forwarded message -- From: Saba Usmani Date: Thu, Apr 10, 2014 at 11:35 PM Subject: Re: [Tutor] Refining Code To: Danny Yoo Hi, Yes I did use copy and paste sometimes- is that bad? How could you tell and what are the similarities between the snacks- why? Thanks Saba Sent from my iPhone > On 11 Apr 2014, at 03:05, "Danny Yoo" wrote: > > Hi Saba, > > Do you see any similarities between each of the snack choices? Do you > see any differences? > > (Did you happen to use copy-and-paste at any time when you wrote the program?) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor