![]() |
|
Re: ** Python Support Thread **
I downloaded Python3 the other day, and although I was irritated at first, I find I like it quote a bit. Here's my list of changes, but since I've only converted about 300 lines of code, my list is far from complete.
Here's an interesting thread from stack exchange. Apparently, the transition is following the core developers' predictions. http://programmers.stackexchange.com...using-python-3 The first thing that is new, and quite interesting, in my opinion, is the change from ASCII to UTF-8. I guess this is a reaction to HTML5. I don't know about the workings, but apparently unicode conversion is no longer handled by Python, so instead of asking if you want to convert, the program implodes? So no dependable copy/paste? The next thing is the forced implementation of new and not-so-new functions. --print( ); So, yeah, this is the first shock you'll get when you try to run an old code on Python3. No longer print x and see an output. Not sure why they did this. The only thing I can think of is that they want to allow you to run functions and default arguments through print? Maybe it just looks pretty. --print 'Hello, {0}, welcome to {1}. My name is {0} also.'.format(arg1, arg2) I love this. I always felt that string functions were stupid and basically pointless in Python, so I seldom bothered to use them. This time, however, you can easily use multiple values, add default args, and reuse args multiple times in one sentence. Of course this also works in Python2, but I won't miss using %s. -- input() raw_input() is no longer valid. --list() There's a lot going on here, but 2 main points: 1- the shorthand ([statement]) no longer works. 2- This is more subtle, and a little hard to explain until you see your codes break, but Python3 forces you to use lists in many places you would normally use tuples. While I can ouput tuples, and even tuples in lists, I can't actually use tuples inside of functions any more. I'm not sure how I feel about this. I mean, if they want to add cdr'ing to Python, I'm fine with that, but don't straddle the fence on this stuff. They basically tossed out tuples since you (almost) can't use them in your code. An output is, by definition, immutable, so why would they bother keeping the syntax there? I guess a fruity example is: Code:
Code:
def myFun(a, b):This one is simply confounding to me, and one that will most certainly deter programmers of math-heavy code. Instead of >> 10/2 5 you get >>10/2 5.0 Something sort of common: Code:
use a = sorted(object) instead. -- dictionary comprehensions went through a massive overhaul, which I'm sure is controversial to some people. -- .iteritems no longer valid use .items instead. If you are observant: Code:
Since I'll likely get asked "why" my only answer is "for the hell of it." |
Re: ** Python Support Thread **
Short question : Can you put functions inside dictionaries, or are they limited to values like strings and integers?
|
Re: ** Python Support Thread **
Yup. The beauty of python is that you can usually just try something and see if it works:
>>> def foo(a): ... print a ... >>> d = {'a':foo} >>> d['a']() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: foo() takes exactly 1 argument (0 given) >>> d['a'](32) 32 |
Re: ** Python Support Thread **
It's python, you can do what ever you want.
|
Re: ** Python Support Thread **
Quote:
Managed to solve the problem after awhile. Nothing seems to be more frustrating than programming, but it is even more satisfying to eventually solve a problem! |
Re: ** Python Support Thread **
Quote:
Code:
|
Re: ** Python Support Thread **
Hey there,
I've just started to try to teach myself a little Python with *very* little previous programming experience (which mainly consisted of trying to program on a C64 about 30 yrs ago!), and to start myself off I decided to try to write a piece of code that could find the square root of a given number. I know there is a function that does this, but I thought it would be a good exercise. My problem is I don't have a huge number of Python commands under my belt yet, and I don't think I am thinking about program structure correctly given the last language I was kinda familiar with was a very basic BASIC, where I pretty much spent my entire life using the FOR and IF statements. I know this code is incredibly clumsy, and not in the least elegant, so if anybody could point me in the right direction toward making this leaner, less clumsy, and altogether more graceful, I'd really appreciate it! Code:
|
Re: ** Python Support Thread **
It looks to me like you will find a few numbers that will create infinite loops, though I'm not certain what values would cause this, so I could be wrong.
There's a ton of algorithms for square roots. Heron's method is the most common introductory one afaik: http://en.wikipedia.org/wiki/Methods...g_square_roots |
Re: ** Python Support Thread **
Thanks for the link. I realised before embarking on this that there were probably plenty of effective algorithms for square roots, but as I was trying to get my brain working in a logcal and "programmatical" fashion I deliberately elected to ignore them and to see if I could figure out a way to do it myself :)
I know what I've come up with is far from optimal - not just the algorithm, but also the code seems somewhat clumsy to me. I think my next goal is to try to make the code better while using the same algorithm. There just *has* to be a better way of doing what I did without using all those "while" statements! Regarding the infinite loops - I came across a lot of those the first time I tried to do this, but since I changed to this method I've had none so far. I added a variable to count the number of "refinements" that my code went through for any given variable, and I think the max it has needed so far is 40. However, you may well be right about the odd number causing an infinite loop, so I should probably set an upper limit on that count variable and force the code to stop once that limit has been hit! |
Re: ** Python Support Thread **
First step is to acknowledge that your code only works for numbers >= 1. If a = 0.25 things don't work out so well in the first step.
As for the refinement, you can nest two loops to collapse the whiles down. This will also allow you to add an extra 'knob' to determine just how refined you want any given attempt to be. I don't know python so I'll fake it based on your code. Consider this pseudocode: Code:
d = 0.1 |
Re: ** Python Support Thread **
Doh! That's a ton more elegant - thank you!
You're also totally correct in that I should add some checks to ensure that a >= 1. Thanks a ton for the help. |
Re: ** Python Support Thread **
Tidied the code up a fair bit based on your suggestion - thank you!
Code:
# Successive approximation for finding the square root of variable 'a'Quick syntax question: I've been using "count=count+1" to increment that variable, but I know there's a shorthand way of doing this. I thought it was "count++" or "count+=1" but I get errors every time I try those. Am I just fudging the syntax? Edit: duh, "count+=1" does work. I guess "count++" was where I was going wrong. Next goal: convert from a stand-alone app to a function that can be called from either the command line or another application. Never done that before so this should be a voyage of discovery. |
Re: ** Python Support Thread **
No point trying to reinvent the sqrt wheel when your starting out. Programming offers many more interesting possibilities IMO. I guess you could try to create an individual code for each sqrt algorithm. I would think you'd learn more valuable things that way. I am not a master programmer by any means, but I think learning how to implement multiple solutions to divide and conquer problems is more valuable than trying to think of a sqrt implementation. If you use Newton and Herod, you can compare convergence and accuracy with large numbers where 13 trials is a little small.
|
Re: ** Python Support Thread **
Quote:
In my opinion, when you are starting out programming, it doesn't matter what you're working on as long as you're working on something and enjoying it. The most important thing is that you are having fun no matter what problem you decide to tackle. Writing your own square root finding algorithm, no matter how inefficient, seems like a fine choice to me to get your feet wet. You don't have to solve the halting problem in your first week back at coding. |
Re: ** Python Support Thread **
Gazillion, if you're looking for new and interesting programming problems, try working through some of Project Euler. I just started on Project Euler tonight.
It's really cool to come up with an answer and then see how others have solved the same problem in the forum. |
Re: ** Python Support Thread **
Thank you for all the feedback and support!
Flux, that link looks great! However, it's nothing more than a tantalizing promise for me right now as the problem page seems to be down, so I'm refreshing every few minutes in the hope that it's just temporary! I've further refined my code - if it's against the spirit of the thread to keep posting updates please just tell me to stop and I'll quit with the updates, but I've defined my algorithm as a function and then written a simple user front end for the code. The one problem I'm trying to work out is something that appears when I enter testing mode by un-commenting lines 11, 26 and 34: with many solutions, as it reaches the end of the iteration/refinement cycle it appears to have already been in possession of the correct answer for a number of tries before it eventually stops. I tried to insert some checks in the for/while loops to break upon finding an exact match, but they didn't seem to work. If anybody is up to the task of figuring out why it may be behaving like this, I'm all ears/eyes! : Code:
def sqrt(arg): |
Re: ** Python Support Thread **
+1 for Project Euler, it's full of maths questions to be solved like this: you come up with a brute force approach, find it just takes too long, then try to figure out the clever refinement. The problems page is down for me too but you can look at the problems directly like this: http://projecteuler.net/problem=2 (obviously change the =2 to whatever number you like).
I think your current problem is a good way to get back into coding as well. Re why your code doesn't always work, perhaps it's because floating point arithmetic (i.e. calculations using numbers that are not integers) doesn't always work the way you expect. In particular, it's rarely a good idea to do a comparison like Code:
if result**2==arg: |
Re: ** Python Support Thread **
Thanks RoundTower! To be honest, your explanation for why the checks may not be working had occurred to me as the likely culprit. I noticed that floats always seem to get rounded to about 12 decimal places, but when I print the returned value it is often a number of decimal places longer. However, if I test with arg=9 for example and un-comment the testing code, I will see a list of all the iterations it performs, with 3.0 being returned for maybe the last 6 or 7 iterations, which is what has been confusing me. If it was 3.000000000002 or something like that, I could understand what was happening, but as it is settling on 1 decimal place for a number of iterations, I'm getting perplexed.
Code:
if result**2==arg:It's not imperative that I use these checks given the speed of modern processors and how many computational cycles I have available to me, but I thought it would be good practise to try to make the algorithm as efficient as possible in advance of such a time when I'm doing things that are more computationally demanding. I'll be scratching my head over that one for a while. In the mean time, the good news is Project Euler appears to be back up, so I'm going to start getting stuck into some of those problems :) |
Re: ** Python Support Thread **
Here's an example of what I mean:
Code:
Enter a number to find the square root of (enter 0 to escape): 9 |
Re: ** Python Support Thread **
Quote:
Quote:
Code:
print "{0:.30f}".format(result) |
Re: ** Python Support Thread **
Yes, comparing floating point numbers with == and != is always a bad idea. I once spent a week tracking down a bug due to a comparison like this.
If you're testing to floating point numbers for equality then you should do: Code:
epsilon = 1E-7 |
Re: ** Python Support Thread **
Quote:
Code:
num1 - num2 < epsilon |
Re: ** Python Support Thread **
Hey guys,
I've been getting my teeth into Project Euler (great site!) but I'm having some troubles with problem 3. Without trying to give away too many spoilers for those who may want to try this and haven't already, I am basically trying to do the following: 1) find all the factorials of the number, and add them to list 'fact[]' 2) I then want to take that list and, starting from fact[-1] and working backwards, check each of these values for primacy until I find the first value that returns true. (1) I have accomplished fairly quickly and easily, but I'm having troubles with (2). I was hoping I could maybe take all the values in the list and use those in a FOR loop (ideally in reverse order), in order to then check each of them, but it's not proving easy. Is there a way to use the contents of a list to act as a range for a loop, and have that loop only iterate for each value stored within a list? Is this the wrong way to go about it, and if so, is there a more preferable option to something like the FOR statement for iterating through this list? Sorry for the questions - I'm a list newb so still know very little about them. BTW, Neko, I though I had thanked you for your post the other day. I see for some reason it didn't show up in-thread, so thank you for that explanation. It'll take a while for that to become second nature for me but thanks a lot for showing me how it can be done. |
Re: ** Python Support Thread **
Usually the way you will iterate through a list of values is like this:
Code:
>>> values = [1,3,5,7,11,13,17,19]Code:
>>> for value in reversed(values): |
Re: ** Python Support Thread **
Awesome, thank you!! It was the reversed(value) bit that was throwing me the most. I think that's nailed it for me.
My algorithm must be super ineffecient because it's taking a looonnnnnnng time to find all the factors (I'll have to fine tune this), but thanks a lot - your code really helped: Spoiler:
|
| All times are GMT -4. The time now is 11:10 PM. |
|
Powered by vBulletin®
Copyright ©2000 - 2026, Jelsoft Enterprises Ltd.
Copyright © 2008-2020, Two Plus Two Interactive