Re: [Tutor] Tutor Digest, Vol 123, Issue 27
gt; > > from an interactive shell: > > > > > > import pycountry > > > country = pycountry.countries.get(alpha2='DE') > > > currency = pycountry.currencies.get(numeric=country.numeric) > > > Traceback (most recent call last): > > > File "", line 1, in > > > File "/usr/lib/pymodules/python2.6/pycountry/db.py", line 83, in get > > > return self.indices[field][value] > > > KeyError: '276' > > > > > > The obvious issue here is that the pycountry.countries collection does > > not > > > contain a currency with a numeric of 276 (Germany's numeric) - yet it > > does > > > contain the Euro. Any ideas as to what the way around this may be? > > > > It looks like the development version of babel > > > > > > > http://babel.pocoo.org/docs/api/numbers/#babel.numbers.get_territory_currencies > > > > can do what you want: > > > > $ LANG=en_US.UTF-8 python > > Python 2.7.5+ (default, Feb 27 2014, 19:37:08) > > [GCC 4.8.1] on linux2 > > Type "help", "copyright", "credits" or "license" for more information. > > >>> import babel.numbers as bn > > >>> bn.get_territory_currencies("DE") > > ['EUR'] > > >>> print bn.format_currency(1.234, "EUR") > > ?1.23 > > >>> print bn.format_currency(1.234, "EUR", locale="DE") > > 1,23 ? > > >>> import babel > > >>> babel.__version__ > > '2.0-dev' > > > > ___ > > Tutor maillist - Tutor@python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor > > > > > > -- > Regards, > Sithu Lloyd Dube > -- next part -- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20140508/4c054982/attachment.html > > > > -- > > Subject: Digest Footer > > ___ > Tutor maillist - Tutor@python.org > https://mail.python.org/mailman/listinfo/tutor > > > -- > > End of Tutor Digest, Vol 123, Issue 27 > ** > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] preferred httprequest library
Hello, : I¹m new to python but not so much to programming. I need to : construct a set or programs to test a forms poster that has been : enhanced (it is in php). I mostly need http get and post. This : is a hands on set of tests and does not have to be bullet proof. : : What would be a good http request library to use for this work? There are many options. When you can afford to suck the entire remote resource into memory (as with many applications), you will probably find the 'requests' library very handy. I'd start here, avoiding grabbing for the standard library tools (urllib, and urllib2) unless you need that finer control. This has a nice abstraction and, from your description, I think this would be a good fit: http://docs.python-requests.org/en/latest/ -Martin -- Martin A. Brown http://linux-ip.net/___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] preferred httprequest library
Sorry, I¹m sure this has been asked before: I¹m new to python but not so much to programming. I need to construct a set or programs to test a forms poster that has been enhanced (it is in php). I mostly need http get and post. This is a hands on set of tests and does not have to be bullet proof. What would be a good http request library to use for this work? Thanks in advance Eric Palmer ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] PyCountry currency formatting woes
Thank you all, babel works just fine. I also tried ccy, which isn't bad either - except that it returns non-unicode currency letters for countries in the Eurozone. On Mon, May 5, 2014 at 10:10 AM, Peter Otten <__pete...@web.de> wrote: > Sithembewena Lloyd Dube wrote: > > > Thanks, i was actually getting the error information to update the post. > > Apoligies to waste your time posting here - I could not find an > > appropriate PyCountry discussion list and my next best bet seemed to be a > > Python users' list. > > > > For those who care to look, the error is as follows (a concise example > > from an interactive shell: > > > > import pycountry > > country = pycountry.countries.get(alpha2='DE') > > currency = pycountry.currencies.get(numeric=country.numeric) > > Traceback (most recent call last): > > File "", line 1, in > > File "/usr/lib/pymodules/python2.6/pycountry/db.py", line 83, in get > > return self.indices[field][value] > > KeyError: '276' > > > > The obvious issue here is that the pycountry.countries collection does > not > > contain a currency with a numeric of 276 (Germany's numeric) - yet it > does > > contain the Euro. Any ideas as to what the way around this may be? > > It looks like the development version of babel > > > http://babel.pocoo.org/docs/api/numbers/#babel.numbers.get_territory_currencies > > can do what you want: > > $ LANG=en_US.UTF-8 python > Python 2.7.5+ (default, Feb 27 2014, 19:37:08) > [GCC 4.8.1] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import babel.numbers as bn > >>> bn.get_territory_currencies("DE") > ['EUR'] > >>> print bn.format_currency(1.234, "EUR") > €1.23 > >>> print bn.format_currency(1.234, "EUR", locale="DE") > 1,23 € > >>> import babel > >>> babel.__version__ > '2.0-dev' > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Regards, Sithu Lloyd Dube ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How inefficient is this code?
On 5/7/2014 8:39 PM, C Smith wrote: I see. Thanks that is exactly what I was looking for. Would your example be an instance of an object-oriented approach, compartmentalizing things into functions? One of the fun parts of Project Euler is using mathematical analysis and other tricks to improve your algorithm. You have a nice, general Fibonacci number generator, but you can use a less general function to increase efficiency [1]. In this case, it doesn't matter--your initial solution was fast enough--but you'll soon be solving problems where the most general solution fails to be fast enough. [1] Your code is calculating about twice as many Fibonacci numbers as it needs to. See if you can create a way to calculate Fib(n+2) from Fib(n). -- Neil Cerutti ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (no subject)
Hello Kevin, and welcome! My responses are below, interleaved between yours. On Thu, May 08, 2014 at 10:00:11AM +, Kevin Johnson wrote: > Hi, > > Total beginner to python and am working my way through Michael Dawsons > 'Absolute beginner' book. Just got stuck on the last bit of the challenges > from chapter 3. Essentially need to create a game where the user picks a > number between 1 and 100 and the computer has to guess, program should > indicate to the computer if the guess need to be higher or lower, it should > also count the number of attempts and call a halt to the game if a set > number of attempts is reached. > > The highlighted bit is where I think I'm going wrong Many programmers -- myself included -- operate exclusively with "plain text", no formatting. I won't go into all the reasons, but let's just assume we have a good reason for it. Unfortunately that means that many of us can't see your highlighting. If you want to maximize the number of tutors here who can answer your questions, you may like to find a way to comment your code other than coloured highlighting. A good way is to insert a comment, like # This is the section I'm having problems with. [code goes here] # This is the end of the section. Or similar. > but I just can't think > how to make the computer remember the previously closest highest and lowest > guesses, Any time you want the computer to remember something, the most obvious way is to give it a variable. I'm not quite sure what you mean by "previously closest highest and lowest guesses", but I'm going to take a stab at it. You want the computer to compare the current guess to your number, and if the guess is *closer* to the previous closest guess, remember it. E.g. suppose you pick the number 50, and the computer guesses 25. Since this is the first guess, it's automatically the closest. Then the computer guesses 60. Since 60-50 = 10 is smaller than 50-25 = 25, 60 is the closest. Then the computer guesses 30. Since 50-30 = 20 is greater than 10, 60 remains the closest. Am I on the right track? Assuming I am, how might I program this? The first thing is to have a variable that holds the closest value: closest = ... what? Here's a trick. Since we know that the guesses are always between 1 and 100, if we set the first "closest" to something greater than 100, the first guess will always count as closer! So: closest = Then, as you check each guess: if abs(computer_guess - user_number) < abs(closest - user_number): # this guess is closer than the previous closest closest = computer_guess With a little thought you should be able to extend this idea to keeping two variables, the closest_high number and the closest_low number. If the computer's guess is too low, you check and update closest_low; if the guess is too high, you check and update closest_high. Regards, -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (no subject)
On 08/05/14 11:00, Kevin Johnson wrote: user picks a number between 1 and 100 and the computer has to guess, Hmm, usually its the other way around, the computer picks a number and the user guesses it. Interesting twist! The highlighted bit is where I think I'm going wrong but I just can't think how to make the computer remember the previously closest highest and lowest guesses, I'm not sure why you think you need to do that? But simply you create a new variable called last_guess or somesuch and store computer_guess there before you change it. But the biggest problem is that the computer is using random values between 1 and the current guess(+/-1). That's a very inefficient way to get to the place you want. A more efficient technique is something called a binary chop: You know the users number is between 1 and 100 so you start in the middle at 50. If its too high then the users guess is between 1 and 49 so you pick the new middle - say 25 If its too high the target is between 1 and 24m, so you pick the middle -> 12 and so on. Similarly if the first guess is too low you know the user is between 51 and 100 so you pick the middle - 75 If its too high you pick midway between 75 and 100 and so on. That should pretty much always get the computer to the right answer within its 10 guesses. The only values you need to keep track of are the lower and upper bounds - starting at 1 & 100 respectively. user_number = int(input("Pick a number between 1 and 100: ")) computer_guess = random.randint(1, 100) guesses = 1 while computer_guess != user_number: ... if computer_guess > user_number: computer_guess = random.randrange(1, (computer_guess-1)) else: computer_guess = random.randint((computer_guess + 1), 100) guesses += 1 if computer_guess == user_number: print("Well done you guessed the number was", user_number) print("It took you", guesses, "tries") There is also a bug in the above code: in the case that the computer guesses the correct number the else clause causes the computer to generate a new guess. So the computer can never win on the first guess!! The else line should really be: elif computer_guess < user_number: Also why use randint() on one line but randrange() on the other? They are subtly different and only one is correct in this situation. I'll let you figure out which! :-) And if you use binary chop you won't need either! 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] Final review
On Wed, May 07, 2014 at 08:49:11PM -0700, Scott W Dunning wrote: [...] > > >>> greeting [len(greeting)] > > > > It is trying to access the character at the position "11", where the > > string "Hello world" doesn't contain any value in the index "11" and > > the maximum index is 10. So it throws the following error. > > I think this is where I am getting confused. I guess I don’t > understand why/how it’s trying to access the character at the index > 11? The value of greeting is "Hello world". So let's write it out, showing the index of each character. Remember that Python starts counting from zero, not one: Index 0: H Index 1: e Index 2: l Index 3: l Index 4: o Index 5: space Index 6: w Index 7: o Index 8: r Index 9: l Index 10: d So the indexes start from 0, and go up to 10. How many characters are there? Count them, and you get 11. Which makes sense: one character per index, there are at least ten indexes (1 through 10), plus one extra (index 0) makes 11. So the length of the string is 11, but the highest index is 10. So greeting[0] gives "H", greeting[1] gives "e", greeting[2] gives "l", and so on, until you get to greeting[10] which gives "d", and greeting[len(greeting)] => greeting[11] which is an error. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (no subject) - (added) Number guessing game
On 05/08/2014 06:00 AM, Kevin Johnson wrote: Hi, Total beginner to python and am working my way through Michael Dawsons 'Absolute beginner' book. Just got stuck on the last bit of the challenges from chapter 3. Essentially need to create a game where the user picks a number between 1 and 100 and the computer has to guess, program should indicate to the computer if the guess need to be higher or lower, it should also count the number of attempts and call a halt to the game if a set number of attempts is reached. The highlighted bit is where I think I'm going wrong but I just can't think how to make the computer remember the previously closest highest and lowest guesses, not sure if you have all read Micheal Dawsons book but I've not covered a whole lot by chapter 3 and so any hints/solutions need to be pretty basic as I don't want to get ahead of myself. Thanks, Kevin #numbers game again but... #user picks number between 1 and 100 #and computer guesses import random user_number = int(input("Pick a number between 1 and 100: ")) computer_guess = random.randint(1, 100) guesses = 1 while computer_guess != user_number: print("The computers guess is", computer_guess) if computer_guess > user_number: print("Lower...") else: print("Higher...") if guesses == 10: print("You lose computer!") break if computer_guess > user_number: computer_guess = random.randrange(1, (computer_guess-1)) else: computer_guess = random.randint((computer_guess + 1), 100) guesses += 1 if computer_guess == user_number: print("Well done you guessed the number was", user_number) print("It took you", guesses, "tries") input("Press the enter key to exit.") This is a classic game. The first issue I see is the while exit condition. I prefer to use: max_guess = 7 # I believe this game can be won in 7 guesses if the correct strategy is used. guess = 0 initial_guess = random.randrange(1, 100) while guess < max_guess: do stuff guess += 1 Also, I would model how you would play this game efficiently against a person. Then write the "do stuff" to replicate that. Hint: you do not need to generate random guesses within the while loop. -- Jay Lozier jsloz...@gmail.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How inefficient is this code?
> I see. Thanks that is exactly what I was looking for. Would your > example be an instance of an object-oriented approach, > compartmentalizing things into functions? That's an interesting question. It's an example of abstraction, which is one of the pillars of object oriented design. You're abstracting the principle of calculating the fibonacci numbers, into the function fib, and separating it from the concrete use cases for the numbers themselves. This is probably the pattern you're detecting here and associating with OOP: you take a self-contained piece of functionality and throw it somewhere where its logic can be used in an abstract manner. Now, there are more pillars to object oriented design: encapsulation, inheritance, and polymorphism, and this example demonstrates neither. For example, it doesn't really feature polymorphism: the fib function is very concrete, and has really only one "form", namely the one you're seeing. So, while these generator functions introduce a pretty neat possibility for abstraction, namely abstracting out the concept of iteration and separating from what happens during iteration, I'm not really sure you can call it OOP. Perhaps it depends on the way you look at it. A more complex generator (maybe implemented as an object) might, for example, be polymorphic in nature. These design questions can often blur, so I'm not sure how better to answer your question, maybe someone can chime in. On Wed, May 7, 2014 at 8:39 PM, C Smith wrote: > On Wed, May 7, 2014 at 7:55 PM, Joe Cortes wrote: >> Welcome to the wonderful world of generators! >> >> Looking at your code, you'll notice two things. First, you're >> iterating over all the numbers twice: once to calculate them, and then >> another time to actually do the sum. What's worse, at any given point >> in time, you're only really using fibs[-1] and fibs[-2], and yet >> you're still building this huge list with all the numbers. This is bad >> in terms of memory efficiency. Luckily, it's such a common problem >> that Python offers a really nice, really Pythonic solution. You can >> define the following function: >> >> def fib(top): >> first = 1 # As an aside, consider starting the sequence from 0, 1. >> next = 2 >> yield first >> while next < top: >> yield next >> # For kicks, try rewriting the following three lines as a >> tuple assignment. >> new_next = next + first >> first = next >> next = new_next >> >> Now, how do you use this? This being Python, there is a super simple >> way to do this: >> >> sum = 0 >> for num in fib(400): >> if num % 2 == 0: >> sum += num >> print sum >> >> >> So, what's going on here? fib is mostly straightforward, but that >> yield keyword might look new. >> Here's the deal: when you have a function that uses the yield keyword, >> that function becomes usable in the context of a for loop. Every time >> it hits a yield it will, well, yield that value out to the for loop. >> At the end of an iteration, control will be handed back to the >> function, which will do its magic, and yield another value. Again, the >> value will be sent out to the for loop, in this case as the "num" >> variable, for use in that iteration. >> When the function hits a return (or reaches the end of its body), the >> for loop ends. >> >> This is called a generator function, and is a really nice way to >> simplify and optimize your loops. >> >> You can read more about generators here: >> https://wiki.python.org/moin/Generators >> >> >> On Wed, May 7, 2014 at 7:27 PM, C Smith wrote: >>> A topic came up on slashdot concerning "intermediate" programming, >>> where the poster expressed the feeling that the easy stuff is too easy >>> and the hard stuff is too hard. >>> >>> Someone did point out that 'intermediate' programming would still >>> involve actually selling code or at least some professional >>> experience, so this would probably fall into the category of 'novice'. >>> >>> I feel similarly right now and the cs 101 classes from udacity or >>> coursera or the opencourseware stuff are very easy and boring. I tried >>> the class "design of computer programs" on udacity and made it about >>> halfway before being overwhelmed. The class involved making an api for >>> a regex-like function to parse text (if I am communicating that >>> correctly, it was sort of rewriting regex functionality in Python >>> terms), and it seemed to go over a very definite cliff in terms of >>> difficulty. Could someone provide a concise example of decorator use? >>> >>> Someone suggested projecteuler.net and I started blazing through >>> things I had done before, when I realized this would be a good time to >>> start more efficient practices instead of code that just happens to >>> work and may be very inefficient. >>> >>> #sum all even fib seq integers under 4 million >>> fibs = [1,2] >>> sum = 0 >>> while fibs[-1] < 400: >>> nexty = fibs[-1] + fibs[-2] >>>
Re: [Tutor] How inefficient is this code?
Welcome to the wonderful world of generators! Looking at your code, you'll notice two things. First, you're iterating over all the numbers twice: once to calculate them, and then another time to actually do the sum. What's worse, at any given point in time, you're only really using fibs[-1] and fibs[-2], and yet you're still building this huge list with all the numbers. This is bad in terms of memory efficiency. Luckily, it's such a common problem that Python offers a really nice, really Pythonic solution. You can define the following function: def fib(top): first = 1 # As an aside, consider starting the sequence from 0, 1. next = 2 yield first while next < top: yield next # For kicks, try rewriting the following three lines as a tuple assignment. new_next = next + first first = next next = new_next Now, how do you use this? This being Python, there is a super simple way to do this: sum = 0 for num in fib(400): if num % 2 == 0: sum += num print sum So, what's going on here? fib is mostly straightforward, but that yield keyword might look new. Here's the deal: when you have a function that uses the yield keyword, that function becomes usable in the context of a for loop. Every time it hits a yield it will, well, yield that value out to the for loop. At the end of an iteration, control will be handed back to the function, which will do its magic, and yield another value. Again, the value will be sent out to the for loop, in this case as the "num" variable, for use in that iteration. When the function hits a return (or reaches the end of its body), the for loop ends. This is called a generator function, and is a really nice way to simplify and optimize your loops. You can read more about generators here: https://wiki.python.org/moin/Generators On Wed, May 7, 2014 at 7:27 PM, C Smith wrote: > A topic came up on slashdot concerning "intermediate" programming, > where the poster expressed the feeling that the easy stuff is too easy > and the hard stuff is too hard. > > Someone did point out that 'intermediate' programming would still > involve actually selling code or at least some professional > experience, so this would probably fall into the category of 'novice'. > > I feel similarly right now and the cs 101 classes from udacity or > coursera or the opencourseware stuff are very easy and boring. I tried > the class "design of computer programs" on udacity and made it about > halfway before being overwhelmed. The class involved making an api for > a regex-like function to parse text (if I am communicating that > correctly, it was sort of rewriting regex functionality in Python > terms), and it seemed to go over a very definite cliff in terms of > difficulty. Could someone provide a concise example of decorator use? > > Someone suggested projecteuler.net and I started blazing through > things I had done before, when I realized this would be a good time to > start more efficient practices instead of code that just happens to > work and may be very inefficient. > > #sum all even fib seq integers under 4 million > fibs = [1,2] > sum = 0 > while fibs[-1] < 400: > nexty = fibs[-1] + fibs[-2] > fibs.append(nexty) > > for xer in fibs: > if xer%2 == 0: > sum += xer > print sum > > This gets the correct solution, but what would be ways to improve > speed or use more complicated parts of Python to do the same thing. > Thanks in advance > ___ > 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] (no subject)
Hi, Total beginner to python and am working my way through Michael Dawsons 'Absolute beginner' book. Just got stuck on the last bit of the challenges from chapter 3. Essentially need to create a game where the user picks a number between 1 and 100 and the computer has to guess, program should indicate to the computer if the guess need to be higher or lower, it should also count the number of attempts and call a halt to the game if a set number of attempts is reached. The highlighted bit is where I think I'm going wrong but I just can't think how to make the computer remember the previously closest highest and lowest guesses, not sure if you have all read Micheal Dawsons book but I've not covered a whole lot by chapter 3 and so any hints/solutions need to be pretty basic as I don't want to get ahead of myself. Thanks, Kevin #numbers game again but... #user picks number between 1 and 100 #and computer guesses import random user_number = int(input("Pick a number between 1 and 100: ")) computer_guess = random.randint(1, 100) guesses = 1 while computer_guess != user_number: print("The computers guess is", computer_guess) if computer_guess > user_number: print("Lower...") else: print("Higher...") if guesses == 10: print("You lose computer!") break if computer_guess > user_number: computer_guess = random.randrange(1, (computer_guess-1)) else: computer_guess = random.randint((computer_guess + 1), 100) guesses += 1 if computer_guess == user_number: print("Well done you guessed the number was", user_number) print("It took you", guesses, "tries") input("Press the enter key to exit.") ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor