How do I count the distance between strings in a list?
For example, if I were to have the code randomlist = ["1", "2", "3", "4"] And I want to count the distance between strings "1" and "4" which is 3, what command can I use to do this? -- http://mail.python.org/mailman/listinfo/python-list
Accepting text input
I'm pretty new to Python, but this has really bugged me. I can't find a way around it. The problem is that, when I use raw_input("sajfasjdf") whatever, or input("dsjfadsjfa"), you can only have numerical values as answers. Any help would be appreciated. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Accepting text input
Collin wrote: I'm pretty new to Python, but this has really bugged me. I can't find a way around it. The problem is that, when I use raw_input("sajfasjdf") whatever, or input("dsjfadsjfa"), you can only have numerical values as answers. Any help would be appreciated. Thanks. Oh, wow. I feel so stupid. Please disregard this message. <_< I read the error message just now a bit more carefully, and I tried something. I tried defining "yes" as some random numerical value. Then when I did: (example code) yes = 123123983 #some number test = input("Test test test ") if test == yes: print "It worked." else: print "failed" (example code off) Collin -- http://mail.python.org/mailman/listinfo/python-list
Re: Accepting text input
Gabriel Genellina wrote: En Mon, 12 May 2008 01:54:28 -0300, Collin <[EMAIL PROTECTED]> escribió: Collin wrote: I'm pretty new to Python, but this has really bugged me. I can't find a way around it. The problem is that, when I use raw_input("sajfasjdf") whatever, or input("dsjfadsjfa"), you can only have numerical values as answers. Any help would be appreciated. Thanks. Oh, wow. I feel so stupid. Please disregard this message. <_< No need to apologize... I read the error message just now a bit more carefully, and I tried something. I tried defining "yes" as some random numerical value. Then when I did: (example code) yes = 123123983 #some number test = input("Test test test ") if test == yes: print "It worked." else: print "failed" (example code off) The usual way for Python<3.0 is: answer = raw_input("Test test test ").lower() if answer == "yes": ... The input() function evaluates user input as an expression: if he types 2+5 the input() function returns the integer 7. I would never use input() in a program - it's way too unsafe; use always raw_input instead. If I use it like that, do I have to import anything to have the .lower() work? And if I do, what does the .lower() signify? -- http://mail.python.org/mailman/listinfo/python-list
Re: Accepting text input
Kam-Hung Soh wrote: On Wed, 14 May 2008 11:02:36 +1000, Collin <[EMAIL PROTECTED]> wrote: Gabriel Genellina wrote: En Mon, 12 May 2008 01:54:28 -0300, Collin <[EMAIL PROTECTED]> escribió: Collin wrote: I'm pretty new to Python, but this has really bugged me. I can't find a way around it. The problem is that, when I use raw_input("sajfasjdf") whatever, or input("dsjfadsjfa"), you can only have numerical values as answers. Any help would be appreciated. Thanks. Oh, wow. I feel so stupid. Please disregard this message. <_< No need to apologize... I read the error message just now a bit more carefully, and I tried something. I tried defining "yes" as some random numerical value. Then when I did: (example code) yes = 123123983 #some number test = input("Test test test ") if test == yes: print "It worked." else: print "failed" (example code off) The usual way for Python<3.0 is: answer = raw_input("Test test test ").lower() if answer == "yes": ... The input() function evaluates user input as an expression: if he types 2+5 the input() function returns the integer 7. I would never use input() in a program - it's way too unsafe; use always raw_input instead. If I use it like that, do I have to import anything to have the .lower() work? And if I do, what does the .lower() signify? -- http://mail.python.org/mailman/listinfo/python-list You don't need to import any module to use ".lower()"; it is a method of a string. raw_input() returns a string, so you can use methods of a string. Try the following statement to see what happens: "ABCDE".lower() So the .lower() string method is just to convert the string to lowercase letters so that you don't have to type a bunch of if - then statements in both cases, I'm assuming? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and Flaming Thunder
Dave Parker wrote: I've read that one of the design goals of Python was to create an easy- to-use English-like language. That's also one of the design goals of Flaming Thunder at http://www.flamingthunder.com/ , which has proven easy enough for even elementary school students, even though it is designed for scientists, mathematicians and engineers. Personally, FT is a bit meh to me. The way you issue your statements I always think something is wrong, mainly because when I want to define, say, x, in python I'd go: x = "whatever" Instantly noting that I defined x. While in Flaming Thunder I'd have to type: Set x to "whatever" It just feels wrong. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and Flaming Thunder
Dave Parker wrote: On May 20, 7:05 pm, Collin <[EMAIL PROTECTED]> wrote: Personally, FT is a bit meh to me. The way you issue your statements I always think something is wrong, mainly because when I want to define, say, x, in python I'd go: x = "whatever" Instantly noting that I defined x. While in Flaming Thunder I'd have to type: Set x to "whatever" It just feels wrong. Actually, it felt wrong to me when I first started working on Flaming Thunder because I've been programming for decades and have had all of the programming idioms burned into my brain. But after getting input from children and teachers, etc, it started feeling right. For example, consider the two statements: x = 8 x = 10 The reaction from most math teachers (and kids) was "one of those is wrong because x can't equal 2 different things at the same time". Many computer languages conflate "equality" with "assignment" and then go to even more confusing measures to disambiguate them (such as using == for equality, or := for assignment). Plus, symbols are more confusing for people to learn about than words. There are lots of people who are fluent in English, but dislike math. So, I opted for a simple, unambiguous, non-mathematical way of expressing "assignment" which makes sense even to the non- mathematically inclined: Set x to 8. That way, = can be reserved unambiguously and unconfusingly for the mathematical notion of "equality" -- because it's in their math classes that people learn what = means: Set QuadraticEquation to a*x^2 + b*x + c = 0. Then I guess the elementary school kids will use your FT system while we will use our naturally burned-in sense of syntax from other programming languages, eh? Not saying this as a negative or anything, I'm just saying that most of us have a habit, and it's not necessarily a bad nor good habit, of doing things the way most languages have them done. For example, x = 8 is extremely readable, to, I assume, most of us. Set x to 8, it takes some time getting used to. Why should we switch to a language that will take us time to get used and some more time to understand syntax when we already understand and can efficiently use our current languages? It's like going to the middle of London and screaming: "HEY GUYS GUESS WHAT! I JUST INVENTED A NEW LANGUAGE AND IT'S VERY VERY EASY TO LEARN!" And the people who would try the language would find the way you do everything is very different from English, or their native language, for that matter. Best let sleeping dogs lie. Collin -- http://mail.python.org/mailman/listinfo/python-list
Re: مقطع فيديو [الو لاده القيصريه] يمنع دخول ضعاف القلوب
a7labnt wrote: برنامج VMware Workstation 6.0 http://www.antya7la.com/vb/t26858.html#post286993 برنامج يعالج فيروسات auto run و folder option http://www.antya7la.com/vb/t26859.html#post286996 ضع صورتك داخل هذة الساعة http://www.antya7la.com/vb/t26860.html#post286997 زيد سرعة ال Ftp ؟ 64 % + الطريقة مضمونة و ناجحة و حصرية http://www.antya7la.com/vb/t26861.html#post286999 اجعل من بداية تشغيل جهازك.. كالصاروخ http://www.antya7la.com/vb/t26862.html#post287000 حصريا : افتح جهازك بنظرة أو ابتسامة - جرب بنفسك لتشاهد وتتأكد ! http://www.antya7la.com/vb/t26863.html#post287010 زوجين في حافلة نيويورك http://www.antya7la.com/vb/t27127.html#post289835 الحكومة تضع قفل على بناطيل النساء000بالصووور http://www.antya7la.com/vb/t27128.html#post289837 تحذير - مياة اكوافينا http://www.antya7la.com/vb/t27129.html#post289839 كل شيء في الكويت جائز ومسموح لكن بعيدا عن اعين الصحافة http://www.antya7la.com/vb/t27130.html#post289841 لمن قلوبهم متعلقة بالبحرين الله يهديهم http://www.antya7la.com/vb/t27131.html#post289843 شوفوا الخبل وش مهرب http://www.antya7la.com/vb/t27132.html#post289845 لايفوووتكم زواج تسعينيه من فتى مراهق بالصور !! http://www.antya7la.com/vb/t27133.html#post289846 فضيحه جديده لهيفاء وهبي http://www.antya7la.com/vb/t27135.html#post289851 قناة اباحيه (اسرائيلية) ستدخل بيتك بدون ارادتك http://www.antya7la.com/vb/t27138.html#post289855 تفاصيل الجريمة البشعة التي حدثت في عمان التي راح ضحيتها 5 اطفال وسيدة http://www.antya7la.com/vb/t27134.html#post289850 فتاة جامعت 300 شخص خلال 24 ساعة!!! http://www.antya7la.com/vb/t27139.html#post289859 انتي وزجك في الحمام حركــات تـــدوخ الصنـــم http://www.antya7la.com/vb/t26884.html#post289876 اعلم ان زوجتك تمارس الجنس وحدها http://www.antya7la.com/vb/t26783.html#post289879 تعلمي كيف تنزعين ملابسك امام زوجك http://www.antya7la.com/vb/t26935.html#post289880 حلي مشاكلك مع زوجك بهذا الدعاء http://www.antya7la.com/vb/t26932.html#post289884 الضحك على البنات!!طريقة ضياع البنات بأغبى الكلام من الشباب http://www.antya7la.com/vb/t26617.html#post289885 نصيحة للبنات قبل الزواج... http://www.antya7la.com/vb/t26815.html#post289889 لشفايف توت و وردة بشيئين فقط !!! آخ رهييبة http://www.antya7la.com/vb/t26914.html#post289893 مقطع فيديو [الولاده القيصريه] يمنع دخول ضعاف القلوب http://www.antya7la.com/vb/t26992.html#post289907 {{{ اذا ضحك لك الزمان فكن حذر..!!}}} http://www.antya7la.com/vb/t26793.html#post289913 كيف تأثرين قلب زوجك http://www.antya7la.com/vb/t27081.html#post289912 جل لتنحيف وشد البشرة..#! http://www.antya7la.com/vb/t2223.html#post289911 تتحداني اعرف لون سروالك؟! http://www.antya7la.com/vb/t4378.html#post289915 ثيميز Windows Xp بربطة واحدة فقط! http://www.antya7la.com/vb/t21396.html#post242891 النسخة الجديدة للمتصفح Internet Explorer 8 Beta 1 http://www.antya7la.com/vb/t21395.html#post242889 رنامج Ares لتحميل اى شىء http://www.antya7la.com/vb/t21394.html#post242887 الآن الإصدار التانى من برنامج KinG Fm لسماع نجوم اف ام والعديد من الإذاعات دون مواقع, http://www.antya7la.com/vb/t21397.html#post242896 النسخة الجديدة للمتصفح Internet Explorer 8 Beta 1 http://www.antya7la.com/vb/t21395.html#post242889 جهازك بطىء!خش ونظف الرمات وسرعها!وخليك On Spd, برنامج لتنظيف الرمات وتسريعها!حصري http://www.antya7la.com/vb/t21398.html#post242898 The Logo Creator لتصميم الشعارات http://www.antya7la.com/vb/t21399.html#post242900 برنامج Driver Wizard يعطيك تعاريف جهازك بالكامل http://www.antya7la.com/vb/t21400.html#post242913 حديقه طبيعية و حقيقيه صوت وصوره على سطح مكتبك تختلف اضاءتها حسب التوقيت رائع http://www.antya7la.com/vb/t21401.html#post242914 احفظ هذه الصفحة في جهازك ستحتاج اليها يوما ما! ارجو التثبيت http://www.antya7la.com/vb/t21402.html#post242919 لن تندم بعدم معرفة أسرار الـWinXP التي القليل يعرفها http://www.antya7la.com/vb/t21403.html#post242920 لتسريع الجهاز بدون برامج وتحدي! مجربة 100% http://www.antya7la.com/vb/t21404.html#post242921 Is this arabic spam? -- http://mail.python.org/mailman/listinfo/python-list
Re: مقطع فيديو [الولاده ا لقيصريه] يمنع دخول ضعاف ال قلوب
George Sakkis wrote: On Jun 12, 12:29 am, Collin <[EMAIL PROTECTED]> wrote: a7labnt wrote: Is this arabic spam? Why, are you curious how V1agr@ or [EMAIL PROTECTED] are spelled in arabic ? No, it's just I've never seen something like it. Quite funny, tbh. -- http://mail.python.org/mailman/listinfo/python-list
PIL for py3k not picking up external libraries
Hi all, I am using python 3.2 on an amd64 Gentoo system. I was trying to compile an unofficial version of PIL to work in 3.2 that I found here: http://www.lfd.uci.edu/~gohlke/pythonlibs Anyway, when I run the setup.py to compile the source, it doesn't pick up tkinter, zlib, or freetype. When I use pdb to step through the code where it is looking for libraries (for example zlib here), I make it all the way into unixcompiler.py: > /usr/lib64/python3.2/distutils/unixccompiler.py(318)find_library_file() -> shared_f = self.library_filename(lib, lib_type='shared') which returns 'libz.cpython-32.so' or 'libtcl8.5.cpython-32.py', depending on what it is looking for. If I step in further to ccompiler.py "") 881 fmt = getattr(self, lib_type + "_lib_format") 882 ext = getattr(self, lib_type + "_lib_extension") 883 884 ->dir, base = os.path.split(libname) 885 filename = fmt % (base, ext) The extension returns .cpython-32.so I have a lot of these extensions for site packages, but how do I generate libraries compatible with this for say tkinter, zlib, etc. For example, I see libtcl8.5.so, but no libtcl8.5.cpython-32.so. Can someone tell me what I am missing? Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Question about python 3.2 distutils
Hi all, I have a question about python 3.2 distutils on a Gentoo amd64 system. When I open an ipython session and import distutils.unixcompiler and then check the shared library extension with UnixCCompiler.shared)lib_extension, it returns '.so', as I would expect. When I run a setup.py in an unofficial PIL source that should work with python 3.2 and step into it, I hit the line: find_library_file(self, "tcl" + version): feature.tcl = "tcl"+TCL_VERSION self is: <__main__.pil_build_ext object at 0xf44510> find_library_file is: def find_library_file(self, library): return self.compiler.find_library_file(self.compiler.library_dirs, library) self.compiler is 0xfc5410> library is: 'tcl8.5' when I check the shared_lib_extension it returns '.cpython-32.so' - not '.so' This is causing a problem because, for example, I have libtcl8.5.so, but it is looking for libtcl8.5.cpython-32.so. Where is this shared lib extension being determined? After all, in an interactive session, it is just looking for .so, but in the script, it is looking for .cpython-32.so. I tried grep -R cpython-32 * in the top level directory of ther PIL source I am using, thinking it may be ovridden or set somewhere, but it turns up empty. Can anyone tell me what the difference is? I posted earlier, but I just noticed this difference between interactive session and script. Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Single type for __builtins__ in Py3.0
Hallo all, As it currently stands, the type of the global __builtins__ differs depending on whether you're in the __main__ namespace (__builtins__ is a module) or not (its a dict). I was recently tripped up by this discrepancy, and googling the issue brings up half-a-dozen or so c.l.p threads where others have been bitten by this, too. I'd like to propose that in Py3.0 (if not earlier), __builtins__ will be the same type regardless of which namespace you're in. Tim Peters has said [1] that the reason __builtins__ in __main__ is a module so that "the curious don't get flooded with output when doing vars() at the prompt". Based on this, I propose that __builtins__ be a module (really, an alias for the __builtin__ module as it is now) in all namespaces. If possible, I'd like to see this go in before 3.0. The reference manual currently states [2] that __builtins__ can be either a dict or a module, so changing it to always be a module would still be in keeping with this. However, I realise that there's probably code out there that hasn't been written to deal with both types, so this would result in some minor breakage (though it would be easily fixable). If this gets a good response, I'll kick it up to python-dev. Thanks, Collin Winter [1] http://mail.python.org/pipermail/python-list/2002-May/103613.html [2] http://www.python.org/doc/2.4.1/ref/naming.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Single type for __builtins__ in Py3.0
On 9/23/05, Fredrik Lundh <[EMAIL PROTECTED]> wrote: > Collin Winter wrote: > > > As it currently stands, the type of the global __builtins__ differs > > depending on whether you're in the __main__ namespace (__builtins__ is > > a module) or not (its a dict). I was recently tripped up by this > > discrepancy, and googling the issue brings up half-a-dozen or so c.l.p > > threads where others have been bitten by this, too. > > __builtins__ is a CPython implementation detail. why not just let it > be an implementation detail, and refrain from using it? it's not that > hard, really. Given, but I fail to see why it can't be a consistent implementation detail. After my own encounter with __builtins__, I now know that I should use __builtin__ instead. However, the docs never mention this. The only way you'd know that __builtin__ is preferred is by searching the list archives, something you're not likely to do unless you're already having a problem. If it's decided to leave things they way they are, at the very least the docs should be amended to indicate that users shouldn't be touching __builtins__. If anyone has a suggestion as to where this kind of thing might best fit (tutorial, library reference, language reference?), I'd be happy to write a patch for the docs. Collin Winter -- http://mail.python.org/mailman/listinfo/python-list
Re: Single type for __builtins__ in Py3.0
On 9/23/05, Christopher Subich <[EMAIL PROTECTED]> wrote: > How would this change, if made in a minimal way, impact the "provide > alternate globals() and locals() to eval and exec" feature? Altering > __builtins__ is a half-assed way of providing some sort of security, but > it's probably useful in preventing user-supplied code from shooting > itself in the foot without aiming first. In all cases (eval, exec, execfile), the globals parameter must be a dict and the locals can be any mapping object, so the value of the __builtins__ key would just need to be a module (could be created with the "new" module). This is about the same breakage as with any other code using __builtins__. One possibility would be to deprecate the dict-form. This could be done as Tom Anderson suggests, by supporting both __getattr__ and __getitem__, with the latter issuing a deprecation warning for a while. My tests indicate that this is possible, with both module.attr and module['item'] forms available. Collin Winter -- http://mail.python.org/mailman/listinfo/python-list
Re: Single type for __builtins__ in Py3.0
On 9/23/05, Peter Hansen <[EMAIL PROTECTED]> wrote: > User are clearly told in various places that names with leading and > trailing double underscores are *special*, and at least by implication > they are not to be used without a good understanding of what they are. > You certainly shouldn't have found any docs telling you to use > __builtins__ that way. > > http://www.google.ca/search?q=site%3Apython.org+__builtin__ is a pretty > quick way of finding the above docs, and while doing the same search > with __builtins__ admittedly finds lots of mailing list archives where > people have the same misconception as you did, it doesn't take one past > the second page of results before you'll be right back at a post by > Fredrik pointing out the same mistake. :-) The difference between __builtins__ and the other __*__ names is that while the others shouldn't be used without understanding their purpose, the consensus on __builtins__ seems to be that it shouldn't be used at all. Since you mention Fredrik's posts on the subject, I'll quote one for you: http://mail.python.org/pipermail/python-list/2002-June/109090.html """ forget about __builtins__; it's an implementation detail. if you need to explicitly refer to stuff in the built-in namespace, *always* import the __builtin__ module. never use __builtins__ in your code. """ Other posts echo this. To my mind this indicates that, at the very least, users should be explicitly told -- up front, in the official documentation -- that they shouldn't ever touch __builtins__. Maybe __builtins__ could be removed entirely from Py3.0, thus bringing reality in to sync with policy. Collin Winter -- http://mail.python.org/mailman/listinfo/python-list
Re: Single type for __builtins__ in Py3.0
On 9/23/05, Peter Hansen <[EMAIL PROTECTED]> wrote: > My point, which might not have been clear, is that users are *already* > told that they shouldn't ever touch __anything__ without understanding > what it is, which is more general advice than and therefore encompasses > the __builtins__ issue. For this reason I believe the existing advice > is sufficient for everyone except those who would probably also end up > ignoring your above suggestions anyway. I'm not proposing a new rule on the level of "learn about __foo__ before you mess with it"; the delegation structure of that rule is sufficient. I do however want the docs for __builtins__ to explicitly mention a) that you should do your mucking with __builtin__ instead, and b) that __builtins__ is a module when in __main__ and a dict everywhere else; the current documentation makes no mention of either. Come morning I'll submit a patch for the reference manual. > > Maybe > > __builtins__ could be removed entirely from Py3.0, thus bringing > > reality in to sync with policy. > > That's a possibility, though given that it's an implementation detail > there could easily be other implementation details which you would then > be asking to be removed as well because they might confuse someone. If > you really want to avoid having implementation details exposed like > this, you should probably be participating closely in the development > process. ;-) I'm relatively new to the python-dev world, but I intend to do what I can to eliminate blemishes like __builtins__. Collin Winter -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamically adding and removing methods
One caveat, as I recently discovered, to dynamically adding methods is that it doesn't work for __foo__ methods. For example, you can't make an object into an iterator by dynamically assigning bound methods to obj.__iter__ and obj.next. Same thing with __getitem__, __setitem__, etc; adding them directly to the instance doesn't get you a subscriptable object. This is because the interpreter looks at the methods defined by the class, rather than the instance's attributes. Just a word of caution. Collin Winter -- http://mail.python.org/mailman/listinfo/python-list
[ANNOUNCE] functional 0.7.0 released
Hello all, I have released version 0.7.0 of my functional module, a collection of higher-order and functional programming tools for Python. Currently offered are tools for function composition, partial function application, plus filter, flip, foldl, foldr, map, scanl and scanr functions. Two version of the release are available: one is written in pure Python and aims for maximum readability and portability. The other is coded as a C extension module and is focused on raw performance. Where to get it: # functional is available from the Python Package Index at http://cheeseshop.python.org/pypi/functional/ Both source tarballs and Python Eggs are available for both the pure Python and C releases. Eggs are available for Python versions 2.3, 2.4 and 2.5. Release Notes + functional now includes map() and filter() functions. These are roughly equivalent to the Python built-in functions, though without some of the weird/incorrect behaviour of the built-ins. Specifically: functional.map() works like the built-in, except functional.map() 1) always takes a single iterable, and 2) doesn't support the None nonsense that the built-in does. functional.filter() works like the built-in, except functional.filter() 1) iterates over subclasses of str, unicode and tuple correctly, 2) doesn't support the None nonsense that the built-in does, 3) always returns a list, unlike the built-in. + Several reference counting-related bugs have been squashed in the C implementation. + The test suite has been enhanced to do reference count checking after each test, making it much easier to track down future errors in the C implementation. + The C implementation now supports Python 2.3, in addition to 2.4 and 2.5 As always, feedback welcome! Collin Winter -- http://mail.python.org/mailman/listinfo/python-list
Questions on unittest behaviour
While working on a test suite for unittest these past few weeks, I've run across some behaviours that, while not obviously wrong, don't strike me as quite right, either. Submitted for your consideration: 1) TestCase.tearDown() is only run if TestCase.setUp() succeeded. It seems to me that tearDown() should always be run, regardless of any failures in setUp() or the test method itself. The case I'm considering is something like this, ie, a multi-part setUp(): > def setUp(self) > lock_file(testfile) # open_socket(), connect_to_database(), etc > > something_that_raises_an_exception() > > def tearDown(self): > if file_is_locked(testfile): > unlock_file(testfile) In this pseudo-code example, the file won't be unlocked if some later operation in setUp() raises an exception. I propose that TestCase.run() be changed to always run tearDown(), even if setUp() raise an exception. I'm undecided if this is a new feature (so it should go in for 2.6) or a bug fix; I'm leaning toward the latter. 2) The TestLoader.testMethodPrefix attribute currently allows anything to be assigned to it, including invalid objects and the empty string. While the former will cause errors to be raised when one of TestLoader's loadTestsFrom*() methods is called, the empty string will raise no exception; rather, the loadTestsFrom*() methods will interpret every possible attribute as being a test method, e.g., meaning you get things like assertEqual(), failUnlessEqual(), etc, when TestLoader.loadTestsFromTestCase() is run. I propose protecting testMethodPrefix with a property that validates the assigned value, restricting input to non-empty instances of str. I see this as a bug fix that should go in before 2.5-final. 3) TestLoader.loadTestsFromTestCase() accepts objects that are not test cases and will happily look for appropriately-named methods on any object you give it. This flexibility should be documented, or proper input validation should be done (a bug fix for 2.5). 4) TestLoader.loadTestsFromName() (and by extension, loadTestsFromNames(), too) raises an AttributeError if the name is the empty string because -- as it correctly asserts -- the object does not contain an attribute named ''. I recommend that this be tested for and ValueError be raised (bug fix for 2.5). This of course leads into the question of how much input validation should be done on these names. Should loadTestsFrom{Name,Names}() make sure the names are valid attribute names, or is this overkill? 5) When TestLoader.loadTestsFrom{Name,Names}() are given a name that resolves to a classmethod on a TestCase subclass, the method is not invoked. From the docs: > The specifier name is a ``dotted name'' that may resolve either to a module, > a test > case class, a TestSuite instance, a test method within a test case class, or a > callable object which returns a TestCase or TestSuite instance. It is not documented which of these tests takes priority: is the classmethod "a test method within a test case class" or is it a callable? The same issue applies to staticmethods as well. Once I get answers to these questions, I can finish off the last few bits of the test suite and have it ready for 2.5-final. Thanks, Collin Winter -- http://mail.python.org/mailman/listinfo/python-list
I will be proposing this PEP
Attached is a PEP which I will be proposing soon. If you have any questions, comments, or suggestions, please email them to me with the subject "Adding Built-in Class Attributes PEP" PEP: XXX Title: Adding Built-in Class Attributes Version: $Revision$ Last-Modified: $Date$ Author: Collin Stocks Status: Draft Type: Standards Track Content-Type: text/plain Created: 03-Jan-2007 Python-Version: 2.6 Post-History: Abstract Python currently allows users to create their own __setattr__, __getattr__ and __delattr__ member functions inside a class. This is all well and dandy, but it causes programmers to have to find a different way to set, get, and delete attributes within those functions. In __delattr__ and __getattr__, this usually is not a problem, because you can just get or delete those from __dict__, the built-in dictionary in a class. __setattr__ is more of a problem, because, if self.my_attr does not exist, self.__dict__['my_attr']="some value" raises an exception. This PEP proposes to add __setattr__, __getattr__ and __delattr__ as built-in member functions of all Python class objects. Rationale Many programs that use classes need to create their own __setattr__, __getattr__ and __delattr__ member functions. If not done carefully, this can cause recursion errors (something that increases the learning curve for newbies). This is also not very object oriented. Really, does it make sense to use objects of two different types to refer to the same object? This PEP does not propose to remove __dict__, just to add a more sensical way to access the attributes of a class. This will prevent recursion, make Python code make more sense and introduce a more object oriented and correct way of handling class attributes. Specification: Any class created by a Python file will have the __setattr__, __getattr__ and __delattr__ member functions built into it upon initiation. This would allow programmers to create copies of these functions, and then create their own, which call on the copies in order to change attributes. For example, suppose you wanted to make the attribute readOnlyAttr read-only: In the current version of Python, you must do something like this: class blah: def __init__(self): self.readOnlyAttr=1 def __setattr__(self,name,value): try: assert name=="readOnlyAttr" print 1 self.__dict__[name] print 2 raise TypeError, "Cannot change a readonly attribute" except KeyError: self.__dict__[name]=value except AssertionError: self.__dict__[name]=value The downside to this is obvious: This is an enormous amount of code to do a simple thing, and must be cleverly thought out. Most would say that this is not Pythonic. Here is what that code would look like following this proposal: class blah: def __init__(self): self.readOnlyAttr=1 self.save_setattr=self.__setattr__ #makes a copy of the #previous, built-in __setattr__() def __setattr__(self,name,value): #this function is created #after __init__() has been called if name=="readOnlyAttr": raise TypeError, "Cannot change a readonly attribute" else: self.save_setattr(name,value) This code is much smaller and more readable. It also does not use __dict__[], which is a dictionary representation of the class. Since blah().__dict__ and blah() refer to the same object in the current version of Python, we are not able to take full advantage of object orientation, because this causes class objects to really have two different types. This PEP does not propose to remove __dict__[] (maybe in Python 3000 __dict__[] will be removed); It just proposes a way to take a fuller advantage of object orientation. Another example: Suppose you wanted to create your own __setattr__() member function, but you were deriving your class from another class that may or may not have that member function already. Suppose also, that you want to use that function after filtering through your own __setattr__() member function. This is how that might be done in the current version of Python: class blah(derivitive): def __init__(self): try: self.save_setattr=self.__setattr__ self.__setattr__=self.new_setattr except: self.__setattr__=self.new_setattr def ne
equivalent to c++ "reference" or "pointers"
Hello,Is there a Python equivalent to creating "reference" or "pointer"-type variables as in C++?? I'm trying to create a couple classes that have something like a container-and-iterator relationship; one class acts as a data resource (container-like) and can be queried by multiple control classes if needed (iterator-like). If it's of any use, one class will contain all the frames of an animation and its attributes, and the other will query the former for image data and those attributes but control the actual animation process on its own. Here is a simple (albeit crappily written) example, in C++, of what I'm trying to achieve. Perhaps in Python I should be using a different paradigm than this... that would be fine, as long as I can figure out something that will serve my purpose. #include using namespace std;class CrazyRes {private: char *astring, *bstring; public: void setAString(char *s); void setBString(char *s); char *getAString() { return astring; } char *getBString() { return bstring; }};void CrazyRes::setAString(char *s){ astring = new char[255]; strcpy(astring, s);}void CrazyRes::setBString(char *s){ bstring = new char[255]; strcpy(bstring, s);}class CrazyCtrl {private: CrazyRes *res; public: void attach(CrazyRes *r) { res = r; } void printAString() { cout << res->getAString(); } void printBString() { cout << res->getBString(); }};int main(){ CrazyRes res; CrazyCtrl ctrl; res.setAString("Hey! A-String!\n"); res.setBString("Whoa! B-String!\n"); ctrl.attach(&res); ctrl.printAString(); ctrl.printBString(); return 0;}I tried to keep this to the point... thanks in advance for any suggestions.Colin -- http://mail.python.org/mailman/listinfo/python-list
[ANN] functional 0.5 released
Hello all, I have released version 0.5 of my functional module, a collection of higher-order and functional programming tools for Python. Currently offered are tools for function composition, partial function application, plus flip, foldl, foldr, scanl and scanr functions. Two version of the release are available: one is written in pure Python and aims for maximum readability and portability. The other is coded as a C extension module and is focused on raw performance. Where to get it: # functional is available at http://oakwinter.com/code/functional/ and from the Python Package Index at http://cheeseshop.python.org/pypi/functional. Both source tarballs and Python Eggs are available for both the pure Python and C releases. I'm open to user-contributed RPM, Deb or other packagings. Release Notes The biggest news in this release is the addition of the C implementation. Also, a number of functions were removed, as I had unknowingly duplicated a lot of functionality from the itertools module. As always, feedback welcome! Collin Winter -- http://mail.python.org/mailman/listinfo/python-list
Re: [ANN] functional 0.5 released
On 2/11/06, Neal Becker <[EMAIL PROTECTED]> wrote: > I just installed from .tar.gz on fedora FC5 x86_64. I ran into 1 small > problem: > [snip] > Because this distribution was installed --multi-version or --install-dir, > before you can import modules from this package in an application, you > will need to 'import pkg_resources' and then use a 'require()' call > similar to one of these examples, in order to select the desired version: > > pkg_resources.require("functional") # latest installed version > pkg_resources.require("functional==0.5") # this exact version > pkg_resources.require("functional>=0.5") # this version or higher > > Processing dependencies for functional==0.5 > > What's all this about multi-version? Did I do something wrong? I've tried installing the package in all sorts of ways and haven't been able to reproduce this problem. I'm guessing that somewhere in your setuptools configuration, however, that there's a config file passing --multi-version or --install-dir without your knowledge. Do you get this same message when installing other Python packages? Thanks, Collin Winter -- http://mail.python.org/mailman/listinfo/python-list
Re: functional 0.5 released
On 10 Feb 2006 19:57:48 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > > Collin Winter wrote: > > As always, feedback welcome! > > Any specific reason flip only flip the first 2 arguments rather than > the whole tuple ? > > That is, I would like to see: > > assert(f(a,b,c, d) == flip(f)(d, c, b, a)) Because that's what I'm used to from Haskell and other functional languages : ) I'll see what I can do about having it flip all arguments in the next release. Thanks, Collin Winter -- http://mail.python.org/mailman/listinfo/python-list
[ANN] svnmock 0.3 released
Hello all, Version 0.3 of `svnmock`, a package for testing Python applications that use Subversion's Python bindings, has been released. `svnmock` emulates the entire suite of Python bindings, allowing developers to ensure that their application is calling the expected API functions with the expected arguments. In addition, `svnmock` provides facilities for simulating error conditions that would otherwise be difficult or impossible to test against. Last but not least, `svnmock` includes support for tracing API calls, allowing for quick debugging without the need to mock up an entire application. `svnmock` is compatible with all releases of Subversion, including the just-released 1.3.0. Where to get it: # functional is available at http://oakwinter.com/code/svnmock/ and from the Python Package Index at http://cheeseshop.python.org/pypi/svnmock Source tarballs are available, as are Python Eggs for Python 2.4 and 2.5. Release Notes The 0.3 release is primarily a refinement release. Certain parts of the package have been made much easier to use for the vast majority of use cases. A full tutorial and reference manual is available at http://oakwinter.com/code/svnmock/. As always, feedback welcome! Collin Winter -- http://mail.python.org/mailman/listinfo/python-list
Direct memory access
Does anyone know how to directly handle memory using python? I want to be able, for example, to copy the actual contents of a memory address, or set the actual contents of a memory address. Here is an example of what I would like to be able to do: num=12 addr=id(num) contents=(hex(addr)).read(2) contents "0b" (hex(addr),"w").write("0e") num 15 In that example, I was assuming that the function would return a file like object: it doesn't have to. Any type of function would be fine. -- http://mail.python.org/mailman/listinfo/python-list
Re: Direct memory access
Thanks. I didn't know about ctypes. -- http://mail.python.org/mailman/listinfo/python-list
Re: Direct memory access
One last thing. Does anyone know how to take a python object and measure how much space it is taking up in memory? I'm thinking probably not, but it's worth asking. -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-Dev] Python 3000 PEP: Postfix type declarations
On 4/1/07, Georg Brandl <[EMAIL PROTECTED]> wrote: [snip several pages of excellent ideas] > > The mapping between types and declarators is not static. It can be completely > customized by the programmer, but for convenience there are some predefined > mappings for some built-in types: > > = === > Type Declarator > = === > ``object`` � (REPLACEMENT CHARACTER) > ``int``ℕ (DOUBLE-STRUCK CAPITAL N) > ``float`` ℮ (ESTIMATED SYMBOL) > ``bool`` ✓ (CHECK MARK) > ``complex``ℂ (DOUBLE-STRUCK CAPITAL C) > ``str``✎ (LOWER RIGHT PENCIL) > ``unicode``✒ (BLACK NIB) > ``tuple`` ⒯ (PARENTHESIZED LATIN SMALL LETTER T) > ``list`` ♨ (HOT SPRINGS) > ``dict`` ⧟ (DOUBLE-ENDED MULTIMAP) > ``set``∅ (EMPTY SET) (*Note:* this is also for full sets) > ``frozenset`` ☃ (SNOWMAN) > ``datetime`` ⌚ (WATCH) > ``function`` ƛ (LATIN SMALL LETTER LAMBDA WITH STROKE) > ``generator`` ⚛ (ATOM SYMBOL) > ``Exception`` ⌁ (ELECTRIC ARROW) > = === > > The declarator for the ``None`` type is a zero-width space. > > These characters should be obvious and easy to remember and type for every > programmer. > [snip] > > Example > === > > This is the standard ``os.path.normpath`` function, converted to type > declaration > syntax:: > > def normpathƛ(path✎)✎: > """Normalize path, eliminating double slashes, etc.""" > if path✎ == '': > return '.' > initial_slashes✓ = path✎.startswithƛ('/')✓ > # POSIX allows one or two initial slashes, but treats three or more > # as single slash. > if (initial_slashes✓ and > path✎.startswithƛ('//')✓ and not path✎.startswithƛ('///')✓)✓: > initial_slashesℕ = 2 > comps♨ = path✎.splitƛ('/')♨ > new_comps♨ = []♨ > for comp✎ in comps♨: > if comp✎ in ('', '.')⒯: > continue > if (comp✎ != '..' or (not initial_slashesℕ and not new_comps♨)✓ > or > (new_comps♨ and new_comps♨[-1]✎ == '..')✓)✓: > new_comps♨.appendƛ(comp✎) > elif new_comps♨: > new_comps♨.popƛ()✎ > comps♨ = new_comps♨ > path✎ = '/'.join(comps♨)✎ > if initial_slashesℕ: > path✎ = '/'*initial_slashesℕ + path✎ > return path✎ or '.' > > As you can clearly see, the type declarations add expressiveness, while at the > same time they make the code look much more professional. My only concern is that this doesn't go far enough. While knowing that some object is a ⒯ is a good start, it would be so much more helpful to know that it's a ⒯ of ✎s. I think something like ✎✎✎3⒯ to indicate a 3-⒯ of ✎s would be nice. This would change the line in the above from "if comp✎ in ('', '.')⒯:" to "if comp✎ in ('', '.')✎✎2⒯:", which I think is a nice win in terms of readability, EIBTI and all that. (Sidebar: I think the PEP should feature a section on how these new type declarations will cut down on mailing list volume and documentation size.) In light of this PEP, PEP 3107's function annotations should be rejected. All that hippie feel-good crap about "user-defined annotations" and "open-ended semantics" and "no rules, man" was just going to get us into trouble. This PEP's more modern conception of type annotations give the language a power and expressiveness that my PEP could never hope to match. This is clearly a move in the right direction. +4 billion. Collin Winter -- http://mail.python.org/mailman/listinfo/python-list
Re: way to extract only the message from pop3
so get two strings: only headers, and the whole message. find the length of the headers, and chop that off the beginning of the whole message: message=whole_message[len(headers):None] You can omit the word None: it is just there for clarity purposes. On 3 Apr 2007 12:36:10 -0700, flit <[EMAIL PROTECTED]> wrote: Hello All, Using poplib in python I can extract only the headers using the .top, there is a way to extract only the message text without the headers? like remove the fields below: " Return-Path: X-Original-To: Received: from [ by (Postfix) with ESMTP id B32382613C for Tue, 3 Apr 2007 09:54:28 -0300 (BRT) Date: Tue, 03 Apr 2007 09:52:15 -0300 From: <@> To: Subject: test Message-Id: MIME-Version: 1.0 Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit X-Mailer: Becky! ver. 2.24.02 [en] X-UIDL: !Dn!!HKT!!/k Status: RO " and only get this: this is a text message.. .. Thanks -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Looping issues
I don't know what is wrong with your code yet, but first you should clean it up. Either replace those backslashes with forward slashes, or put r before the first quote in the path string. This prevents special characters from being evaluated as such. Second, you should debug a little. Feel free to put print statements in! correct_settings = open(r"C:\Python25\Scripts\Output\correct_settings.txt","r") current_settings = open(r"C:\Python25\Scripts\Output\output.txt","r") for line in correct_settings: print "line=", line for val in current_settings: print "val=", val if val == line: print line, "found." ## please don't concatenate strings in the print statement! separate them with commas! break ## You have already found that the same line is in both files: you don't need to keep searching correct_settings.close() current_settings.close() On 5 Apr 2007 11:01:09 -0700, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: What I am trying to do is compare two files to each other. If the 2nd file contains the same line the first file contains, I want to print it. I wrote up the following code: correct_settings = open("C:\Python25\Scripts\Output \correct_settings.txt","r") current_settings = open("C:\Python25\Scripts\Output\output.txt","r") for line in correct_settings: for val in current_settings: if val == line: print line + " found." correct_settings.close() current_settings.close() For some reason this only looks at the first line of the correct_settings.txt file. Any ideas as to how i can loop through each line of the correct_settings file instead of just looking at the first? -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Looping issues
That *shouldn't* be the problem, since files are iterable On 5 Apr 2007 11:18:50 -0700, anglozaxxon <[EMAIL PROTECTED]> wrote: On Apr 5, 2:01 pm, [EMAIL PROTECTED] wrote: > What I am trying to do is compare two files to each other. > > If the 2nd file contains the same line the first file contains, I want > to print it. I wrote up the following code: > > correct_settings = open("C:\Python25\Scripts\Output > \correct_settings.txt","r") > current_settings = open("C:\Python25\Scripts\Output\output.txt","r") > > for line in correct_settings: > for val in current_settings: > if val == line: > print line + " found." > > correct_settings.close() > current_settings.close() > > For some reason this only looks at the first line of the > correct_settings.txt file. Any ideas as to how i can loop through each > line of the correct_settings file instead of just looking at the first? Instead of "for line in correct_settings", try "for line in correct_settings.readlines()". -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Can we make a local variable in a function as global variable???
As for me, I find this problem annoying, but easy to solve. My solution is: this=__import__(__name__) To set global variable spam to 4, I say: this.spam=4 This always works, and is much more convenient than: global spam spam=4 and then worry about local variables also named spam. On 5 Apr 2007 02:19:34 -0700, sairam <[EMAIL PROTECTED]> wrote: I have some local variables defined in one method and Can I make those variables as global variables? If so , can any one explain me how can I do that Thanks, Sairam -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: way to extract only the message from pop3
I only put None there so that the colon would be more visible: in some browser fonts, [value:] looks the same as [value] On 4/5/07, Gabriel Genellina <[EMAIL PROTECTED]> wrote: En Thu, 05 Apr 2007 15:09:18 -0300, Collin Stocks <[EMAIL PROTECTED]> escribió: > message=whole_message[len(headers):None] > > You can omit the word None: it is just there for clarity purposes. Uhm... I can't find any usage of slices including an explicit None in code.google.com (except on the Python test suite), and really I don't consider that to be more readable than whole_message[len(headers):] But of course this is just a stylistic issue. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Can we make a local variable in a function as global variable???
Then name it something else. I tend to chose "this" because it is a meaningless name that would not tend to be used for anything else. I would have used "self", except that that tends to be used inside classes. My inspiration for coming up with this is to make modules a little more like classes. I suppose you wouldn't like me to post my own (somewhat buggy) module that allows you to import modules as new type classes? On 4/5/07, Steve Holden <[EMAIL PROTECTED]> wrote: Collin Stocks wrote: > As for me, I find this problem annoying, but easy to solve. My solution is: > > >>> this=__import__(__name__) > > To set global variable spam to 4, I say: > > >>> this.spam=4 > > This always works, and is much more convenient than: > > >>> global spam > >>> spam=4 > > and then worry about local variables also named spam. > That's truly horrible. And what if you have a local variable called "this"? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Recent Ramblings http://holdenweb.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Web Servers and Page Retrievers
I tried it, and when checking it using a proxy, saw that it didn't really work, at least in the version that I have (urllib v1.17 and urllib2 v2.5). It just added that header onto the end, therefore making there two User-Agent headers, each with different values. I might add that my script IS able to retrieve search pages from Google, whereas both urllibs are FORBIDDEN with the headers that they use. On 4/8/07, Max Erickson <[EMAIL PROTECTED]> wrote: Subscriber123 <[EMAIL PROTECTED]> wrote: > urllib, or urllib2 for advanced users. For example, you can > easily set your own headers when retrieving and serving pages, > such as the User-Agent header which you cannot set in either > urllib or urllib2. Sure you can. See: http://www.diveintopython.org/http_web_services/user_agent.html (though the behavior was changed for python 2.3 to make setting the user agent work better) max -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: os.popen() not executing command on windows xp
I have no clue what is wrong. If all else fails, use os.system() instead of os.popen(). Pipes tend not to always work in windows. -- http://mail.python.org/mailman/listinfo/python-list
[ANNOUNCE]: functional 0.6 released
Hello all, I have released version 0.6 of my functional module, a collection of higher-order and functional programming tools for Python. Currently offered are tools for function composition, partial function application, plus flip, foldl, foldr, scanl and scanr functions. Two version of the release are available: one is written in pure Python and aims for maximum readability and portability. The other is coded as a C extension module and is focused on raw performance. Where to get it: # functional is available from the project's website at http://oakwinter.com/code/functional/download/ and from the Python Package Index at http://cheeseshop.python.org/pypi/functional. Both source tarballs and Python Eggs are available for both the pure Python and C releases. Eggs are available for Python versions 2.3, 2.4 and 2.5. Release Notes + flip will now reverse all non-keyword arguments, as opposed to simply reversing the first two as it did in version 0.5 (by popular request). + functional.compose now comes with an optional unpack parameter to make up for the fact that Python functions aren't fully curried. The unpack parameter means that you can now do something like this with compose: >>> f(*g(*arg,**kw)) i.e., automatically unpacking g's return value and passing the result to f. To get this functionality, you'd write something like: >>> compose(f, g, unpack=True)(*args, **kwargs) This was impossible with functional 0.5. + Weakref support has been added to flip and compose objects in the C version. + Sundry performance improvements for the C implementation. As always, feedback welcome! Collin Winter -- http://mail.python.org/mailman/listinfo/python-list
[ANNOUNCE]: typecheck 0.3.5 released
Hello all, I have released version 0.3.5 of my typecheck module, a Python module providing run-time typechecking facilities for function parameters and return values, as well as generator yield values. The main workhorses of this module, the functions accepts, returns and yields, are used as function/method decorators. These operate on a function arguments, function return values and generator yield values, respectively. A number of utility classes are provided to assist in building more complex signatures, for example, by creating boolean expressions based on classes and/or types. It is possible to incorporate typechecking facilities into user-defined classes. A mixin class, UnorderedIteratorMixin, is provided to allow easy typechecking of iterators. Numerous examples are provided as to how to integrate your own container classes into typecheck. Where to get it: # typecheck is available from the project's website at http://oakwinter.com/code/typecheck/ and from the Python Package Index at http://cheeseshop.python.org/pypi/typecheck Both source tarballs and Python Eggs for Python versions 2.4 and 2.5 are available. Release Notes This is a bug-fix release: + After fixing an issue with the test suite, typecheck is now compatible with Python 2.5 + Compatibility issues: - Typeclass instances are no longer callable. This means that "Number() is not Number" is True. This was done to fix a bug with typeclasses. + Bug fixes: - Add an __all__ list to typecheck/__init__.py - Instances with __call__ methods can now be used as functions (ie, in conjunction with Function) - Unicode can now be used to specify type variables - Rename all message() methods on the internal _TC_* extensions to error_message() (Python 2.5's exceptions already have message attribute) - Add repr() and str() support to Typeclass instances - Fix a bug related to typecheck_args()'s checking of the number of arguments passed to the typechecked function - Fix SF #1495358; typeclasses can now actually be used. As always, feedback welcome! Collin Winter -- http://mail.python.org/mailman/listinfo/python-list
Re: Factoring Polynomials
On Dec 18, 11:52 am, eric wrote: > On Dec 18, 8:37 pm, collin.da...@gmail.com wrote: > > > I am trying to write a simple application to factor polynomials. I > > wrote (simple) raw_input lines to collect the a, b, and c values from > > the user, but I dont know how to implement the quadratic equation > > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > > into python. Any ideas? > > with numpy: > from numpy import * > > s=[1,-1] > x = -b+s*sqrt( b**2-4*a*c )/(2*a) > > Erichttp://codeslash.blogspot.com Ahh. Great.. thank you. I didnt know about the sqrt function.. saves me from doing "^1/2". Thanks again. -CD -- http://mail.python.org/mailman/listinfo/python-list
Re: Factoring Polynomials
On Dec 18, 1:09 pm, Mark Dickinson wrote: > On Dec 18, 8:47 pm, Scott David Daniels wrote: > > > else: # a single result (discriminant is zero) > > return (-b / (2 * a),) > > Maybe make that (-b / (2. * a)) to avoid getting funny results > when a and b are integers. (Or do a from __future__ import > division, or use Python 3.0, or ) > > And to make the function more bullet-proof, you might want to > do something like (untested): > > from math import copysign > > [rest of example as in Scott's post] > > if discriminant: # two results > root1 = (-b - copysign(discriminant, b))/(2*a) > root2 = c/(a*root1) > return (root1, root2) > > to avoid numerical problems when b*b is much larger > than abs(a*c). Compare with the results of the usual > formula when a = c = 1, b = 10**9, for example. But > that still doesn't help you when the computation > of the discriminant underflows or overflows... > > Isn't floating-point a wonderful thing! :) > > Mark Thanks for all your help! Its good to know how to do it w/ without numpy. And yes, floating point is the best thing since sliced bread. ^^ -CD -- http://mail.python.org/mailman/listinfo/python-list
Re: Factoring Polynomials
On Dec 18, 4:41 pm, "James Mills" wrote: > On Fri, Dec 19, 2008 at 10:11 AM, Gabriel Genellina > > wrote: > > En Thu, 18 Dec 2008 17:37:35 -0200, escribió: > > >> I am trying to write a simple application to factor polynomials. I > >> wrote (simple) raw_input lines to collect the a, b, and c values from > >> the user, but I dont know how to implement the quadratic equation > > >> x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > Why is this so hard ? This is simple simple > expression. Reading through the Python > tutorial and reading up on how to define > functions is all you need! :) > > Here goes: > > >>> def f(a, b, c): > > ... x = (-1 * b) + ((b**2 - (4 * a * c)) / (2 * a)) > ... return (-1 * x), x > ... > > >>> f(1, 2, 3) > (6, -6) > > cheers > James Hiya James! Just one small problem with your equation above... The quadratic formula is: x = -b +or- (b**2 - (4 * a * c))^1/2 / 2a You just forgot the square root which makes quadratic a bit more complicated. You would have to download and import sqrt() from numpy or **.5 Also.. I need to build in functionality so the user does not have to directly call the function like: f(a,b,c) Instead.. they should be able to just raw_input their values. Also.. as with some of the examples above its a good idea to analyze the discriminant to make sure we have a real solution. Of course.. thats all pretty simple to build in. Thanks a lot! -- http://mail.python.org/mailman/listinfo/python-list
Re: Factoring Polynomials
On Dec 18, 5:30 pm, "James Mills" wrote: > UPDATE: > > jmi...@atomant:~/tmp$ cat polycalc.py > #!/usr/bin/env python > > from math import sqrt > > def f(a, b, c): > if (b**2 - (4 * a * c)) < 0: > return None, None # Can't solve > x1 = -b - (sqrt(b**2 - (4 * a * c)) / (2 * a)) > x2 = -b + (sqrt(b**2 - (4 * a * c)) / (2 * a)) > return x1, x2 > > print "Polynomial Solver..." > print > > while True: > a = float(raw_input("a: ")) > b = float(raw_input("b: ")) > c = float(raw_input("c: ")) > > x = f(a, b, c) > if None in x: > print "Can't solve!" > else: > print "x = (%0.2f, %0.2f)" % x > jmi...@atomant:~/tmp$ ./polycalc.py > Polynomial Solver... > > a: 1 > b: 8 > c: 5 > x = (-11.32, -4.68) Ahh. Great.. that answers a lot of questions. Originally I was using just a = raw_input('a: ') And was getting errors because you cant perform mathmatical operations on strings. >.< Thanks again! -- http://mail.python.org/mailman/listinfo/python-list
Re: Factoring Polynomials
On Dec 18, 5:10 pm, Steven D'Aprano wrote: > On Thu, 18 Dec 2008 11:37:35 -0800, collin.day.0 wrote: > > I am trying to write a simple application to factor polynomials. I wrote > > (simple) raw_input lines to collect the a, b, and c values from the > > user, but I dont know how to implement the quadratic equation > > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > > into python. Any ideas? > > def quadratic_solution(a, b, c): > sol1 = (-b + (b**2 - 4*a*c)**0.5)/2*a > sol2 = (-b - (b**2 - 4*a*c)**0.5)/2*a > return (sol1, sol2) > > Because this looks like homework, I've deliberately left in two errors in > the above. One of them is duplicated in the two lines above the return, > and you must fix it or you'll get radically wrong answers. > > The second is more subtle, and quite frankly if this is homework you > could probably leave it in and probably not even lose marks. You will > need to do significant research into numerical methods to learn what it > is, but you will then get significantly more accurate results. > > -- > Steven The corrected function is: def quadratic_solution(a,b,c) sol1 = -1*b + ((b**2 - 4*a*c)**.5)/2*a sol1 = -1*b - ((b**2 - 4*a*c)**.5)/2*a return (sol1, sol2) Squaring the -b would give you some strange solutions :D -CD -- http://mail.python.org/mailman/listinfo/python-list
Re: Factoring Polynomials
On Dec 18, 11:37 am, collin.da...@gmail.com wrote: > I am trying to write a simple application to factor polynomials. I > wrote (simple) raw_input lines to collect the a, b, and c values from > the user, but I dont know how to implement the quadratic equation > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > into python. Any ideas? I completed the code: #import from math import sqrt # collect data a = float(raw_input('Type a value: ')) b = float(raw_input('Type b value: ')) c = float(raw_input('Type c value: ')) # create solver def solver(a,b,c): if b**2 - 4*a*c < 0: return 'No real solution.' else: sol1 = -1 * b + (sqrt(b**2 - 4*a*c)) / 2*a sol2 = -1 * b - (sqrt(b**2 - 4*a*c)) / 2*a return (sol1, sol2) # execute print solver(a,b,c) Thanks to everyone who helped... This really expanded my knowledge on some of the mathematical functions in Python. -- http://mail.python.org/mailman/listinfo/python-list
Re: Factoring Polynomials
On Dec 18, 6:12 pm, Collin D wrote: > On Dec 18, 11:37 am, collin.da...@gmail.com wrote: > > > I am trying to write a simple application to factor polynomials. I > > wrote (simple) raw_input lines to collect the a, b, and c values from > > the user, but I dont know how to implement the quadratic equation > > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > > into python. Any ideas? > > I completed the code: > > #import > from math import sqrt > > # collect data > a = float(raw_input('Type a value: ')) > b = float(raw_input('Type b value: ')) > c = float(raw_input('Type c value: ')) > > # create solver > def solver(a,b,c): > if b**2 - 4*a*c < 0: > return 'No real solution.' > else: > sol1 = -1 * b + (sqrt(b**2 - 4*a*c)) / 2*a > sol2 = -1 * b - (sqrt(b**2 - 4*a*c)) / 2*a > return (sol1, sol2) > > # execute > print solver(a,b,c) > > Thanks to everyone who helped... > This really expanded my knowledge on some of the mathematical > functions in Python. UPDATE: ' #import from math import sqrt # collect data a = float(raw_input('Type a value: ')) b = float(raw_input('Type b value: ')) c = float(raw_input('Type c value: ')) # create solver def solver(a,b,c): if b**2 - 4*a*c < 0: return 'No real solution.' else: sol1 = (-1 * b + (sqrt(b**2 - 4*a*c))) / 2*a sol2 = (-1 * b - (sqrt(b**2 - 4*a*c))) / 2*a return (sol1, sol2) # execute print solver(a,b,c) -- http://mail.python.org/mailman/listinfo/python-list
Re: Factoring Polynomials
On Dec 18, 6:23 pm, "Russ P." wrote: > On Dec 18, 6:17 pm, Collin D wrote: > > > > > > > On Dec 18, 6:12 pm, Collin D wrote: > > > > On Dec 18, 11:37 am, collin.da...@gmail.com wrote: > > > > > I am trying to write a simple application to factor polynomials. I > > > > wrote (simple) raw_input lines to collect the a, b, and c values from > > > > the user, but I dont know how to implement the quadratic equation > > > > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > > > > into python. Any ideas? > > > > I completed the code: > > > > #import > > > from math import sqrt > > > > # collect data > > > a = float(raw_input('Type a value: ')) > > > b = float(raw_input('Type b value: ')) > > > c = float(raw_input('Type c value: ')) > > > > # create solver > > > def solver(a,b,c): > > > if b**2 - 4*a*c < 0: > > > return 'No real solution.' > > > else: > > > sol1 = -1 * b + (sqrt(b**2 - 4*a*c)) / 2*a > > > sol2 = -1 * b - (sqrt(b**2 - 4*a*c)) / 2*a > > > return (sol1, sol2) > > > > # execute > > > print solver(a,b,c) > > > > Thanks to everyone who helped... > > > This really expanded my knowledge on some of the mathematical > > > functions in Python. > > > UPDATE: > > ' > > > #import > > from math import sqrt > > > # collect data > > a = float(raw_input('Type a value: ')) > > b = float(raw_input('Type b value: ')) > > c = float(raw_input('Type c value: ')) > > > # create solver > > def solver(a,b,c): > > if b**2 - 4*a*c < 0: > > return 'No real solution.' > > else: > > sol1 = (-1 * b + (sqrt(b**2 - 4*a*c))) / 2*a > > sol2 = (-1 * b - (sqrt(b**2 - 4*a*c))) / 2*a > > return (sol1, sol2) > > > # execute > > print solver(a,b,c) > > You need to put your denominator, 2*a, in parens. The way it stands, > you are dividing by 2, then multiplying by a. That's not what you > want. > > Also, for better style, I suggest you compute the discriminanat once > and store it for reuse rather than repeating the expression three > times.- Hide quoted text - > > - Show quoted text - I see what you mean on the denominator and discriminant. Ill do that. -- http://mail.python.org/mailman/listinfo/python-list
Re: Factoring Polynomials
On Dec 18, 6:27 pm, Collin D wrote: > On Dec 18, 6:23 pm, "Russ P." wrote: > > > > > > > On Dec 18, 6:17 pm, Collin D wrote: > > > > On Dec 18, 6:12 pm, Collin D wrote: > > > > > On Dec 18, 11:37 am, collin.da...@gmail.com wrote: > > > > > > I am trying to write a simple application to factor polynomials. I > > > > > wrote (simple) raw_input lines to collect the a, b, and c values from > > > > > the user, but I dont know how to implement the quadratic equation > > > > > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > > > > > into python. Any ideas? > > > > > I completed the code: > > > > > #import > > > > from math import sqrt > > > > > # collect data > > > > a = float(raw_input('Type a value: ')) > > > > b = float(raw_input('Type b value: ')) > > > > c = float(raw_input('Type c value: ')) > > > > > # create solver > > > > def solver(a,b,c): > > > > if b**2 - 4*a*c < 0: > > > > return 'No real solution.' > > > > else: > > > > sol1 = -1 * b + (sqrt(b**2 - 4*a*c)) / 2*a > > > > sol2 = -1 * b - (sqrt(b**2 - 4*a*c)) / 2*a > > > > return (sol1, sol2) > > > > > # execute > > > > print solver(a,b,c) > > > > > Thanks to everyone who helped... > > > > This really expanded my knowledge on some of the mathematical > > > > functions in Python. > > > > UPDATE: > > > ' > > > > #import > > > from math import sqrt > > > > # collect data > > > a = float(raw_input('Type a value: ')) > > > b = float(raw_input('Type b value: ')) > > > c = float(raw_input('Type c value: ')) > > > > # create solver > > > def solver(a,b,c): > > > if b**2 - 4*a*c < 0: > > > return 'No real solution.' > > > else: > > > sol1 = (-1 * b + (sqrt(b**2 - 4*a*c))) / 2*a > > > sol2 = (-1 * b - (sqrt(b**2 - 4*a*c))) / 2*a > > > return (sol1, sol2) > > > > # execute > > > print solver(a,b,c) > > > You need to put your denominator, 2*a, in parens. The way it stands, > > you are dividing by 2, then multiplying by a. That's not what you > > want. > > > Also, for better style, I suggest you compute the discriminanat once > > and store it for reuse rather than repeating the expression three > > times.- Hide quoted text - > > > - Show quoted text - > > I see what you mean on the denominator and discriminant. Ill do that.- Hide > quoted text - > > - Show quoted text - UPDATE: #import from math import sqrt # collect data a = float(raw_input('Type a value: ')) b = float(raw_input('Type b value: ')) c = float(raw_input('Type c value: ')) # find discriminant disc = b**2 - 4*a*c # create solver def solver(a,b,c): if disc < 0: return 'No real solution.' else: sol1 = (-1 * b + (sqrt(disc))) / (2*a) sol2 = (-1 * b - (sqrt(disc))) / (2*a) return (sol1, sol2) # execute print solver(a,b,c) -- http://mail.python.org/mailman/listinfo/python-list
Re: Factoring Polynomials
On Dec 18, 6:41 pm, "Russ P." wrote: > On Dec 18, 6:31 pm, Collin D wrote: > > > > > > > On Dec 18, 6:27 pm, Collin D wrote: > > > > On Dec 18, 6:23 pm, "Russ P." wrote: > > > > > On Dec 18, 6:17 pm, Collin D wrote: > > > > > > On Dec 18, 6:12 pm, Collin D wrote: > > > > > > > On Dec 18, 11:37 am, collin.da...@gmail.com wrote: > > > > > > > > I am trying to write a simple application to factor polynomials. I > > > > > > > wrote (simple) raw_input lines to collect the a, b, and c values > > > > > > > from > > > > > > > the user, but I dont know how to implement the quadratic equation > > > > > > > > x = (-b +or- (b^2 - 4ac)^1/2) / 2a > > > > > > > > into python. Any ideas? > > > > > > > I completed the code: > > > > > > > #import > > > > > > from math import sqrt > > > > > > > # collect data > > > > > > a = float(raw_input('Type a value: ')) > > > > > > b = float(raw_input('Type b value: ')) > > > > > > c = float(raw_input('Type c value: ')) > > > > > > > # create solver > > > > > > def solver(a,b,c): > > > > > > if b**2 - 4*a*c < 0: > > > > > > return 'No real solution.' > > > > > > else: > > > > > > sol1 = -1 * b + (sqrt(b**2 - 4*a*c)) / 2*a > > > > > > sol2 = -1 * b - (sqrt(b**2 - 4*a*c)) / 2*a > > > > > > return (sol1, sol2) > > > > > > > # execute > > > > > > print solver(a,b,c) > > > > > > > Thanks to everyone who helped... > > > > > > This really expanded my knowledge on some of the mathematical > > > > > > functions in Python. > > > > > > UPDATE: > > > > > ' > > > > > > #import > > > > > from math import sqrt > > > > > > # collect data > > > > > a = float(raw_input('Type a value: ')) > > > > > b = float(raw_input('Type b value: ')) > > > > > c = float(raw_input('Type c value: ')) > > > > > > # create solver > > > > > def solver(a,b,c): > > > > > if b**2 - 4*a*c < 0: > > > > > return 'No real solution.' > > > > > else: > > > > > sol1 = (-1 * b + (sqrt(b**2 - 4*a*c))) / 2*a > > > > > sol2 = (-1 * b - (sqrt(b**2 - 4*a*c))) / 2*a > > > > > return (sol1, sol2) > > > > > > # execute > > > > > print solver(a,b,c) > > > > > You need to put your denominator, 2*a, in parens. The way it stands, > > > > you are dividing by 2, then multiplying by a. That's not what you > > > > want. > > > > > Also, for better style, I suggest you compute the discriminanat once > > > > and store it for reuse rather than repeating the expression three > > > > times.- Hide quoted text - > > > > > - Show quoted text - > > > > I see what you mean on the denominator and discriminant. Ill do that.- > > > Hide quoted text - > > > > - Show quoted text - > > > UPDATE: > > > #import > > from math import sqrt > > > # collect data > > a = float(raw_input('Type a value: ')) > > b = float(raw_input('Type b value: ')) > > c = float(raw_input('Type c value: ')) > > > # find discriminant > > disc = b**2 - 4*a*c > > > # create solver > > def solver(a,b,c): > > if disc < 0: > > return 'No real solution.' > > else: > > sol1 = (-1 * b + (sqrt(disc))) / (2*a) > > sol2 = (-1 * b - (sqrt(disc))) / (2*a) > > return (sol1, sol2) > > > # execute > > print solver(a,b,c) > > A couple of style points. I would use -b rather than -1 * b. Also, you > don't need the else clause. You can simplify it to > > def solver(a, b, c): > > disc = b**2 - 4 * a * c > > if disc < 0: return "No real solution." > > sol1 = (-b + sqrt(disc)) / (2*a) > sol2 = (-b - sqrt(disc)) / (2*a) > > return sol1, sol2- Hide quoted text - > > - Show quoted text - UPDATE: #import from math import sqrt # collect data a = float(raw_input('Type a value: ')) b = float(raw_input('Type b value: ')) c = float(raw_input('Type c value: ')) # create solver def solver(a,b,c): disc = b**2 - 4*a*c if disc < 0: return 'No real solution.' else: sol1 = (-b + (sqrt(disc))) / (2*a) sol2 = (-b - (sqrt(disc))) / (2*a) return (sol1, sol2) # execute print solver(a,b,c) -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter - problem closing window
On Jan 5, 6:25 am, "Djames Suhanko" wrote: > Hello! > I'm sorry my terrible english (my native language is portuguese). > I has a litle program that open another window. When I close de root > window in quit button, I need clicking 2 times to close. is where the > problem? > > The source: > 1 #!/usr/bin/env python > 2 from Tkinter import * > 3 import sys > 4 import random > 5 class App: > 6 def __init__(self, master): > 7 frame = Frame(master) > 8 frame.pack() > 9 rotulo = Label(frame, text="Clique em 'Gerar' e boa > sorte!",borderwidth=2,bg="gray",justify=C ENTER,relief=SUNKEN) > 10 rotulo.pack() > 11 > 12 self.button = Button(frame, text="Sair", fg="red", > command=frame.quit,borderwidth=1) > 13 self.button.pack(side=LEFT) > 14 self.hi_there = Button(frame, text="Gerar Numero", > command=self.say_hi,borderwidth=1) > 15 self.hi_there.pack(side=RIGHT,padx=2,pady=2) > 16 > 17 def gera_seis(self): > 18 a = {} > 19 for i in range(6): > 20 a[i] = "%02d" % int (random.randint(0,60)) > 21 resultadoA = "%s-%s-%s-%s-%s-%s" % > (str(a[0]),str(a[1]),str(a[2]),str(a[3]),str(a[4]),str(a[5])) > 22 return resultadoA > 23 > 24 def say_hi(self): > 25 resultado = self.gera_seis() > 26 raiz = Tk() > 27 F = Frame(raiz) > 28 F.pack() > 29 hello = Label(F, text=resultado) > 30 hello.pack() > 31 F.mainloop() > 32 > 33 root = Tk() > 34 root.title("$$$ Loteria $$$") > 35 app = App(root) > 36 root.mainloop() > > -- > Djames Suhanko > LinuxUser 158.760 Also for style, you might want to group the import lines so they look like this: from Tkinter import * import sys, random A bit more pythonic. :P -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter - problem closing window
On Jan 5, 9:21 am, Roger wrote: > On Jan 5, 11:52 am, Collin D wrote: > > > > > On Jan 5, 6:25 am, "Djames Suhanko" wrote: > > > > Hello! > > > I'm sorry my terrible english (my native language is portuguese). > > > I has a litle program that open another window. When I close de root > > > window in quit button, I need clicking 2 times to close. is where the > > > problem? > > > > The source: > > > 1 #!/usr/bin/env python > > > 2 from Tkinter import * > > > 3 import sys > > > 4 import random > > > 5 class App: > > > 6 def __init__(self, master): > > > 7 frame = Frame(master) > > > 8 frame.pack() > > > 9 rotulo = Label(frame, text="Clique em 'Gerar' e boa > > > sorte!",borderwidth=2,bg="gray",justify=C ENTER,relief=SUNKEN) > > > 10 rotulo.pack() > > > 11 > > > 12 self.button = Button(frame, text="Sair", fg="red", > > > command=frame.quit,borderwidth=1) > > > 13 self.button.pack(side=LEFT) > > > 14 self.hi_there = Button(frame, text="Gerar Numero", > > > command=self.say_hi,borderwidth=1) > > > 15 self.hi_there.pack(side=RIGHT,padx=2,pady=2) > > > 16 > > > 17 def gera_seis(self): > > > 18 a = {} > > > 19 for i in range(6): > > > 20 a[i] = "%02d" % int (random.randint(0,60)) > > > 21 resultadoA = "%s-%s-%s-%s-%s-%s" % > > > (str(a[0]),str(a[1]),str(a[2]),str(a[3]),str(a[4]),str(a[5])) > > > 22 return resultadoA > > > 23 > > > 24 def say_hi(self): > > > 25 resultado = self.gera_seis() > > > 26 raiz = Tk() > > > 27 F = Frame(raiz) > > > 28 F.pack() > > > 29 hello = Label(F, text=resultado) > > > 30 hello.pack() > > > 31 F.mainloop() > > > 32 > > > 33 root = Tk() > > > 34 root.title("$$$ Loteria $$$") > > > 35 app = App(root) > > > 36 root.mainloop() > > > > -- > > > Djames Suhanko > > > LinuxUser 158.760 > > > Also for style, you might want to group the import lines so they look > > like this: > > > from Tkinter import * > > import sys, random > > > A bit more pythonic. :P > > In that case you probably want to take out the 'from' import and: > > import Tkinter, sys, random > > in order to avoid any namespace issues especially if you have a large > project with lots of gui manipulations. But that's just me being > pedantic. ;) I agree... you could have conflicting functions.. not fun. XD -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-Dev] annoying dictionary problem, non-existing keys
2008/4/24 bvidinli <[EMAIL PROTECTED]>: > I posted to so many lists because, > > this issue is related to all lists, > this is an idea for python, > this is related to development of python... > > why are you so much defensive ? > > i think ideas all important for development of python, software > i am sory anyway hope will be helpful. Please consult the documentation first: http://docs.python.org/lib/typesmapping.html . You're looking for the get() method. This attribute of PHP is hardly considered a feature, and is not something Python wishes to emulate. Collin Winter > 2008/4/24, Terry Reedy <[EMAIL PROTECTED]>: > > > > Python-dev is for discussion of development of future Python. Use > > python-list / comp.lang.python / gmane.comp.python.general for usage > > questions. > > > > > > > > ___ > > Python-Dev mailing list > > [EMAIL PROTECTED] > > http://mail.python.org/mailman/listinfo/python-dev > > Unsubscribe: > http://mail.python.org/mailman/options/python-dev/bvidinli%40gmail.com > > > > > > -- > İ.Bahattin Vidinli > Elk-Elektronik Müh. > --- > iletisim bilgileri (Tercih sirasina gore): > skype: bvidinli (sesli gorusme icin, www.skype.com) > msn: [EMAIL PROTECTED] > yahoo: bvidinli > > +90.532.7990607 > +90.505.5667711 > ___ > > > Python-Dev mailing list > [EMAIL PROTECTED] > http://mail.python.org/mailman/listinfo/python-dev > Unsubscribe: > http://mail.python.org/mailman/options/python-dev/collinw%40gmail.com > -- http://mail.python.org/mailman/listinfo/python-list
Command parsing... best module to use?
Hey everyone. I am writing a game in python, and it includes a text console somewhat like the one in WoW and Runescape. I want to be able to include "/" commands, like IRC, and was wondering what the best module would be to parse these. Thanks a lot, Collin D -- http://mail.python.org/mailman/listinfo/python-list
Re: Command parsing... best module to use?
Thanks for the replies. Pyparsing looks just like what I need. -- http://mail.python.org/mailman/listinfo/python-list
Factoring Polynomials
I am trying to write a simple application to factor polynomials. I wrote (simple) raw_input lines to collect the a, b, and c values from the user, but I dont know how to implement the quadratic equation x = (-b +or- (b^2 - 4ac)^1/2) / 2a into python. Any ideas? -- http://mail.python.org/mailman/listinfo/python-list