Re: [Tutor] dict vs several variables?
Leam Hall wrote: On 02/17/2012 09:26 AM, Dave Angel wrote: There are two ways to think of a class. One is to hold various related data, and the other is to do operations on that data. If you just consider the first, then you could use a class like a dictionary whose keys are fixed (known at compile time). I think a class is the way to go for a couple reasons. First, of course, is that it pushes me to learn more. It also lets me encapsulate a lot of the work into one thing and keep the methods there. One word of caution. If you make just one do-it-all class with a single instance and use instance attributes as if they were global variable the improvement over the global dictionary is minimal. You still should strive to make dependencies explicit, e. g. prefer def add(a, b): return a + b over class DoItAll: def add_a_and_b(self): self.c = self.a + self.b ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dict vs several variables?
On 02/18/2012 03:39 AM, Peter Otten wrote: Leam Hall wrote: On 02/17/2012 09:26 AM, Dave Angel wrote: There are two ways to think of a class. One is to hold various related data, and the other is to do operations on that data. If you just consider the first, then you could use a class like a dictionary whose keys are fixed (known at compile time). I think a class is the way to go for a couple reasons. First, of course, is that it pushes me to learn more. It also lets me encapsulate a lot of the work into one thing and keep the methods there. One word of caution. If you make just one do-it-all class with a single instance and use instance attributes as if they were global variable the improvement over the global dictionary is minimal. You still should strive to make dependencies explicit, e. g. prefer def add(a, b): return a + b over class DoItAll: def add_a_and_b(self): self.c = self.a + self.b Understood. In this case I'm starting the application and there are two separate bits. I'm studying tkinter for the class I'm in so the GUI stuff is one module and the formulas are in another module. The reason I considered a global dict or a class is because all of the data bits are directly related. Dave angel wrote: class MyDiver(object): def __init__(self, depth, gasmix, time, rate): self.depth = int(depth) self.gasmix = int(gasmix) self.time = datetime.datetime(time) self.rate = float(rate) Which is a pretty good start, makes me think he's done scuba before. :) The object in question is a scuba dive. The user types in how deep they want to go, what gas mix they are on, how long they plan on staying, and what they think their air consumption rate will be. The formulas calculate absolute atmospheres which are used in other formulas, O2 concentration (a risk factor), how much of the daily increased O2 exposure the dive will create, and how much gas is needed to make that dive. If the program grew the only thing that might be pulled out is the air consumption rate. That would likely go into a diver object so there was a profile for each diver. However, at the moment the app is just giving you dive profile information so you can plan your bottom time and gas consumption. That's my thinking as of this morning. I need to go back and build unittests; will do so while moving it into a class. Should be fun and good learning! Leam ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] arrays, while loops
Hi I need some help with my program. I need to: Inside a getNumbers() function: Make an array that holds 7 elements - (got that done) make sure the numbers entered are greater than 0 and less than 1001 (can't get this) - is there a way to write a between statment or an or?? send the array to the aboveAverage () function What I can't get to work is the between 0 and 1001, and also where to make the array entries integer (I get an error saying can't compare string and integer) I also have to answer the three questions I have commented out at the end. I know this should be simple, but the more I read and try things, the more confused I get. Thanks for any suggestions! Here is what I have so far: amount = [0 for index in range (7)] size = len (amount) def getNumbers(): for index in range (size): amount[index] = input (Enter an amount: ) while amount[index] 0 or 1001: return (amount[index]) ##getNumbers() ## ##def aboveAverage(): ##total = 0.0 ## ##for value in amount: ##total +=amount[index] ##average = total/len(amount) ## ## ##getNumbers() ##def printData(): ## ##print (The numbers you entered from lowest to highest are: ) ##print (The average number is: ) ##print (You entered this many numbers above average: ) ## ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] arrays, while loops
On Sat, Feb 18, 2012 at 1:35 PM, Deborah Knoll dknol...@hotmail.com wrote: Hi I need some help with my program. I need to: Inside a getNumbers() function: Make an array that holds 7 elements - (got that done) make sure the numbers entered are greater than 0 and less than 1001 (can't get this) - is there a way to write a between statment or an or?? send the array to the aboveAverage () function What I can't get to work is the between 0 and 1001, and also where to make the array entries integer (I get an error saying can't compare string and integer) I also have to answer the three questions I have commented out at the end. I know this should be simple, but the more I read and try things, the more confused I get. Thanks for any suggestions! Here is what I have so far: amount = [0 for index in range (7)] size = len (amount) def getNumbers(): for index in range (size): amount[index] = input (Enter an amount: ) while amount[index] 0 or 1001: return (amount[index]) ##getNumbers() ## ##def aboveAverage(): ## total = 0.0 ## ## for value in amount: ## total +=amount[index] ## average = total/len(amount) ## ## ##getNumbers() ##def printData(): ## ##print (The numbers you entered from lowest to highest are: ) ##print (The average number is: ) ##print (You entered this many numbers above average: ) ## So, you need to get 7 numbers from the user, make sure they are between 0 and 1001, then report the numbers in sorted order - lowest to highest, report the average, and how many numbers are above the average. Since you are restricting the numbers allowed, you will need to figure out if the number is ok, and if not, tell the user, and ask again for a proper number. You could do something like this: def get_number(n): while 0 n 1001: n = input('Enter an number between 0 and 1001) return int(n) That will get you a single good number Now, to get 7 good numbers in your list you could do something like this: def get_numbers(amount): for i, a in enumerate(amount): # this will give you the index and the value in amount[i] amount[i] = get_number(a) return amount# this will return your amount list to the caller Now you just need to write 3 functions: the first to find the average, then one to tell you how many entries are greater than the average, and finally to sort the numbers from lowest to highest. Try working on that and come back with more questions -- Joel Goldstick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] arrays, while loops
On 18/02/2012 18:35, Deborah Knoll wrote: Hi I need some help with my program. I need to: Inside a getNumbers() function: Make an array that holds 7 elements - (got that done) make sure the numbers entered are greater than 0 and less than 1001 (can't get this) - is there a way to write a between statment or an or?? send the array to the aboveAverage () function What I can't get to work is the between 0 and 1001, and also where to make the array entries integer (I get an error saying can't compare string and integer) I also have to answer the three questions I have commented out at the end. I know this should be simple, but the more I read and try things, the more confused I get. Thanks for any suggestions! Here is what I have so far: amount = [0 for index in range (7)] This is outside getNumbers! Could be written as amount = [0] * 7. Better still amounts, see below. size = len (amount) You don't need this, because... def getNumbers(): for index in range (size): Usually written something like for amount in amounts: amount = ... amount[index] = input (Enter an amount: ) Input some strings into your list overwriting the original integers. while amount[index]0 or 1001: Whoops. You'll first need to convert the input numbers with an appropriate function such as int or float, which you can do at the input stage. Python also lets you chain comparisons so this is allowed. while 0 amount[index] 1001: return (amount[index]) No point to this as amount is external to getNumbers. ##getNumbers() ## ##def aboveAverage(): ##total = 0.0 ## ##for value in amount: ##total +=amount[index] You don't need the loop, use the sum built-in function. ##average = total/len(amount) ## ## ##getNumbers() ##def printData(): ## ##print (The numbers you entered from lowest to highest are: ) Use built-in functions min and max. ##print (The average number is: ) ##print (You entered this many numbers above average: ) I'll leave this for you :) ## ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor HTH. -- Cheers. Mark Lawrence. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] arrays, while loops
On 02/18/2012 01:35 PM, Deborah Knoll wrote: Hi I need some help with my program. I need to: First thing you need to do when asking a question is to establish what version of Python you're running, and on what OS . In this case OS probably doesn't matter, but version does. Mark Lawrence assumed you were running Python 3, while Joel and I are assuming Python 2.x. Inside a getNumbers() function: Make an array that holds 7 elements - (got that done) Python has a class array.array. But that's not what you're using. What you're actually using are lists. I almost skipped the query because I'm not that familiar with the array module. make sure the numbers entered are greater than 0 and less than 1001 (can't get this) - is there a way to write a between statment or an or?? You can use 'or' or 'and' in an expression, but not the way you did below. Anyway there is what you might call a between operation: if 0 n 1001: send the array to the aboveAverage () function What I can't get to work is the between 0 and 1001, and also where to make the array entries integer (I get an error saying can't compare string and integer) I also have to answer the three questions I have commented out at the end. I know this should be simple, but the more I read and try things, the more confused I get. Thanks for any suggestions! Before you write the code, you need to decide lots more things. But the first one is what should the program do if the user enters a value that's not within the range? Should it just crash, or should it prompt for a new value? And keep prompting till the user enters an acceptable number. I'll assume the latter. Here is what I have so far: amount = [0 for index in range (7)] Start with meaningful names. At the very least, when it's a list of amount values, call it amounts (plural). size = len (amount) def getNumbers(): for index in range (size): amount[index] = input (Enter an amount: ) The user may have already entered 7 wrong values. Now what? You want to catch each number as its being input, rather than wait till the end of the loop. This is calling out for another function. For now, pretend you've already written such a function. for index in range(size): amounts[index] = getinput(min, max) Now the function needs to return the list it has built. You weren't really going to use a global there, were you? return amounts knoll while amount[index]0 or 1001: return (amount[index]) Now you need to write a functiongetinput(min, max), that asks the user for input, and returns it if it's between min and max, but asks again if it's not. ##getNumbers() ## ##def aboveAverage(): You forgot to have the function take a list object. Call it amounts, if you like. Remember to change the references below. ##total = 0.0 ## ##for value in amount: ##total +=amount[index] ##average = total/len(amount) ## now it needs to return average. And in fact, this function should be called average(), since that's what it does. ## ##getNumbers() ##def printData(): ## ##print (The numbers you entered from lowest to highest are: ) Seems that if you sort the amounts list, you could print it pretty easily then. ##print (The average number is: ) You already wrote that. ##print (You entered this many numbers above average: ) ## This function should take a parameter called amounts, call average() on it, then loop through comparing each amount to that average: def aboveAverage(amounts): avg = average(amounts) count = 0 for amount in amounts: if : count += 1 return count -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] arrays, while loops
On 18/02/12 18:35, Deborah Knoll wrote: make sure the numbers entered are greater than 0 and less than 1001 (can't get this) - is there a way to write a between statment or an or?? Several replies have shown how to do between. To use or you would do: if n 0 or n 1001: # handle error else: store value ##def aboveAverage(): ## total = 0.0 ## ## for value in amount: ## total +=amount[index] ## average = total/len(amount) An alternative solution here uses a list comprehension def aboveAverage(amounts, ave): return len( [item for item in amounts if item ave] ) HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] list comprehension efficiency
Generally speaking, are list comprehensions more efficient that the equivalent for loop with interior conditionals for a given task? Do they compile down to the same Python byte code? Thanks, Bill Allen ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] list comprehension efficiency
On 19/02/2012 01:31, Bill Allen wrote: Generally speaking, are list comprehensions more efficient that the equivalent for loop with interior conditionals for a given task? Do they compile down to the same Python byte code? Thanks, Bill Allen ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Use the timeit module to answer Q1 and the dis module to answer Q2. -- Cheers. Mark Lawrence. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] list comprehension efficiency
Bill Allen wrote: Generally speaking, are list comprehensions more efficient that the equivalent for loop with interior conditionals for a given task? Do they compile down to the same Python byte code? It depends, and no. For-loops are more general, so there are loops that can't be written as list comprehensions. Consequently, so is the byte code generated. Python makes no attempt to analyse a for-loop and decide that it could be written as a list comp. Nor do list comps generate the exact same code as a for-loop: they can't, because the semantics are slightly different. (Specifically, a list comp is an atomic operation: either the whole thing succeeds, or the resultant list does not persist. That same does not apply to for-loops.) You can inspect the byte code produced by using the dis module. But, for the subset of possible for-loops which can be re-written as list comps, yes, list comps often are more efficient, as building the list can be performed at full C speed instead of at relatively slower Python speed. But don't over-estimate how big a difference that makes in practice. For trivial loops, it makes a big difference: py with Timer(): ... _ = [None for i in range(1)] ... time taken: 0.004692 seconds py py with Timer(): ... _ = [] ... for i in range(1): ... _.append(None) ... time taken: 0.020877 seconds but for loops that do actual, significant work, the difference becomes correspondingly less important: py def func(x): ... y = 2*i**3 - 15*i*i + 17*i + 3 ... z = x**0.5/(2*y**2 - 1) ... return (3*z)/(1+z)**1.25 ... py with Timer(): ... _ = [func(i) for i in range(1)] ... time taken: 0.210438 seconds py py with Timer(): ... _ = [] ... for i in range(1): ... _.append(func(i)) ... time taken: 0.250344 seconds If you're interested in using my Timer() code, you can find it here: http://code.activestate.com/recipes/577896-benchmark-code-with-the-with-statement/ Beware though, that you can't exit out of a list comp early. So if you have code like this: collection = [] for x in sorted(sequence): if x 10: break collection.append(x + 5) versus this: collection = [x+5 for x in sorted(sequence) if x = 10] Consider what happens if sequence = range(100). The for-loop does eleven iterations, the list-comp does a million. Guess which will be faster? :) -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] arrays, while loops
On 2/18/2012 1:35 PM, Deborah Knoll wrote: Hi [snip] You've received a (perhaps confusing and some incorrect) melange of responses. I hesitate to add to the pile yet feel compelled to put in my comments. 1) thanks for seeking help. 2) this appears to be homework. Our normal policy is to not write programs to solve the assignment. I'm surprised no one else has mentioned this. 3) I assume you are taking a class, yet the amount of struggle you evince indicates that either you did not learn whatever preceded this assignment, or the class is too far advanced for you. Please confirm or explain. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor