Re: Problems with properties
I was thinking that in Python2.4, all class definitions inherited from new-style classes. There may be a bug here. I can make your code work as expected by changing the class definition to: class Task(object): with that change, the assignment raises an attribute error. You could also accomplish the same thing by eliminating the setNothing method and defining your property as: command=property(getCommand) or for a really simple case like this, you could even leave off the getCommand function and define the property as: command=property(lambda self: self._command) (although I am sure personal tastes vary as to style here). -- http://mail.python.org/mailman/listinfo/python-list
subtyping a builtin type in a C extension
I am trying to make a subtype of a string. Initially it will have no new methods or attributes, the C equivalent of: class myStr(str): pass I have experimented a bit, but am currently making a mess of it. Does anybody have an example they can point to of inheriting from a builtin, or a suggestion to point me in the right direction? -- http://mail.python.org/mailman/listinfo/python-list
Re: subtyping a builtin type in a C extension
Thank you. I should have looked for this sort of example. That was exactly what I needed. I don't ask for help here very often, but when I have, I have ALWAYS gotten faster results than with any commercial support option I have used. We have a good developer community :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: python GUIs comparison (want)
Ron Stevens of the Python411 podcast(1) has some good info on these. He did an entire podcast(2) comparing different Python GUI tools, and did several others in greater detail, including specifically on wyPython and Tkinter. You can also subscribe to the RSS feed(3). The main page has titles for all of the podcasts and direct links to the mp3s. Shawn 1. http://www.awaretek.com/python/ 2. http://libsyn.com/media/awaretek/Python411_070509_GUItoolkits.mp3 3. http://www.awaretek.com/python/index.xml -- http://mail.python.org/mailman/listinfo/python-list
How to implement a combo Web and Desktop app in python.
I am somewhat new to python. I am still learning it. I am starting an app that I ma not quite sure how to best implement it. In the grand scheme, there will be 4 apps total. There will be a core shared between them that allows them to easily talk to each other (ill explain) and communicate with a database, as well as redis for pubsub events. I also need things to work on both web, and desktop. So i will likely have to keep the UI and the core of each app in their own separate apps entirely. The main core on the web will be a REST interface with proper content negotiation, depending on what is requested. Normally, if the desktop is online, you may think "If you have a good rest interface, this makes the desktop version pointless". While true for some cases, the reason I need a desktop implementation, is because the end user still needs to be able to use the app while there is no internet connectivity. For example, an in store POS system. They would still need to process transactions like cash while offline, and they would also need access to their inventory. This is also good for intermittent connection problems, and for speed. So they don't have to worry about networking issues to do things. For this reason a local database is also needed. And when online, it keeps in sync with the remote database. So I need to find a way I can implement this in the best way, to help prevent code duplication, and reduce the amount of time it takes to get into production. If possible, I would like to use some kind of built in webkit for desktop as well, so users have the same experience both online and locally. So i would likely need to package a webserver as well (tornado/gunicorn?) If it was entirely online, I see how I could implement this, but when needing to have a desktop version, I feel like I would need to split things up differently. Here is so far, how I would think that I need to structure everything. Core: this is the CORE api to talk to the server, and interact with the systems. I should be able to do most things using this interface, and the individual apps may (or may not) add onto this for specific functionality. App: this is the individual apps. going along with my example, these could be the actual POS interface, a shopping cart, product catalog/inventory management, and an admin/backend that would tie into everything and be able to show things like product/customer stats and so on. Presentation: the actual user interfaces for each app. I also feel like I should put it all into one app, bundled, and only split up the ui based on web vs desktop. The different 4 apps may also be at 4 web addresses. such as: http://main.com (would probably include the admin app) http://pos.com http://products.com so what is avaiable to the end user, will also be dependant on the domain as well. If they are all on one core, with only the UI separated out, the rest interface would likely be on all of them and only allow things based on what app you are looking at. Unless you are on the master domain where everything is allowed. I understand this is a complex question about implementation, and could be philosophically different depending on the developer. But im not sure how to best go about it, so I was hoping to get some ideas and input. Should I do it an entirely different way? Currently for the apps themselves, I am looking at using either flask, bottle, web2py, or pyramid. I need to understand how I am going to implement it more before I choose a framework. Django is nice, but it doesnt seem to fit what I need to do. There are rest api plugins available for it, but if the core of my app is based on REST, it seemed to make more sense to start with something that has REST built into the core of the framework. Any input or advice is much appreciated. Thanks. - Shawn McElroy -- http://mail.python.org/mailman/listinfo/python-list
Re: How to implement a combo Web and Desktop app in python.
This does help. I have not determined if I will make a native UI for the desktop yet. To start I just figured I would use the web based interface, and if needed, use something like qt, or wx. As for the ability to drag items into the user interface, there are javascript libraries that can handle that now, which triggers an upload of that file. So I dont think that would be a large issue. For example, minus.com does this really well with file uploads (mostly image sharing). Although you are correct in the aspect of having 'real' OS level integration. Being able to communicate with other apps as well as contextual menus. Although, could I not still implement those features from python, into the host system from python? There are also tools like 'kivi' which allow you to get system level access to do things. Though im not too sure on how far that extends, or how useful it would be. as it stands now, I plan on having the 3 layers of my app. core, apps, and presentation. the core would go on both web and desktop and has no UI. the apps add on functionality to the core, based on what the app does. This way I can distribute a single app, without the others. And the UI, will be different based on platform. web/mobile will just be html/css, and desktop, will likely end up being something like qt/wx. Thanks. On Thursday, September 13, 2012 5:20:48 PM UTC-7, Shawn McElroy wrote: > I am somewhat new to python. I am still learning it. I am starting an app > that I ma not quite sure how to best implement it. > > > > In the grand scheme, there will be 4 apps total. There will be a core shared > between them that allows them to easily talk to each other (ill explain) and > communicate with a database, as well as redis for pubsub events. I also need > things to work on both web, and desktop. So i will likely have to keep the UI > and the core of each app in their own separate apps entirely. The main core > on the web will be a REST interface with proper content negotiation, > depending on what is requested. > > > > Normally, if the desktop is online, you may think "If you have a good rest > interface, this makes the desktop version pointless". While true for some > cases, the reason I need a desktop implementation, is because the end user > still needs to be able to use the app while there is no internet > connectivity. For example, an in store POS system. They would still need to > process transactions like cash while offline, and they would also need access > to their inventory. This is also good for intermittent connection problems, > and for speed. So they don't have to worry about networking issues to do > things. For this reason a local database is also needed. And when online, it > keeps in sync with the remote database. > > > > So I need to find a way I can implement this in the best way, to help prevent > code duplication, and reduce the amount of time it takes to get into > production. If possible, I would like to use some kind of built in webkit for > desktop as well, so users have the same experience both online and locally. > So i would likely need to package a webserver as well (tornado/gunicorn?) > > > > If it was entirely online, I see how I could implement this, but when needing > to have a desktop version, I feel like I would need to split things up > differently. Here is so far, how I would think that I need to structure > everything. > > > > Core: this is the CORE api to talk to the server, and interact with the > systems. I should be able to do most things using this interface, and the > individual apps may (or may not) add onto this for specific functionality. > > > > App: this is the individual apps. going along with my example, these could be > the actual POS interface, a shopping cart, product catalog/inventory > management, and an admin/backend that would tie into everything and be able > to show things like product/customer stats and so on. > > > > Presentation: the actual user interfaces for each app. > > > > I also feel like I should put it all into one app, bundled, and only split up > the ui based on web vs desktop. The different 4 apps may also be at 4 web > addresses. such as: > > > > http://main.com (would probably include the admin app) > > http://pos.com > > http://products.com > > > > so what is avaiable to the end user, will also be dependant on the domain as > well. If they are all on one core, with only the UI separated out, the rest > interface would likely be on all of them and only allow things based on what > app you are looking at. Unless you are on the master domain where everything > is allowed. > > > > I
Re: problem with bcd and a number
Thanks for your help on this, gents. Got it working now. shawn On Thu, Aug 4, 2011 at 2:28 PM, Dave Angel wrote: > nibbles from a byte -- http://mail.python.org/mailman/listinfo/python-list
Re: Development tools and practices for Pythonistas
Depends on the project, but I'd start with git the time I created the first file in my project. If you're in the habit of committing then you can easily rollback missteps. If you're in the habit of making branches you can experiment without breaking the currently-working code. -- http://mail.python.org/mailman/listinfo/python-list
Re: Development tools and practices for Pythonistas
For what it's worth, the Python core developers have selected Mercurial. I personally use git and love it. Most open-source people seem to use one or the other of the two. They're pretty similar in most ways. Look at the big two sites for open-source repositories -- github and bitbucket. One's git, the other Mercurial. I don't think you can go wrong picking either one. -- http://mail.python.org/mailman/listinfo/python-list
ANN: datatest 0.7.0 (Test driven data wrangling)
datatest 0.7.0 (Test driven data wrangling) === Datatest extends the standard library's unittest package to provide testing tools for asserting data correctness. * Docs: http://datatest.readthedocs.io/ * PyPI: https://pypi.python.org/pypi/datatest/ This release includes: * Removes internal magic and renames data assertions to more clearly indicate their intended use. * Restructures data allowances to provide more consistent parameters and more flexible usage. * Adds new method to assert unique values. * Adds full **fmtparams support for CSV handling. * Fixes comparison and allowance behavior for None vs. zero. Update installs with: pip install -U datatest Backward Compatibility: Existing code that relies on the 0.6.0 (dev1) API is supported with the following addition to the beginning of each script: from datatest.__past__ import api_dev1 -- https://mail.python.org/mailman/listinfo/python-list
Fwd: Removing python installation
I've somehow wound up in a situation where I have both 3.7.5 and 3.7.6 installed, and the py.exe launcher can find both of them, and defaults to the older one: >py -0p Installed Pythons found by py Launcher for Windows -3.7-64"C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\python.exe" * -3.7-64C:\Users\shawn\AppData\Local\Programs\Python\Python37\python.exe As you can see, the 3.7.5 install is from Visual Studio. I want to remove this python installation, however while uninstalling it via the VS Installer GUI appears to work, none of the files are removed. Only the json file VS Installer uses to track the package is removed. In the VS Installer logs, I see: Skipping uninstall of 'CPython3.Exe.x64,version=3.7.5,chip=x64' because it is permanent. which seems suspicious. Additionally, in the aforementioned json file I can see the installer being used is "python-3.7.5-amd64.exe" from https://go.microsoft.com/fwlink/?linkid=2109129 , with args: "/quiet /log \"[LogFile]\" InstallAllUsers=1 CompileAll=1 Include_symbols=1 TargetDir=\"[SharedInstallDir]\\Python37_64\"" So, I've downloaded this installer and tried to run it with the /uninstall option. Again, the uninstall appears to complete OK, but the files are not removed. The uninstall log is here: https://gist.github.com/shuffle2/3c3aa736f5cf9579e6e4a4a33b1ad81d Is there some "clean" way to remove this VS-installed 3.7.5 (and not break the 3.7.6 install)? Thanks, -Shawn -- https://mail.python.org/mailman/listinfo/python-list
network installations
Hi All - I am working on a project that requires Python be installed on multiple Windows servers. I was wondering if anyone knew of a method/utility/script that can push the installation of Python to multiple networked servers from a centralized location. Thanks in advance! -shawn begin:vcard fn:Shawn Kelley n:Kelley;Shawn org:Oracle Corp.;Server Technologies adr:Suite 700;;111 Congress Ave;Austin;TX;78701;USA email;internet:[EMAIL PROTECTED] title:Senior Technologist tel;work:512.703.4708 tel;fax:512.703.4708 tel;cell:512.921.2970 x-mozilla-html:TRUE url:http://www.oracle.com version:2.1 end:vcard -- http://mail.python.org/mailman/listinfo/python-list
first post: new to pythong. some questions.
Hello. Im brand new to this list and to python. Ive recently started reading about it
and am now in the tinkering stage. I have a script im working on that i need some
asistance debugging. Its super small and should be a snap for you gurus =)
I have 2 files in a dir off my home dir:
mkoneurl.py
make_ou_class.py
--mkoneurl.py--
#! /usr/bin/env python
import make_ou_class
run = makeoneurl()
-
--make_ou_class.py--
class makeoneurl:
def __init__():
self.commandline()
def commandline():
com = str(raw_input(":"))
#Parse out any params and aguements - reg expressions
#params[] array to hold paramters
params = 0
if com == "ou":
self.ou(params)
else:
print com + " unknown command."
def ou(parameter):
print "hello world"
self.commandline():
---
Why i run mkoneurl.py by typing "python mkonurl.py" i get the following error:
Traceback (innermost last):
File "mkoneurl.py", line 5, in ?
run = makeoneurl()
NameError: makeoneurl
am i missing something here? Any help would be greatly appreciated. Thank you
--Shawn
--
http://mail.python.org/mailman/listinfo/python-list
How did you learn Python?
I was just wondering what the best books were for learning Python. Which books are good for getting started, and which should be saved for later, or or not useful except as a reference for the learned? I have a decent programming background in VB, JavaScript, VBScript, Net.Data (IBM's macro language), regular expressions, and a teensy bit of Perl. My point is, I don't want something that is going to explain the basic programming concepts, but does give a good introduction to Python-specific things. Then, once I know how to get the job done, I would like a good book or two at the intermediate to advanced level, to learn how to write really good code. I understand that resources such as this list and Google searches have all the answers, but it seems like a more structured tool, such as a book or formal class, would be of great benefit to me. The other languages I have used were picked up because of the need to get a job done. As a result, I am able to get the job done, but any experienced coder can show me six more efficient ways to do what I'm doing. I'm new to Python, and I want to do this one right. I believe that Python will be around for a good, long time, and it matches my values as an Open-Source/Linux supporter, while having relevance in the Windows and Mac world, as well. Plus, it looks like it was designed extremely well, and I'm excited about the principles I've read about. Thanks, Shawn -- http://mail.python.org/mailman/listinfo/python-list
Re: Best book on Python?
I asked some questions last week about how those in the group learned Python, and I was given some suggestions. I ended up buying several books. Here are my brief opinions about them. In case it seems that I am too positive about these books, please take into consideration that I purchased each of them after reading plenty of reviews, and several suggestions from other list members. This list is the cream of the crop. In short, I would recommend that anyone keep all four next to the keyboard. If cost is an issue, I recommend getting them in the following order. "Dive Into Python" is available for free from diveintopython.org, but it is listed first because I think it is of the greatest immediate value. Dive Into Python Python in a Nutshell Python Cookbook Learning Python Shawn Python Cookbook Very useful as a reference. There are examples for a great many things. Almost everything I've looked for is in this book. The only downside is that the samples are sometimes too advanced for me at my beginner level. I assume that this book is meant for readers with more that a couple of weeks' experience with Python, so I doubt that the problem is with the book. Python in a Nutshell The best reference, because of the sheer volume of content. The only drawback is that, although all the options are there, clear explanations of how to make use of them are not provided, due to space considerations. This is not a negative comment -- once you have direction, you can pick up the rest elsewhere. However, I would not suggest using this as the sole reference. Dive Into Python This book is awesome. I started reading this before the others arrived. I didn't get too far into it, because I jumped directly into a project for work using Python, so I'm limping along, mainly using all three O'Reilly books as references. But this book jumps right into useful code, and does a good job of explaining it. I should have completed this book before moving on. Learning Python This book seems too basic to be used as the sole learning tool, unless the person is new to programming, not just Python. But the book does contain a lot of valuable information, and the depth of the explainations makes it a good companion to the others in my little reference set. -- http://mail.python.org/mailman/listinfo/python-list
Accessing DB2 with Python
Is anyone doing this? I would like to access a DB2 database (IBM's database) with Python. I checked "Python in a Nutshell," and it refers to ftp://people.linuxkorea.co.kr/pub/db2, but I am unable to connect to that site, although it could be a firewall issue, as I am at work. Is there any commonly used module for this? Thanks, Shawn -- http://mail.python.org/mailman/listinfo/python-list
cannot run a ruby script from a python script.
hello all. i have a linux computer that i use to run a GUI (wxGTK) program. In this program, there is a call to run an external ruby script. command = "ruby run_my_command.rb &" os.system(command) however, when it runs, i get this in the terminal sh: 1: ruby: not found i had considered that the path to the executable was messed up or somesuch, but when i just run python in the interpreter, it works fine. also, i have another computer with identical hardware, same OS, same package versions that it does work on also. This machine is to be a backup. Another note: When i run which ruby i get the path to the ruby executable. If i use that in my code, it will run, however, it will not be able to find any of the modules that i need for the ruby script to import. example command = "/path/to/ruby run_my_command.rb &" os.system(command) will run the ruby script, but the ruby script will not be able to import any of it's modules. thanks for any tips on this. -- https://mail.python.org/mailman/listinfo/python-list
Re: cannot run a ruby script from a python script.
On Wednesday, September 24, 2014 6:57:34 PM UTC-5, Shawn Bright wrote: > hello all. > > > > i have a linux computer that i use to run a GUI (wxGTK) program. In this > program, there is a call to run an external ruby script. > > > > command = "ruby run_my_command.rb &" > > os.system(command) > > > > however, when it runs, i get this in the terminal > > sh: 1: ruby: not found > > > > i had considered that the path to the executable was messed up or somesuch, > but when i just run python in the interpreter, it works fine. > > > > also, i have another computer with identical hardware, same OS, same package > versions that it does work on also. This machine is to be a backup. > > > > Another note: When i run which ruby i get the path to the ruby executable. If > i use that in my code, it will run, however, it will not be able to find any > of the modules that i need for the ruby script to import. > > > > example > > > > command = "/path/to/ruby run_my_command.rb &" > > os.system(command) > > > > will run the ruby script, but the ruby script will not be able to import any > of it's modules. > > > > > > thanks for any tips on this. I tried this with the same results. I am executing the GUI program from a terminal. It is a data engine that only really can serve our company so no reason to create menu entries for it and such. It did try to execute the ruby code, but could not. Thanks for your help. -- https://mail.python.org/mailman/listinfo/python-list
TypeError: no arguments expected
I havet these 2 files in the same dir. This is code im writing to learn pythong
mkoneurl.py:
#! /usr/bin/env python
import make_ou_class
run = make_ou_class.makeoneurl()
make_ou_class.py:
class makeoneurl:
def __init__():
self.commandline()
def commandline():
com = raw_input(":")
#Parse out any params and aguements - reg expressions
#params[] array to hold paramters
params = 0
if com == "ou":
self.ou(params)
else:
print com + " unknown command."
def ou(params):
print "hello world"
self.commandline()
===
when i run the script like this: python mkoneurl.py
I get this error:
Traceback (innermost last):
File "mkoneurl.py", line 5, in ?
run = make_ou_class.makeoneurl()
TypeError: no arguments expected
Ive looked around for this exeption but nothing ive read has help in
this situation.
Any of your thoughts are greatly apprectiated. THANK!!
--shawn
--
http://mail.python.org/mailman/listinfo/python-list
Re: TypeError: no arguments expected
thanks for all your input. Ive gotten it to work thanks! --shawn On 12/12/05, Steve Holden <[EMAIL PROTECTED]> wrote: > Dennis Lee Bieber wrote: > > On Sun, 11 Dec 2005 22:00:55 -0500, shawn a <[EMAIL PROTECTED]> > > declaimed the following in comp.lang.python: > > > > > >>I havet these 2 files in the same dir. This is code im writing to learn > >>pythong > >>mkoneurl.py: > >>#! /usr/bin/env python > >> > >>import make_ou_class > >> > >>run = make_ou_class.makeoneurl() > > > > > > Okay, you've just defined a "run" object that contains an instance > > of "makeoneurl"... What do you expect it to do? > > > Let's get the terminology right: sloppy terminology leads to sloppy > thinking. The statement binds the name "run" to a newly-created > "make_one_url" instance. Remember, "run" isn't an object, it's a > reference to an object like all Python names. > > > >> > >>make_ou_class.py: > >> > > > > Well, first off... You need to /supply/ a placeholder for "self". > > ALL methods of a class receive the instance as the first argument. So... > > > Again you need to be a little careful here, since we now have class > methods and static methods to cloud the picture. So it would be more > accurate to say that "instance methods are all automatically called with > a reference to the instance as the first argument; it is conventional to > use the name 'self' to refer to the instance". > > > [...] > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC www.holdenweb.com > PyCon TX 2006 www.python.org/pycon/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple python iteration question
On 8/14/07, Bryan <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I just started with python, and have a for loop question
>
> In c++ (or a number of other languages) I can do this:
>
> for (int i=0, j=0; i < i_len, j< j_len; ++i, ++j) {}
>
> If I have this in python:
> l = ['a', 'b', 'c']
>
> I want to get the value and also an iterator:
> for i,v in len(l), l:
> print v
> print i
>
> Or something like this without declaring the iterator outside my loop...
>
> How do I do this?
> Thanks!
> --
> http://mail.python.org/mailman/listinfo/python-list
>
If I understand properly, maybe enumerate will help you:
>>> a = ['a','b','c']
>>> for i,v in enumerate(a):
... print i
... print v
...
0
a
1
b
2
c
>>>
--
http://mail.python.org/mailman/listinfo/python-list
Re: Simple python iteration question
> this will get index and item at index, > > for i in range(0, len(l)): > print i > print l[i] > > > -- > http://mail.python.org/mailman/listinfo/python-list > Enumerate is better here -- it provides the same result and that's what it's for. However, if you do use range, the zero is unnecessary -- beginning at zero is the default. -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple python iteration question
> Use the enumerate() builtin. > > >>> l = ['a', 'b', 'c'] > >>> for i, v in enumerate(l): > ... print i, v > ... > 0 a > 1 b > 2 c > > -- Just for my own sanity: Isn't this the third response advocating the use of enumerate()? Did the other responses not get through, or was this a time-delay thing? Thanks, Shawn -- http://mail.python.org/mailman/listinfo/python-list
Re: Opinions about this new Python book?
Yes, please post back to the list. I saw this book on Amazon, but there's no table of contents listed, nor is there one on the publisher's site. Thanks, Shawn On 8/14/07, James Matthews <[EMAIL PROTECTED]> wrote: > i got to say that the best python book i bought was Core Python Programming > (2nd) by Wesly Chun! Aside for all the spelling mistakes and syntax errors > that there are i feel that the book really explained the language well for > someone coming from another programming language! > > > On 8/14/07, Dick Moores <[EMAIL PROTECTED]> wrote: > > At 05:57 AM 8/14/2007, [EMAIL PROTECTED] wrote: > > >On Aug 14, 7:05 am, Dick Moores <[EMAIL PROTECTED]> wrote: > > > > I'd appreciate opinions about this new Python book. > > > > > > > > Title: Python Power!: The Comprehensive Guide > > > > Author: Matt Telles > > > > Publisher: Course Technology > > > > Pub. Date: Jul 27, 2007 > > > > Edition: 1st edition > > > > Binding: Paperback > > > > Pages: 508 > > > > ISBN: 1598631586 > > > > List Price: 34.99 USD > > > > > > > > The book on the publisher's website: < http://tinyurl.com/2dkhzg> > > > > > > > > And at BestBookDeal.com: > > > > <http://www.bestbookdeal.com/book/compare/1598631586> > > > > > > > > Thanks, > > > > > > > > Dick Moores > > > > > >I just got this book over the weekend. I'll start reading/skimming > > >through it this week and hopefully remember to get back to you. > > > > Thanks! > > > > > By the > > >way, why do you want to know? > > > > If the experts like it, I'll buy it. > > > > Dick > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > > -- > http://www.goldwatches.com/ > http://www.jewelerslounge.com > -- > http://mail.python.org/mailman/listinfo/python-list > -- Please read: http://milocast.com/2007/07/31/this-i-believe/ -- http://mail.python.org/mailman/listinfo/python-list
Re: curses library
You should try Google -- you'll get results faster: http://www.amk.ca/python/howto/curses/ http://docs.python.org/lib/module-curses.html On 8/14/07, Ghirai <[EMAIL PROTECTED]> wrote: > Hello list, > > I need to write a console application. > > Are there any wrappers around curses/ncurses? > Or any other similar libraries? > > Thanks. > -- > Regards, > Ghirai. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Please read: http://milocast.com/2007/07/31/this-i-believe/ -- http://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] Python Book Recommendations
If I could have only one book, I would buy "Core Python, Second Edition," by Wesley Chun. For the record, I own: Core Python, Second Edition (great) wxPython in Action (haven't used yet) Beginning Python (barely used) Python in a Nutshell (use as a reference, although interactive python dir() is more useful) Dive into Python (great book) Python Cookbook (great book) Python Pocket Reference (not very useful) Python Phrasebook (I love the Phrasebook series, but this isn't a necessary book) -- http://mail.python.org/mailman/listinfo/python-list
Python app to ration cell-phone minutes
I wrote a little something so I could check my current minutes used to see how I was doing for the month. I only get 1,000 minutes, and I have three phones (two other family members share the plan). This way, I can (theoretically) know ahead of time if I'm trending towards going over my plan. By the way, I get free minutes on weekends, so it takes that into consideration. Everything is working fine. I'm just posting it in case anyone finds it interesting or useful, and as always, comments or constructive criticism are welcome. Shawn $ cat cell.py #!/usr/bin/env python """ Shows the number of minutes which can be use by the end of each weekday without going over monthly minute limit. """ import time #Set some constants minuteLimit = 1000 #minutes in cell phone plan oneDay = 60 * 60 * 24 #seconds in one day cycleBegins = 27 #day of month billing cycle begins date = time.time() #Find the date of the first day of the billing cycle. while time.localtime(date)[2] != cycleBegins: date -= oneDay #Initialize the variables, setting them to one if necessary, because we have to start the loop below at the cycleBegins + 1 to avoid hitting the test immediately. daysInCycle = 1 weekdaysInCycle = 0 if time.localtime(date)[6] < 5: weekdaysInCycle += 1 #Find total days and total weekdays in billing month (for proper reporting of free weekend minutes) testDate = date + oneDay while time.localtime(testDate)[2] != cycleBegins: if time.localtime(testDate)[6] < 5: weekdaysInCycle += 1 testDate += oneDay daysInCycle += 1 #Print number of days in cycle and the report. print "%d total days and %d weekdays in the cycle." % (daysInCycle, weekdaysInCycle) weekdaysElapsed = 0 for daysElapsed in range(daysInCycle + 1)[1:]: if time.localtime(date)[6] < 5: weekdaysElapsed += 1 print "%d/%d: %d" % (time.localtime(date)[1], time.localtime(date)[2], (minuteLimit/weekdaysInCycle) * weekdaysElapsed ) else: print "%d/%d: weekend" % (time.localtime(date)[1], time.localtime(date)[2]) date += oneDay -- http://mail.python.org/mailman/listinfo/python-list
Re: "Variable variable name" or "variable lvalue"
On 8/15/07, mfglinux <[EMAIL PROTECTED]> wrote: > Hello to everybody > > I would like to know how to declare in python a "variable name" that > it is in turn a variable > In bash shell I would wrote sthg like: > > for x in `seq 1 3` > do > M$i=Material(x) #Material is a python class > done > > Why I need this? Cause I have a python module that obliges me to build > a variable called Period, which should have a variable name of > summands (depends on the value of x) > > #Let's say x=3, then Period definition is > Period=Slab(Material1(12.5)+Material2(25)+Material3(12.5)) #Slab is a > python class > > I dont know how to automatize last piece of code for any x > > thank you > > Marcos > > -- > http://mail.python.org/mailman/listinfo/python-list > You could use a dictionary -- just build the dictionary keys using your loop and assign values. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Book Recommendations
I should add that "Dive Into Python" is also available for free online: http://www.diveintopython.org/ It's a great book. It is not a linear book -- it doesn't start you off talking about variable types and structure. It starts you right off with a piece of working code. If you already have some programming experience, it's actually a refreshing change from all the others which basically waste 50 - 100 pages on stuff you already know. -- http://mail.python.org/mailman/listinfo/python-list
Re: A problem with Time
import time oneDay = 60 * 60 * 24 #seconds in one day date = time.time() yesterday = date - oneDay -- http://mail.python.org/mailman/listinfo/python-list
Making a copy (not reference) of a file handle, or starting stdin over at line 0
I wrote a script which will convert a tab-delimited file to a
fixed-width file, or a fixed-width file into a tab-delimited. It reads
a config file which defines the field lengths, and uses it to convert
either way.
Here's an example of the config file:
1:6,7:1,8:9,17:15,32:10
This converts a fixed-width file to a tab-delimited where the first
field is the first six characters of the file, the second is the
seventh, etc. Conversely, it converts a tab-delimited file to a file
where the first six characters are the first tab field, right-padded
with spaces, and so on.
What I want to do is look at the file and decide whether to run the
function to convert the file to tab or FW. Here is what works
(mostly):
x = inputFile.readline().split("\t")
inputFile.seek(0)
if len(x) > 1:
toFW(inputFile)
else:
toTab(inputFile)
The problem is that my file accepts the input file via stdin (pipe) or
as an argument to the script. If I send the filename as an argument,
everything works perfectly.
If I pipe the input file into the script, it is unable to seek() it. I
tried making a copy of inputFile and doing a readline() from it, but
being a reference, it makes no difference.
How can I check a line (or two) from my input file (or stdin stream)
and still be able to process all the records with my function?
Thanks,
Shawn
--
http://mail.python.org/mailman/listinfo/python-list
Re: question
You need to post some kind of code (even non-working) to show that you've actually done some work. Nobody will do your work for you. -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbee Question
#!/usr/bin/env python normalPay = 0.4 overPay = 1.4 normalLimit = 22 def calcPay(numStops): pay = 0 if numStops > normalLimit: pay = overPay * (numStops - normalLimit) numStops = normalLimit return pay + (numStops * normalPay) if __name__ == "__main__": print "Pay for 1 stops: %.2f." % calcPay(1) print "Pay for 10 stops: %.2f." % calcPay(10) print "Pay for 17 stops: %.2f." % calcPay(17) print "Pay for 25 stops: %.2f." % calcPay(25) print "Pay for 30 stops: %.2f." % calcPay(30) print "Pay for 31 stops: %.2f." % calcPay(31) -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbee Question
On 8/20/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > On Aug 20, 9:23 am, "HD1956" <[EMAIL PROTECTED]> wrote: > > This is probably a simple code. I am a truck driver who gets paid by > > stops and cases. I am trying to figure out how to code my stop pay. I > > get 40 cents per stop up to 22 stops, and $1.40 per stops after that. > > def calc(num): > if num < 23: > return 0.4 * num > else: > overtime = num - 22 > x = 0.4 * 22 > x += overtime * 1.4 > return x > > # Use your own brain next time > > Mike > > -- > http://mail.python.org/mailman/listinfo/python-list > Mike, I wonder if we were both just duped into helping someone with their homework... Shawn -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbee Question
> I like to write code, so it's not a big deal when it's something so > simple. Still, that is beyond dumb! Nice code, by the way. > > Mike Yeah, it was fun to write anyway. Thanks for the compliment on the code. I still consider myself a Python newbie, so it's good to know I'm not trying to write it like Perl or VBScript anymore. ^_^ Shawn -- http://mail.python.org/mailman/listinfo/python-list
Re: regular expression dictionary search
#!/usr/bin/env python
import re
patterns = { 'sho.' : 6, '.ilk' : 8, '.an.' : 78 }
def returnCode(aWord):
for k in patterns:
p = "^%s$" % k
regex = re.compile(p)
if re.match(regex, aWord):
return patterns[k]
if __name__ == "__main__":
print "The return for 'fred' : %s" % returnCode('fred')
print "The return for 'silk' : %s" % returnCode('silk')
print "The return for 'silky' : %s" % returnCode('silky')
print "The return for 'hand' : %s" % returnCode('hand')
print "The return for 'strand' : %s" % returnCode('strand')
print "The return for 'bank' : %s" % returnCode('bank')
Note: If a word matches more than one pattern, only one will be returned.
I'm not sure if I'm doing the patterns thing properly -- if anyone
could instruct me on whether it would be proper to declare it in the
function, or use a global declaration, please let me know. However, it
runs properly as far as I tested it.
Shawn
--
http://mail.python.org/mailman/listinfo/python-list
Re: question
> And Shawn, I didn't post any of my work because the network I work on > isn't > connected to the internet. So it didn't seem constructive to re-type > all of my > failed code just to satisfy your "standards" of proving that I've been > trying to > hack this myself for the past few days. All in all, thanks for your, > u, > constructive comments. > > -- > http://mail.python.org/mailman/listinfo/python-list > Your original post said clearly that you didn't post your code because it didn't work. That's a completely different reason/excuse than "no Internet connection so I didn't want to re-type it." So either you're lying or lazy, and in either case I don't appreciate your snarky comments about my "uhhh constructive" comments. Don't get me wrong -- I'm not saying you're definitely being dishonest, but you have to admit that the appearance you gave is questionable, and questionable behavior on lists like this gets questioned. Just so this isn't interpreted badly and doesn't start a flame-war, I will just give up and say that if there was a misunderstanding it was on my end, and I apologize. I just wanted to respond to your passive-aggressive attack, since I'm a friendly, helpful person and don't want to be unfairly labled as "uhhh constructive." -- http://mail.python.org/mailman/listinfo/python-list
Re: regular expression dictionary search
On 8/20/07, Paul McGuire <[EMAIL PROTECTED]> wrote:
> On Aug 20, 10:35 am, "Shawn Milochik" <[EMAIL PROTECTED]> wrote:
> > #!/usr/bin/env python
>
> > if __name__ == "__main__":
> >
> > print "The return for 'fred' : %s" % returnCode('fred')
> > print "The return for 'silk' : %s" % returnCode('silk')
> > print "The return for 'silky' : %s" % returnCode('silky')
> > print "The return for 'hand' : %s" % returnCode('hand')
> > print "The return for 'strand' : %s" % returnCode('strand')
> > print "The return for 'bank' : %s" % returnCode('bank')
> >
>
> Shawn -
>
> All that copy/pasting has got to have carpal tunnel written all over
> it - DRY!
>
> tests = "fred silk silky hand strand bank".split()
> for test in tests:
> print "The return for '%s' : %s" % (test, returnCode(test))
>
> -- Paul
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
You're right. Thanks for the correction. My wrists are shot as it is,
and it's easy enough in vim to copy & paste. You know how it is -- I
made one test line, then copied it to a second, then copied it to a
third... Guilty of not planning ahead. ;o)
--
http://mail.python.org/mailman/listinfo/python-list
Re: I Need help from all the group participants
On 8/20/07, Boris Ozegovic <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: > > > The only sentence that comes to mind is: > > > > "I hope I never find myself in a hospital that uses your system." > > You are not funny. The system isn't for hospitals, it is for university > purposes. > > -- > Ne dajte da nas lažljivac Bandić truje: > http://cnn.blog.hr/arhiva-2007-06.html#1622776372 > -- > http://mail.python.org/mailman/listinfo/python-list > I disagree. He is funny. Sorry you can't appreciate the humor -- it must be the language barrier. Lighten up and enjoy this life -- it's the only one we have. -- http://mail.python.org/mailman/listinfo/python-list
Re: reading a line in file
Write some code, even if it doesn't quite work, and post it. We'll
help you fix it.
You can open a file with: input = open("file.txt", "r")
You can read a line with: someText = input.readline()
You can loop through an open file like this:
for line in input:
#do something with line
That should get you started.
--
http://mail.python.org/mailman/listinfo/python-list
Re: reading a line in file
Hopefully this will help (using your input file) #!/usr/bin/env python import re buildinfo = "input.txt" input = open(buildinfo, 'r') regex = re.compile(r"^\s*build.number=(\d+)\s*$") for line in input: if re.search(regex, line): print line buildNum = re.sub(r"^\s*build.number=(\d+)\s*$", "\\1", line) print line print buildNum -- http://mail.python.org/mailman/listinfo/python-list
Re: reading a line in file
Everybody hates regexes. Except me. Discrimination! -- http://mail.python.org/mailman/listinfo/python-list
Re: reading a line in file
Although you're technically correct, I think there's a knee-jerk anti-regex reaction, citing the meaningless overhead. If you're running many thousands of records or something then it becomes a small issue compared to a replace statement or something. But in most cases it makes no difference at all. Run the example script both ways and I'm sure there will be no difference, and I prefer a clear regex to a convoluted (in my opinion) substring call. In any case, it's a preference, and I have never seen anything which convinced me that one should avoid regexes at all costs unless there's no other way to do it. And the comment about solving a problem by using regular expressions creating another problem is just asinine. Like so many other things, it's often repeated without any thought about whether it is true in general, much less in the situation in question. -- http://mail.python.org/mailman/listinfo/python-list
Re: I Need help from all the group participants
"Please enter John's heart rate." "Please notify me immediately if John's heart rate drops below 60 or exceeds 100." -- http://mail.python.org/mailman/listinfo/python-list
Re: Asking all python programmers.
On 8/27/07, Lamonte Harris <[EMAIL PROTECTED]> wrote: > Okay, I know you've guys told me millions of times to read the manual I've > read a lot of it. What do you recommend studying the most? Python is my > goal for the next year in the half. :) > > -- > http://mail.python.org/mailman/listinfo/python-list > Some notes on your question: "You've guys" is nonsensical. Your first sentence is a run-on sentence. Your e-mail address identifies you as an immature script-kiddie. "Year in the half" is nonsensical. Okay, so why am I "picking on you"? Because I want to help. Present yourself in this way, and you're not going to get as much help from intelligent people as you would if they saw you were worth their time. You are either going to get angry at me or you're going to think about this. If you're angry then I can't help you. If you actually care how people see you, you will get further in life in general. To answer the question I think you were trying to ask, a combination of "The Python Cookbook" and "Dive Into Python" should get you started in doing amazing things with Python. The latter is available for free online. Take some pride in the way you write. It will pay off. Shawn -- http://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] Code reading for learning Python
I second the Python Cookbook recommendation. -- http://mail.python.org/mailman/listinfo/python-list
PythonAlley.com
I bought the domain PythonAlley.com (and PerlAlley.com and RubyAlley.com) not too long ago. I had the inspiration to make some kind of community site thing, but never did get around to it. Does anyone have any ideas as to what a wonderful use for PythonAlley.com would be? I'd really like to do something with at least the Python site, since I love Python. Not too sure about the others -- maybe I'm make them wikis and open them up to the community. Maybe I should just sell them. Ideas? Thanks, Shawn -- http://mail.python.org/mailman/listinfo/python-list
Re: PythonAlley.com
On 9/5/07, O.R.Senthil Kumaran <[EMAIL PROTECTED]> wrote: > * Shawn Milochik <[EMAIL PROTECTED]> [2007-09-05 10:27:08]: > > I bought the domain PythonAlley.com (and PerlAlley.com and > > > > Does anyone have any ideas as to what a wonderful use for > > PythonAlley.com would be? I'd really like to do something with at > > If "you" don't have an idea, most likely others wont have as well. :) > > -- > O.R.Senthil Kumaran > http://uthcode.sarovar.org > Faulty logic. Otherwise, you would have to agree that you don't know what you want for lunch if I don't know. -- http://mail.python.org/mailman/listinfo/python-list
Re: REGULAR EXPRESSION
> Hi.. Thanks alot for finding time to help a beginner like me. What I > am trying to do is validate the input i get. I just want to take > numbers and numbers only. So if the input is 23+1 or 2/3 or 9-0 or > 7/0 , I want to find it using reg exp. I know there are other ways to > do this... but i thought i will try this as i need to learn reg exp. I > tried \D+ , \W+, and \D+|\W+ .. Thanks once again... > > > -- Send a couple of strings and the output you would like from each. -- http://mail.python.org/mailman/listinfo/python-list
Re: Text processing and file creation
On 9/5/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > I have a text source file of about 20.000 lines. > >From this file, I like to write the first 5 lines to a new file. Close > that file, grab the next 5 lines write these to a new file... grabbing > 5 lines and creating new files until processing of all 20.000 lines is > done. > Is there an efficient way to do this in Python? > In advance, thanks for your help. > I have written a working test of this. Here's the basic setup: open the input file function newFileName: generate a filename (starting with 1.tmp). If filename exists, increment and test again (0002.tmp and so on). return fileName read a line until input file is empty: test to see whether I have written five lines. If so, get a new file name, close file, and open new file write line to file close output file final time Once you get some code running, feel free to post it and we'll help. -- http://mail.python.org/mailman/listinfo/python-list
Re: Text processing and file creation
Here's my solution, for what it's worth:
#!/usr/bin/env python
import os
input = open("test.txt", "r")
counter = 0
fileNum = 0
fileName = ""
def newFileName():
global fileNum, fileName
while os.path.exists(fileName) or fileName == "":
fileNum += 1
x = "%0.5d" % fileNum
fileName = "%s.tmp" % x
return fileName
for line in input:
if (fileName == "") or (counter == 5):
if fileName:
output.close()
fileName = newFileName()
counter = 0
output = open(fileName, "w")
output.write(line)
counter += 1
output.close()
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python and Cron
Could you send the output of "crontab -l" and the script you're running? It's probably an environment issue of some kind, but it's hard to say what blindly. -- http://mail.python.org/mailman/listinfo/python-list
Re: why should I learn python
I wholeheartedly second the recommendation of this article: http://www.linuxjournal.com/article/3882 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and Cron
Any chance your import statements aren't coming in properly due to something in your environment in Python that's not being inherited by your cron job? -- http://mail.python.org/mailman/listinfo/python-list
Difference between two times (working ugly code, needs polish)
I have done what I wanted, but I think there must be a much better way.
Given two timestamps in the following format, I just want to figure
out how far apart they are (in days, seconds, whatever).
Format:
-MM-DD_MM:SS
Example:
2007-09-11_16:41
It seems to me that to do what I want, I need to convert a string into
a number (time.mktime()), such as this: 1189543487.0
Once I have that, I can just subtract one from the other and do
whatever I want. The ugly part is converting something like
2007-09-11_16:41 to the numeric equivalent.
Below is my code. Any suggestions?
Thanks in advance.
Here is what I have (works):
#runTimeStamp is the current time, set when the script begins execution
def recAge(lastUpdate, runTimeStamp):
import re
oneDay = 60 * 60 * 24
lastUpdate = re.sub(r'\D+', ',', lastUpdate)
lastUpdate = lastUpdate + ",0,0,0,0"
lastUpdate = [int(x) for x in lastUpdate.split(',')]
lastUpdate = time.mktime(tuple(lastUpdate))
runTimeStamp = re.sub(r'\D+', ',', runTimeStamp)
runTimeStamp = runTimeStamp + ",0,0,0,0"
runTimeStamp = [int(x) for x in runTimeStamp.split(',')]
runTimeStamp = time.mktime(tuple(runTimeStamp))
return (runTimeStamp - lastUpdate) / oneDay
--
http://mail.python.org/mailman/listinfo/python-list
Re: Difference between two times (working ugly code, needs polish)
On 9/11/07, Grant Edwards <[EMAIL PROTECTED]> wrote: > On 2007-09-11, Shawn Milochik <[EMAIL PROTECTED]> wrote: > > > I have done what I wanted, but I think there must be a much better way. > > See the strptime() function in either the time or the datetime > modules: > > http://docs.python.org/lib/module-time.html > http://docs.python.org/lib/module-datetime.html > Grant: Thanks, this works, and is much shorter. Any further improvements, anyone? def isOld(lastUpdate, runTimeStamp): oneDay = 60 * 60 * 24 lastUpdate = time.mktime(time.strptime(lastUpdate, "%Y-%m-%d_%H:%M")) runTimeStamp = time.mktime(time.strptime(runTimeStamp, "%Y-%m-%d_%H:%M")) return (runTimeStamp - lastUpdate) / oneDay -- http://mail.python.org/mailman/listinfo/python-list
Re: Difference between two times (working ugly code, needs polish)
> > I suppose really oneDay should be a global (i.e. outside the function > definition). Apart from that it would be hard to improve on: obvious, > easy to read, in short - pythonic. > > Are you concerned about daylight savings? That could certainly introduce > a whole new level of complexity into the problem. Let's hope not ... I'm not concerned with DST; this is a script which checks my Ebay auctions (I have some things for sale), and sends me e-mail whenever someone bids. It's run by cron every half hour -- it keeps me from compulsively checking my auctions. ^_^ In any case, DST isn't an issue because the same machine generates both timestamps, and all I use it for is to stop displaying auctions after they are 10 days old, so I don't get all my old crap filling up the alert e-mail or skewing the total dollar amount for all active auctions. Thanks. Shawn -- http://mail.python.org/mailman/listinfo/python-list
Re: Difference between two times (working ugly code, needs polish)
> Just to be picky - your function returns the number of days between > two dates, but it's called isOld, which looks like it should return a > boolean. i.e. it looks like it would be used as: > > if not isOld(auctionDate, currentTime): > checkForBid() > > rather than how I assume it is used: > > if isOld(auctionDate, currentTime) <= 10: > checkForBid() > > I'd call it daysDiff or something similar, or make it more specific so > that it works like the first block of code above: You're absolutely right; I started writing it with one purpose in mind and changed it midstream. I actually renamed it yesterday to dayDiff. ;o) Shawn -- http://mail.python.org/mailman/listinfo/python-list
Perl and Python, a practical side-by-side example.
I'm new to Python and fairly experienced in Perl, although that
experience is limited to the things I use daily.
I wrote the same script in both Perl and Python, and the output is
identical. The run speed is similar (very fast) and the line count is
similar.
Now that they're both working, I was looking at the code and wondering
what Perl-specific and Python-specific improvements to the code would
look like, as judged by others more knowledgeable in the individual
languages.
I am not looking for the smallest number of lines, or anything else
that would make the code more difficult to read in six months. Just
any instances where I'm doing something inefficiently or in a "bad"
way.
I'm attaching both the Perl and Python versions, and I'm open to
comments on either. The script reads a file from standard input and
finds the best record for each unique ID (piid). The best is defined
as follows: The newest expiration date (field 5) for the record with
the state (field 1) which matches the desired state (field 6). If
there is no record matching the desired state, then just take the
newest expiration date.
Thanks for taking the time to look at these.
Shawn
##
Perl code:
##
#! /usr/bin/env perl
use warnings;
use strict;
my $piid;
my $row;
my %input;
my $best;
my $curr;
foreach $row (<>){
chomp($row);
$piid = (split(/\t/, $row))[0];
push ( @{$input{$piid}}, $row );
}
for $piid (keys(%input)){
$best = "";
for $curr (@{$input{$piid}}){
if ($best eq ""){
$best = $curr;
}else{
#If the current record is the correct state
if ((split(/\t/, $curr))[1] eq (split(/\t/, $curr))[6]){
#If existing record is the correct state
if ((split(/\t/, $best))[1] eq (split(/\t/,
$curr))[6]){
if ((split(/\t/, $curr))[5] gt
(split(/\t/, $best))[5]){
$best = $curr;
}
}else{
$best = $curr;
}
}else{
#if the existing record does not have the
correct state
#and the new one has a newer expiration date
if (((split(/\t/, $best))[1] ne (split(/\t/,
$curr))[6]) and
((split(/\t/, $curr))[5] gt (split(/\t/, $best))[5])){
$best = $curr;
}
}
}
}
print "$best\n";
}
##
End Perl code
##
##
Python code
##
#! /usr/bin/env python
import sys
input = sys.stdin
recs = {}
for row in input:
row = row.rstrip('\n')
piid = row.split('\t')[0]
if recs.has_key(piid) is False:
recs[piid] = []
recs[piid].append(row)
for piid in recs.keys():
best = ""
for current in recs[piid]:
if best == "":
best = current;
else:
#If the current record is the correct state
if current.split("\t")[1] == current.split("\t")[6]:
#If the existing record is the correct state
if best.split("\t")[1] == best.split("\t")[6]:
#If the new record has a newer exp. date
if current.split("\t")[5] >
best.split("\t")[5]:
best = current
else:
best = current
else:
#If the existing record does not have the
correct state
#and the new record has a newer exp. date
if best.split("\t")[1] != best.split("\t")[6]
and
current.split("\t")[5] > best.split("\t")[5]:
best = current
print best
##
End Python code
##
--
http://mail.python.org/mailman/listinfo/python-list
Boost Python properties/getter functions for strings
Hi, I'm trying to expose a C++ class' internals to python via
boost::python. I can do integer/boolean functions fine, but as soon
as I do a string get/set it craps out.
boost::python::class_ >("Entity")
//publics
.def("isActive", &Entity::isActive) //bool
.def("activate", &Entity::activate) //bool
.def("deactivate", &Entity::deactivate) //bool
//...
.add_property("name", &Entity::getName) //compile error
(1)
.def("getName", &Entity::getName,
boost::python::return_internal_reference<>());
//runtime error(2)
Compile error (1) shows this: C:/MinGW/include/boost/python/detail/
invoke.hpp: In function `PyObject*
boost::python::detail::invoke(boost::python::detail::invoke_tag_<
false, true>, const RC&, F&, TC&) [with RC =
boost::python::detail::specify_a_return_value_policy_to_wrap_functions_returning, F = const std::string&(rsblsb::Entity::*)() const, TC =
boost::python::arg_from_python]':
C:/MinGW/include/boost/python/detail/caller.hpp:199: instantiated
from `PyObject* boost::python::detail::caller_arity<1u>::impl::operator()(PyObject*, PyObject*) [with F = const
std::string&(rsblsb::Entity::*)() const, Policies =
boost::python::default_call_policies, Sig = boost::mpl::vector2]'
C:/MinGW/include/boost/python/object/py_function.hpp:38:
instantiated from `PyObject*
boost::python::objects::caller_py_function_impl::operator()
(PyObject*, PyObject*) [with Caller =
boost::python::detail::caller >]'
C:\Game\svn\Platform\Framework\Python\PyModuleSetup.cc:58:
instantiated from here
C:/MinGW/include/boost/python/detail/invoke.hpp:88: error: no match
for call to `(const
boost::python::detail::specify_a_return_value_policy_to_wrap_functions_returning) (const std::basic_string,
std::allocator >&)'
Runtime error 2 just crashes whenever I try:
import modulename
I = modulename.Entity()
I.getName()
Anyone have any idea what I can try? thanks a lot!
-Shawn.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Boost Python properties/getter functions for strings
I forgot to mention, getname is defined as: const std::string &Entity::getName() const; -- http://mail.python.org/mailman/listinfo/python-list
Re: Boost Python properties/getter functions for strings
On Mar 19, 12:00 pm, "Shawn McGrath" <[EMAIL PROTECTED]> wrote: > I forgot to mention, getname is defined as: > const std::string &Entity::getName() const; After more reading I found the copy_const_reference, and replaced: boost::python::return_internal_reference<>()); with: boost::python::return_value_policy()); and it fixed my problem. Is there any downside to using copy_const_reference over return_internal_reference? Thanks, Shawn. -- http://mail.python.org/mailman/listinfo/python-list
Re: Boost Python properties/getter functions for strings
On Mar 19, 12:49 pm, "Jon Clements" <[EMAIL PROTECTED]> wrote: > On 19 Mar, 16:40, "Shawn McGrath" <[EMAIL PROTECTED]> wrote: > > > On Mar 19, 12:00 pm, "Shawn McGrath" <[EMAIL PROTECTED]> wrote: > > > > I forgot to mention, getname is defined as: > > > const std::string &Entity::getName() const; > > > After more reading I found the copy_const_reference, and replaced: > > boost::python::return_internal_reference<>()); > > with: > > > boost::python::return_value_policy()); > > > and it fixed my problem. Is there any downside to using > > copy_const_reference over return_internal_reference? > > You might get some answers here; if not, can I > suggesthttp://mail.python.org/mailman/listinfo/c++-sig? I think a lot of the > Boost.Python developers hang around on that list. > > hth, > > Jon. Cool thanks a lot. The problem is actually due to python's strings being immutable (I knew this, but I thought returning const std::string& would do it). return_internal_reference<> works for other pointers/references, just not strings. (I just answered it so if it gets searched later on people will find the solution) -Shawn. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Start
On 9/14/07, James Stroud <[EMAIL PROTECTED]> wrote: > > Here's your recipe: > >1. begin coding until you hit a wall >2. read official tutorial until you figure out a solution >3. experiment in interactive interpreter >4. goto 1. > > I know this sounds obvious, but its the best way to jumpstart. > > James > -- What a beautiful way of putting it! That's what I do all the time, although sometimes my bookshelf or Google is a stand-in for #2. I try not to post to the list before I have working code. You know, if you could make that process into a haiku, you could just make that your sig and answer nearly every question that hits this list. ^_^ I wonder whether lists like this hurt more people than they help, because it's too easy to ask for help too soon. Those of you who consistently give the best advice didn't learn by asking for help every step along the way, did you? Is it really teaching a man to fish if you bait his line and tell him where to cast? Shawn -- http://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] Just bought Python in a Nutshell
My best advice: Skim it -- just flip the pages, glancing at each one without really reading it -- maybe just read the bold type. You'll find that very rewarding when you run into a problem in your coding and remember that you saw *something* which could be related. You will probably notice some built-in functions that you will need and possibly would have re-invented if you didn't know they were there. I don't really find it to be a "reading" book -- it's more of a reference book. Flip through it, then keep it within reach of your keyboard. Shawn -- http://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] list iteration question for writing to a file on disk
When you use "print," it automatically adds a newline (\n). You can avoid this by following the print line with a comma: print j, Or rstrip() the line before printing. Either way. -- http://mail.python.org/mailman/listinfo/python-list
string questions
Hi everyone, I'm a beginning programming student in Python and have a few questions regarding strings. If s1 = "spam" If s2 = "ni!" 1. Would string.ljust(string.upper(s2),4) * 3 start it at the left margin and move it 12 spaces to the right because of the 4 *3? If so, why is it in the parathesis for the upper command and not the ljust? I already know that it would cap it to NI! 2. To get the output "Spam Ni! Spam Ni! Spam Ni!" I could do something like this string.join ([s1, s2]), But I'm a little lost how to get it repeated three times on one line. Would I just have to put the same command on the next two lines? 3. To change spam to spm, the string.replace seems to be the best function to use. However, when I use string.replace(s1, "a", " ") in python to replace a with an empty space, it doesn't work...I just get spam back when I print s1. Any ideas? Thanks. -Shawn -- http://mail.python.org/mailman/listinfo/python-list
thanks everyone for your replies!
:) -- http://mail.python.org/mailman/listinfo/python-list
Re: pattern combinations
On 9/17/07, dorje tarap <[EMAIL PROTECTED]> wrote: > Hi all, > > Given some patterns such as "...t...s." I need to make all possible > combinations given a separate list for each position. The length of the > pattern is fixed to 9, so thankfully that reduces a bit of the complexity. > > For example I have the following: > > pos1 = ['a',' t'] > pos2 = ['r', 's'] > pos3 = ['n', 'f'] > > So if the pattern contains a '.' character at position 1 it could be 'a' or > 't'. For the pattern '.s.' (length of 3 as example) all combinations would > be: > > asn > asf > tsn > tsf > > Thanks > -- > http://mail.python.org/mailman/listinfo/python-list > Sounds like homework to me. -- http://mail.python.org/mailman/listinfo/python-list
qa
I'm trying to get a space in between these two strings but it's ignoring the space in between when it prints. >>> string.capwords (string.join([s1 + " " + s2])) * 3 'Spam Ni!Spam Ni!Spam Ni!' >>> -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question
On 9/18/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > On Sep 18, 1:31 pm, "Shawn Milochik" <[EMAIL PROTECTED]> wrote: > > On 9/18/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > > > > > If I have a file name: AVC1030708.14. How do I strip out certain > > > characters from the file name? I am so used to using MID, LEFT, and > > > RIGHT functions, that I have no idea how to do this in python? I have > > > had trouble as well with most newbies on finding the help. But I have > > > used the command line built in help, but with no luck. Thanks. > > > > > Kou > > > > Do you want to strip out specific characters, characters in specific > > positions, or characters matching certain patterns? > > Yes, I want specific characters in specific positions. > Try this: newString = oldString[0:3] + oldString[5:10] Some other quick examples: >>> test = "this is a test" >>> test 'this is a test' >>> fred = test[:3] + test[9:] >>> fred 'thi test' >>> test[0:5] 'this ' >>> test[:5] 'this ' >>> test[4:] ' is a test' -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question
On 9/18/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > If I have a file name: AVC1030708.14. How do I strip out certain > characters from the file name? I am so used to using MID, LEFT, and > RIGHT functions, that I have no idea how to do this in python? I have > had trouble as well with most newbies on finding the help. But I have > used the command line built in help, but with no luck. Thanks. > > Kou Do you want to strip out specific characters, characters in specific positions, or characters matching certain patterns? -- http://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] Finding prime numbers
Here's my attempt: #!/usr/bin/env python import math for x in range(3,1000,2): isPrime = True for y in range(3,(math.sqrt(x) + 1)): if x % y == 0: isPrime = False break if isPrime: print "%d is prime." % x Notes: This doesn't bother with even numbers at all, and uses the square root function of "math." Any improvements anyone? -- http://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] Finding prime numbers
Okay, I caught one bug already myself: for y in range(3,(math.sqrt(x) + 1)): should be for y in range(3,(int(math.sqrt(x)) + 1)): -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding prime numbers
> If you'd just search the archives, you would have found this: > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/b134b2235e9c19a6/34857fb0b0b2a4b5?lnk=gst&q=prime+number&rnum=1#34857fb0b0b2a4b5 Yeah, but that's no fun. ;o) -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding prime numbers
On 9/20/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > On Sep 19, 1:31 pm, "Shawn Milochik" <[EMAIL PROTECTED]> wrote: > > > If you'd just search the archives, you would have found this: > > > > >http://groups.google.com/group/comp.lang.python/browse_thread/thread/... > > > > Yeah, but that's no fun. ;o) > > Yes! Never do what you can fool others into doing for you. > > Mike > Maybe for some people, but for me it's more fun to figure it out on my own. By the "no fun" part, I meant that it wouldn't be fun to just find the answer in an old thread instead of writing code to find primes myself. -- http://mail.python.org/mailman/listinfo/python-list
acronym program
I'm trying to write a program that gets the first letter of every word of a phrase and prints it on screen. I'm having problems with it. I'm thinking a for loop would be good since I don't know the exact number of words the user is going to enter, but after that I get confused. How do I tell python to just goto the beg of each word in the phrase and include it in the acronym? Am I on the right track? for a in string.split(phrase) acronym = phrase [0] acronym = acronym + 1 thx -- http://mail.python.org/mailman/listinfo/python-list
Re: acronym program
That was it! Thanks a lot! I was also trying to output the acronym in caps so I was entering string.upper (acronym) like whats in the book and kept getting a "'tuple' object is not callable" error message. Just for the heck of it I tried it acronym.upper() and it worked! I thought it could work both ways? Paul Rudin wrote: > Shawn Minisall <[EMAIL PROTECTED]> writes: > > >> I'm trying to write a program that gets the first letter of every word >> of a phrase and prints it on screen. I'm having problems with it. >> I'm thinking a for loop would be good since I don't know the exact >> number of words the user is going to enter, but after that I get >> confused. How do I tell python to just goto the beg of each word in >> the phrase and include it in the acronym? Am I on the right track? >> >>for a in string.split(phrase) >>acronym = phrase [0] >>acronym = acronym + 1 >> > > > How about: > > for a in phrase.split(): > print a[0] > > > > -- http://mail.python.org/mailman/listinfo/python-list
too many values with string.split
I'm trying to unpack a list of 5 floats from a list read from a file and python is telling me 5 variables are too many for the string.split statement. Anyone have any other idea's? NOTE: the only reason I convert it to a float instead of just leaving it as a string in the loop is because I have to have it printed out as a float besides the names and then the average displayed underneath thx #read in data line by line for line in infile: mylist = string.split(line) firstName[counter] = mylist[0] lastName[counter] = mylist[1] grades[counter] = float(mylist[2]) print firstName[counter], lastName[counter],":","\t\t",grades[counter] #increment counter counter = counter + 1 #calculates and prints average score grades = str(grades) num1, num2, num3, num4, num5 = string.split(grades,",") average = float(num1 + num2 + num3 + num4 + num5) / 5 print print "Average:" -- http://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] Take if offline
Since everyone else is replying to the list, I'll (top) post this: No, not really. He had to give everyone the rule once. Otherwise, he'd have to do it a hundred times a day, and monitor every single post to find out who he had to inform. He'd end up doing not much else with his life, and would flee to a monastery and give up coding forever. You wouldn't want that to happen, would you? On 9/25/07, Michael Langford <[EMAIL PROTECTED]> wrote: > I agree with Kent... > > -- > Michael Langford > Phone: 404-386-0495 > Consulting: http://www.TierOneDesign.com/ > Entertaining: > http://www.ThisIsYourCruiseDirectorSpeaking.com > > > On 9/25/07, Kent Johnson <[EMAIL PROTECTED]> wrote: > > Hansen, Mike wrote: > > > Anytime someone posts in HTML, or posts without a subject, or > > > accidentally > > > hijacks a thread, or top-posts, or writes in caps, a couple of posters > > > pop up > > > and complain. Rather than posting to the entire list, I think it'd be > > > best if > > > you send your complaint directly to the "offending" user. I'd prefer to > > > read > > > about Python not read lessons in net/mail-list etiquette. > > > > Hmmm. So instead, whenever someone complains about netiquette on-list we > > should post on-list complaining about it? I'm not sure that improves the > > situation any, especially if it sparks a discussion. Perhaps you should > > email your suggestion privately to the offending parties. :-) > > > > I definitely think this list is about how to be part of the Python > > community, as well as how to program in Python. Knowing how to > > participate in a mailing list is part of that. Maybe you could just skip > > those posts, there are not that many of them. > > > > Kent > > ___ > > Tutor maillist - [EMAIL PROTECTED] > > http://mail.python.org/mailman/listinfo/tutor > > > > > ___ > Tutor maillist - [EMAIL PROTECTED] > http://mail.python.org/mailman/listinfo/tutor > > -- Please read: http://milocast.com/2007/07/31/this-i-believe/ -- http://mail.python.org/mailman/listinfo/python-list
ValueError: too many values to unpack,>>>
I am trying to read a few lines of a file with multiple values, the rest are single and are reading in fine. With the multiple value lines, python says this "ValueError: too many values to unpack" I've googled it and it says that happens when you have too few or too many strings that don't match with the variables in number your trying to assign them too. Below are the lines in reading in: line 3 - 19.1829.1578.75212.10 line 4 - 10020410.29 And this is the code I'm using: #read withdrawls from file on line3 line = infile.readline() #split withdrawls up withdraw1, withdraw2, withdraw3, withdraw4 = string.split(line, "\t") #read deposits from file on line4 line = infile.readline() #split deposits up deposit1, deposit2, deposit3 = string.split(line, "\t") I have 4 strings to match line 3 and 3 to match the 3 on line 4...any thoughts? thx -- http://mail.python.org/mailman/listinfo/python-list
ValueError: too many values to unpack
I am trying to read a few lines of a file with multiple values, the rest are single and are reading in fine. With the multiple value lines, python says this "ValueError: too many values to unpack" I've googled it and it says that happens when you have too few or too many strings that don't match with the variables in number your trying to assign them too. Below are the lines in reading in: line 3 - 19.1829.1578.75212.10 line 4 - 10020410.29 And this is the code I'm using: #read withdrawls from file on line3 line = infile.readline() #split withdrawls up withdraw1, withdraw2, withdraw3, withdraw4 = string.split(line, "\t") #read deposits from file on line4 line = infile.readline() #split deposits up deposit1, deposit2, deposit3 = string.split(line, "\t") I have 4 strings to match line 3 and 3 to match the 3 on line 4...any thoughts? thx -- http://mail.python.org/mailman/listinfo/python-list
Re: ValueError: too many values to unpack,>>>
Marc 'BlackJack' Rintsch wrote: > On Thu, 27 Sep 2007 12:36:58 -0400, Shawn Minisall wrote: > > >> With the multiple value lines, python says this "ValueError: too many >> values to unpack" >> >> I've googled it and it says that happens when you have too few or too >> many strings that don't match with the variables in number your trying >> to assign them too. Below are the lines in reading in: >> >> line 3 - 19.1829.1578.75212.10 >> line 4 - 10020410.29 >> >> And this is the code I'm using: >> >> #read withdrawls from file on line3 >> line = infile.readline() >> >> #split withdrawls up >> withdraw1, withdraw2, withdraw3, withdraw4 = string.split(line, "\t") >> >> #read deposits from file on line4 >> line = infile.readline() >> #split deposits up >> deposit1, deposit2, deposit3 = string.split(line, "\t") >> >> I have 4 strings to match line 3 and 3 to match the 3 on line 4...any >> thoughts? >> > > First thought is to find out which of the two lines triggers the > exception. This information is part of the full traceback. > > Ciao, > Marc 'BlackJack' Rintsch > Sorry, it looks like it's on the fourth line with the 3 values on line 4...its reading line 3 fine Traceback (most recent call last): File "", line 1, in main() File "I:\COMPUTER PROGRAMMING CLASS\PROJECT #1\project1.py", line 33, in main deposit1, deposit2, deposit3 = string.split(line, "\t") ValueError: too many values to unpack -- http://mail.python.org/mailman/listinfo/python-list
Re: ValueError: too many values to unpack,>>>
Fredrik Lundh wrote: > Shawn Minisall wrote: > > >> Sorry, it looks like it's on the fourth line with the 3 values on line >> 4...its reading line 3 fine >> >> Traceback (most recent call last): >> File "", line 1, in >> main() >> File "I:\COMPUTER PROGRAMMING CLASS\PROJECT #1\project1.py", line 33, >> in main >> deposit1, deposit2, deposit3 = string.split(line, "\t") >> ValueError: too many values to unpack >> > > instead of fumbling around in the dark, try inserting a print statement > before the offending line, so you can see what you're trying to unpack: > > print string.split(line, "\t") # see what it is > deposit1, deposit2, deposit3 = string.split(line, "\t") > > > I did and it printed everything up until the 3rd line with 3 numbers for deposits. I have since figured it out...the teacher put in an extra tab after the last value so python thought it was 4 values for three. I went back into the file and deleted the extra tab after the 3rd number and saved it...now it's working fine. I'm going to kill her... ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: Algebraic Modules For Python
On 10/1/07, Brandon McGinty <[EMAIL PROTECTED]> wrote: > > > Hi All, > I know that there is probably a great deal of literature on this on the net, > but I don't have any time to go searching. -- > Brandon McGinty > McGinty Soft Ltd. > Website design, configuration, and maintenance > Python and PHP coder So let me get this straight: You label yourself as a coder for hire in Python, but you don't have time to search the Internet for an answer to your own Python question? Remind me to avoid McGinty Soft for any and all needs which might require someone useful. -- http://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] data from excel spreadsheet to csv and manipulate
On 10/3/07, sacha rook <[EMAIL PROTECTED]> wrote: > > Hi > > can anyone help with the best way to tackle this? > > I have a spreadsheet ms excel, that has a name column that I want to > extract to csv and manipulate as follows. > > The name column has data in this format > > Name > > Surname Firstname > > after extracting and manipulating I want it to be as follows in three comma > separated fields; > > > Firstname, Surname, Firstname Surname > > So > > Smith John > > becomes > > John, Smith, John Smith > > I hope I have explained myself. > > I want to use python to do all this if sensible, so what is the best > approach? > > Many thanks > > S > > > Do you know a place like the back of your hand? Share local knowledge with > BackOfMyHand.com > ___ > Tutor maillist - [EMAIL PROTECTED] > http://mail.python.org/mailman/listinfo/tutor > > Here's the best approach: 1. Browse: http://python.org/doc/ 2. Search Google. 3. Write code. 4. Post code to the group and ask for help with the pieces that aren't working as you expect. Have fun! Shawn -- http://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] matching a street address with regular expressions
On 10/4/07, Ricardo Aráoz <[EMAIL PROTECTED]> wrote:
> Christopher Spears wrote:
> > One of the exercises in Core Python Programming is to
> > create a regular expression that will match a street
> > address. Here is one of my attempts.
> >
> street = "1180 Bordeaux Drive"
> patt = "\d+ \w+"
> import re
> m = re.match(patt, street)
> if m is not None: m.group()
> > ...
> > '1180 Bordeaux'
> >
> > Obviously, I can just create a pattern "\d+ \w+ \w+".
> > However, the pattern would be useless if I had a
> > street name like 3120 De la Cruz Boulevard. Any
> > hints?
> >
>
Also, that pattern can be easily modified to have any number of words
at the end:
patt = "\d+ (\w+){1,}"
This would take care of 3120 De la Cruz Boulevard.
--
http://mail.python.org/mailman/listinfo/python-list
if then elif
I just learned about if, then elif statements and wrote this program.
The problem is, it's displaying all of the possibilities even after you
enter a 0, or if the fat grams are more then the total number of
calories , that is supposed to stop the program instead of continuing on
with the print statements that don't apply. Any idea's? thanks
#Prompt for calories
cal = input("Please enter the number of calories in your food: ")
#Prompt for fat
fat = input("Please enter the number of fat grams in your food: ")
#Input validation
if cal or fat <= 0:
#Display message
print "Error. The number of calories and/or fat grams must be
positive"
print
else:
#Calculate calories from fat
calfat = float(fat) * 9
#Calculate number of calories from fat
caldel = calfat / cal
#change calcent decimal to percentage
calcent = caldel * 100
if calfat > cal:
print "The calories or fat grams were incorrectly entered."
else:
#evaluate input
if caldel <= .3:
print "Your food is low in fat."
elif caldel >= .3:
print "Your food is high in fat."
#Display percentage of calories from fat
print "The percentage of calories from fat in your food is %",
calcent
Here's an example of the output...
Please enter the number of calories in your food: 50
Please enter the number of fat grams in your food: 30
Error. The number of calories and/or fat grams must be positive
Your food is low in fat.
The percentage of calories from fat in your food is % 0.0
It was supposed to print The calories or fat grams were incorrectly
entered since the calories from fat was greater then the total number of
calories.
--
http://mail.python.org/mailman/listinfo/python-list
while statements
I just learned about while statements and get why you place them around
inputs for validation, but I'm a little lost on exactly where to place
it with what condition in this program where the number of fat grams
exceeds the total number of calories so that it loops back and asks you
the two questions again instead of just saying The calories or fat grams
were incorrectly entered. Any idea's?
thx
while cal <=0:
#Prompt for calories
cal = input("Please enter the number of calories in your food: ")
if cal <=0:
print "Error. The number of calories must be positive."
#Prompt for fat
fat = input("Please enter the number of fat grams in your food: ")
if fat <=0:
print "Error. The number of fat grams must be positive."
#Calculate calories from fat
calfat = float(fat) * 9
#Calculate number of calories from fat
caldel = calfat / cal
#change calcent decimal to percentage
calcent = caldel * 100
#evaluate input
if calfat > cal:
print "The calories or fat grams were incorrectly entered."
elif calcent > 0 and calfat < cal:
if caldel <= .3:
print "Your food is low in fat."
elif caldel >= .3:
print "Your food is high in fat."
#Display percentage of calories from fat
print "The percentage of calories from fat in your food is %",
calcent
--
http://mail.python.org/mailman/listinfo/python-list
for loop
#Intro
print "*"
print "WELCOME TO THE POPULATION GROWTH CALCULATOR"
print "*"
print "This program will predict the size of a population of organisms."
print
print
organisms=input("Please enter the starting number of organisms: ")
increase=input("Please enter the average daily population increase
as a percentage (20% = .20): ")
days=input("Please enter the number of days that they will multiply: ")
print " DayPopulation"
print "--"
for p in range (days):
population = organisms * population * increase
print days,
print "\t\t\t\t",population
I'm having problems with my for loop here to calculate estimated
population output to a table. Instead of knowing how much I want to
loop it, the loop index is going to be whatever number of days the user
enters. When I run my program, it asks the 3 questions above but then
just dead stops at a prompt which leads me to believe there's something
wrong with my loop. I have the exact same setup in another program, but
the loop index has a specific value. I tried (0,days), (1,days) ect.
and I don't think for loops need accumulators, I've tried it with one
anyways and it still stops.
Any idea's?
thx
--
http://mail.python.org/mailman/listinfo/python-list
Re: for loop
Thanks, everyone! Using everyone's suggestions and points, the program
is working great now. Here's the updated code.
:)
import math
def main():
#Declare and initialize variables
#starting number of organisms
organisms = 0
#average daily population increase as %
increase = 0.0
#number of days they will multiply
days = 0
#population prediction
population = 0.0
#Intro
print "*"
print "WELCOME TO THE POPULATION GROWTH CALCULATOR"
print "*"
print "This program will predict the size of a population of organisms."
print
print
while organisms <=1:
organisms=input("Please enter the starting number of organisms: ")
if organisms <=1:
print "Error. Population must be at least two."
while increase <=0:
increase=input("Please enter the average daily population
increase as a percentage (20% = .20): ")
if increase <=0:
print "The percent of increase must be positive."
while days <=0:
days=input("Please enter the number of days that they will
multiply: ")
if days <=0:
print "The number of days must be positive."
print " DayPopulation"
print "--"
population = organisms
for p in range (1,days+1):
if( p > 1 ):
population = population + ( population * increase )
print "\t",p,
[EMAIL PROTECTED] wrote:
> On Oct 22, 5:37 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
>
>> On Oct 22, 5:22 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
>>
>>
>>
>>
>>
>>
>>> On Mon, 22 Oct 2007 18:17:56 -0400, Shawn Minisall wrote:
>>>
>>>> #Intro
>>>> print "*"
>>>> print "WELCOME TO THE POPULATION GROWTH CALCULATOR"
>>>> print "*"
>>>>
>>>> print "This program will predict the size of a population of
>>>> organisms."
>>>> print
>>>> print
>>>> organisms=input("Please enter the starting number of organisms: ")
>>>>
>>>> increase=input("Please enter the average daily population increase
>>>> as a percentage (20% = .20): ")
>>>>
>>>> days=input("Please enter the number of days that they will multiply: ")
>>>>
>>>> print " DayPopulation"
>>>> print "--"
>>>>
>>>> for p in range (days):
>>>>
>>>> population = organisms * population * increase
>>>>
>>>> print days,
>>>>
>>>> print "\t\t\t\t",population
>>>>
>>>> I'm having problems with my for loop here to calculate estimated
>>>> population output to a table. Instead of knowing how much I want to
>>>> loop it, the loop index is going to be whatever number of days the user
>>>> enters. When I run my program, it asks the 3 questions above but then
>>>> just dead stops at a prompt which leads me to believe there's something
>>>> wrong with my loop.
>>>>
>>> It should not run at all as it is indented inconsistently. If that
>>> problem is corrected it will stop with a `NameError` because you try to
>>> read `population` before anything was assigned to it.
>>>
>>> Ciao,
>>> Marc 'BlackJack' Rintsch
>>>
>> Also, I would guess that you want to print p, not days
>>
>
> Oh, and your calculation is incorrect. You don't multiply by
> organisms in every loop iteration, organisms is the initial
> value of population, so you can solve the "Name" error by doing
> population = organisms before the for..loop.
>
> And since you're asking for an increase, you don't multiply by the
> percent (as that would decrease the population), but instead by
> 1+increase.
>
> Also, does day==0 represent the first day of increase or t
Re: Regular Expression
On 10/22/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I'm trying to learn regular expressions, but I am having trouble with
> this. I want to search a document that has mixed data; however, the
> last line of every entry has something like C5H4N4O3 or CH5N3.ClH.
> All of the letters are upper case and there will always be numbers and
> possibly one .
>
> However below only gave me none.
>
> import os, codecs, re
>
> text = 'C:\\text_samples\\sample.txt'
> text = codecs.open(text,'r','utf-8')
>
> test = re.compile('\u+\d+\.')
>
> for line in text:
> print test.search(line)
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
I need a little more info. How can you know whether you're matching
the text you're going for, and not other data which looks similar? Do
you have a specific field length? Is it guaranteed to contain a digit?
Is it required to start with a letter? Does it always start with 'C'?
You need to have those kinds of rules in mind to write your regex.
Shawn
--
http://mail.python.org/mailman/listinfo/python-list
greatest and least of these...
I just wrote a program to let the user input a series of whole numbers
and tell them which is least and which is greatest based off of a menu.
However, the menu isn't kicking in after they pick a number. I included
a while statement for a loop just for the menu and compared it to my
other programs that have a similar setup and are working, but I'm
stumped. Here's the program...
def main():
#define and initialize variables
#choice as int
choice = 0
#number as int
number = 0
#intro
print "WELCOME TO THE GREATEST AND LEAST NUMBER PROGRAM!"
print
#Menu loop
while choice != 2:
#display menu
print "Please choose from the following menu: "
print "1. Enter a number"
print "2. Exit"
print
#prompt user for their menu choice
choice = input("Enter your choice here: ")
#if statements to determine which choice
if choice == 1:
nums = []
while number >=0:
nums.append(number)
number = input("Please enter a number.")
elif choice == 2:
print "Have a great day!"
if len(nums) > 0:
print "The smallest number that you entered was:",min(nums)
print "The largest number that you entered was:",max(nums)
else:
#invalid
print "Invalid selection. Enter either one or two."
print
Also, if they quit the program with choice #2 and entered numbers, it
should display the greatest and least of them. If they just started and
didn't enter anything and want to quit, I get an error message saying
UnboundLocalError: local variable 'nums' referenced before assignment.
Isn't the if statement supposed to keep python from going there since if
they didn't enter any input, the length of the list should just be zero.
--
http://mail.python.org/mailman/listinfo/python-list
Re: for loop
I agree, but if I want to get a A on the program, thats how my professor
wants the output.
:)
[EMAIL PROTECTED] wrote:
> On Oct 22, 9:12?pm, Shawn Minisall <[EMAIL PROTECTED]> wrote:
>
>> Thanks, everyone! Using everyone's suggestions and points, the program
>> is working great now.
>>
>
> Actually, it's not. I assume not printing the population
> was a copy error.
>
> But, by adding the "if (p>1):", you have now made
> day 1 the initial population, so if you ask for
> 8 days of multiplication, you actually only get 7.
>
> Although your code is working, it's not giving you
> the correct answer. Most of the time in these kinds
> of problems, days means elapsed days. That means for
> 100 organisms @ 25% growth/day, there will be 125
> after 1 elapsed day. But that "if (p>1):" means you
> show 100 at day 1, which is wrong. You have 100 after
> 0 elapsed days (or day 0).
>
>
>
>> Here's the updated code.
>>
>> :)
>>
>> import math
>>
>> def main():
>> #Declare and initialize variables
>> #starting number of organisms
>> organisms = 0
>> #average daily population increase as %
>> increase = 0.0
>> #number of days they will multiply
>> days = 0
>> #population prediction
>> population = 0.0
>>
>> #Intro
>> print "*"
>> print "WELCOME TO THE POPULATION GROWTH CALCULATOR"
>> print "*"
>>
>> print "This program will predict the size of a population of organisms."
>> print
>> print
>> while organisms <=1:
>> organisms=input("Please enter the starting number of organisms: ")
>> if organisms <=1:
>> print "Error. Population must be at least two."
>>
>> while increase <=0:
>> increase=input("Please enter the average daily population
>> increase as a percentage (20% = .20): ")
>> if increase <=0:
>> print "The percent of increase must be positive."
>>
>> while days <=0:
>> days=input("Please enter the number of days that they will
>> multiply: ")
>> if days <=0:
>> print "The number of days must be positive."
>>
>> print " DayPopulation"
>> print "--"
>> population = organisms
>>
>> for p in range (1,days+1):
>> if( p > 1 ):
>> population = population + ( population * increase )
>>
>> print "\t",p,
>>
>>
>>
>> [EMAIL PROTECTED] wrote:
>>
>>> On Oct 22, 5:37 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
>>>
>>>> On Oct 22, 5:22 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
>>>>
>>>>> On Mon, 22 Oct 2007 18:17:56 -0400, Shawn Minisall wrote:
>>>>>
>>>>>> #Intro
>>>>>> print "*"
>>>>>> print "WELCOME TO THE POPULATION GROWTH CALCULATOR"
>>>>>> print "*"
>>>>>>
>>>>>> print "This program will predict the size of a population of
>>>>>> organisms."
>>>>>> print
>>>>>> print
>>>>>> organisms=input("Please enter the starting number of organisms: ")
>>>>>>
>>>>>> increase=input("Please enter the average daily population increase
>>>>>> as a percentage (20% = .20): ")
>>>>>>
>>>>>> days=input("Please enter the number of days that they will multiply:
>>>>>> ")
>>>>>>
>>>>>> print " DayPopulation"
>>>>>> print "--"
>>>>>>
>>>>>> for p in range (days):
>>>>>>
>>>>>> population
while within while
I've been having some problems with using a while statement for one menu
within another while statement for the main menu, first time I've done
it. It's with choice number two from the menu. When I run the program,
I get a UnboundLocalError: local variable 'ai' referenced before
assignment. I initialize ai as "", but then it just skips to the you
choose scissors I choose and nothing shows up. As soon as I take away
the while again[0] == "y": statement, the program is fine again which
leads me to think I'm just placing it in the wrong place. I just want
to ask the user if they would like to play again and loop them back to
the weapons menu if they choose yes. If they choose no, loop them back
to the main menu. I've placed the question again=raw_input("Would you
like to play again? ") at the end the tasks for menu choice two. Ignore
threeone step at a time. ;)
thx
import random
def main():
#define and initialize variables
#choice as int
choice = 0
#weapon choice as int
weaponchoice = 0
#number of wins
win = 0
#number of loses
lose = 0
#number of ties
tie = 0
#number of rounds
rounds = 0
#play again loop
again = "no"
#intro
print "READY TO PLAY ROCK, PAPER, SCISSORS???"
print
#Menu loop
while choice != 4:
#display menu
print "Please choose from the following menu: "
print "1. See the rules"
print "2. Play against the computer"
print "3. Play a two player game"
print "4. Exit"
#prompt user for their menu choice
choice = input("Please enter your choice here: ")
print
#if statements to determine which choice
if choice == 1:
print
print "The rules of the game are as follows: "
print
print "Rock Covers Rock"
print
print "Rock Smashes Scissors"
print
print "Scissors Cuts Paper"
print
print
elif choice == 2:
while again[0] == "y":
#display menu
print "Please choose a weapon from the following menu: "
print "1. Rock"
print "2. Paper"
print "3. Scissors"
while weaponchoice != 1 and weaponchoice != 2 and
weaponchoice != 3:
weaponchoice = input("Please choose a weapon: ")
if weaponchoice != 1 and weaponchoice != 2 and
weaponchoice != 3:
print
print "Error. Please enter a number from 1-3."
decision = (1, 2, 3)
ai = str((random.choice(decision)))
if ai == "1":
ai = "rock"
if ai == "2":
ai = "paper"
if ai == "3":
ai = "scissors"
if weaponchoice == 1:
weaponchoice = "rock"
elif weaponchoice == 2:
weaponchoice = "paper"
else:
weaponchoice = "scissors"
print "="
print "you choose " + weaponchoice
print
print "I choose " + ai
print
if weaponchoice == "rock" and ai == "scissors":
win += 1
print "You WIN by SMASHING those SCISSORS!"
elif weaponchoice == "paper" and ai == "rock":
win += 1
print "You WIN by COVERING that ROCK!"
elif weaponchoice == "scissors" and ai == "paper":
win += 1
print "You WIN by CUTTING that PAPER!"
elif weaponchoice == ai:
tie += 1
print "YOU TIE!"
else:
lose += 1
print "YOU LOSE!"
print "\nRounds Won: ", + win
print "\nRounds Lost: ", + lose
print "\nRounds Tied: ", + tie
print
print
again=raw_input("Would you like to play again? ")
elif choice == 3:
print "test"
elif choice == 4:
print "Have a great day!"
print
print "Thanks for playing!"
else:
#invalid
print "Invalid selection. Please enter a number from 1 - 4."
print
--
http://mail.python.org/mailman/listinfo/python-list
while within while
K I've since fixed the UnboundLocalError: local variable 'ai' referenced before assignment error, I forgot to include decision = (1, 2, 3) inside " " for each number. Now when I run it, I get this.. >>> main() READY TO PLAY ROCK, PAPER, SCISSORS??? Please choose from the following menu: 1. See the rules 2. Play against the computer 3. Play a two player game 4. Exit Please enter your choice here: 2 = you choose scissors I choose YOU LOSE! Rounds Won: 0 Rounds Lost: 1 Rounds Tied: 0 Would you like to play again? y Please choose from the following menu: 1. See the rules 2. Play against the computer 3. Play a two player game 4. Exit Please enter your choice here: 2 Please choose a weapon from the following menu: 1. Rock 2. Paper 3. Scissors Please choose a weapon: 1 and then the weapon submenu repeats over and over. It's also like the program is ignoring if ai == "1": ai = "rock" if ai == "2": ai = "paper" if ai == "3": ai = "scissors" since it says I choose -- http://mail.python.org/mailman/listinfo/python-list
Re: while within while
Thanks a lot for your suggestions. Unfortunately, a lot of the issues
brought up were simply the way I was taught by my professor and the way
she wants things done,having to use a numbered menu as opposed to
entering r, p or s, being taught just to use one main function for the
entire program, having to init all variables in the program b4 the
actual program starts or else points off for each program, while
statements surrounding every input statement for input validation
purposes...
Going beyond those things, would look like someone else wrote my program
since we didn't talk about or ever cover them in class. I think we get
to true statements in the next chapter next week.
It turns out that my problem was with indentation, as soon as I fixed
it, it's working perfectly now.
thx
Dennis Lee Bieber wrote:
> On Sat, 27 Oct 2007 15:11:37 -0400, Shawn Minisall
> <[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
>
> Smells like homework -- so this week I won't be supplying a working
> program (even one with no documentation -- requiring the student to
> study the reference manuals to figure out what is being done) I'm going
> to more focus on some stylistic features.
>
>> import random
>>
>>
>> def main():
>>
>> #define and initialize variables
>> #choice as int
>> choice = 0
>>
>
> Please note that one cannot define /type/ for a variable NAME. the
> name is just a name that is attached to an object, and can be attached
> to some other object later... It is the object on the RHS of the
> assignment that has a type.
>
> The above binds the name "choice" to an object of type integer -- a
> 0... The type is part of the 0, not of the name.
>
>
>> #play again loop
>> again = "no"
>>
>
>
>
>>
>> #Menu loop
>> while choice != 4:
>> #display menu
>> print "Please choose from the following menu: "
>> print "1. See the rules"
>> print "2. Play against the computer"
>> print "3. Play a two player game"
>> print "4. Exit"
>>
>> #prompt user for their menu choice
>> choice = input("Please enter your choice here: ")
>> print
>>
>>
> Rather than having to pre-initialize your loop conditional (and
> notice that you can use ANY value EXCEPT 4 to initialize it) just for
> the pleasure of using a while loop (I'm guessing being taught from the
> "go to is forbidden" crowd, and not knowing of structured loop exits..)
> that you go out of your way to avoid duplicating code (Pardon my
> phrasing -- I'm not quite sure what my point was trying to be...) Let me
> just mention that in Ada, what you are trying would be formulated as:
>
> loop
> --display menu
> -- prompt for choice
> exit when choice = 4
> -- process other choices
> end loop
>
> No need to preload the condition variable, since the first time it
> is used is when it receives a value from the user.
>
> Python can produce the same formulation... (hint: the naked "loop"
> in Ada is "while True" in Python).
>
>
>>
>>
>> #if statements to determine which choice
>> if choice == 1:
>> print
>> print "The rules of the game are as follows: "
>> print
>> print "Rock Covers Rock"
>> print
>> print "Rock Smashes Scissors"
>> print
>> print "Scissors Cuts Paper"
>> print
>> print
>>
>>
> Python triple quoted strings can be split over multiple lines:
>
> print """
> The rules of the game are as follows:
>
> Paper Covers Rock
>
> Scissors Cut Paper
>
> Rock Breaks Scissors
>
> """
> even better -- This should be an initialized item at the start of the
> program:
>
> rules = """
> The rules... etc.
> """
> and then you just use one
>
> print rules
>
>
>
>>
>> elif choice == 2:
>> while again[0] == "y":
>>
>
> I'd suggest same concern as prior while loop... don't preload
> choices when the real determination can only be made after first
> entering the loop.
>
>
clear shell screen
Does anyone know how to clear the shell screen completely ? I tried
import os and then os.system("clear") was said to have worked in Windows
XP, but it's just bringing up another window, then it turns black and
then it closes in within about a second moving the prompt at the
os.system("clear") line . I've also tried os.system("cls") with the
same results.
thx
--
http://mail.python.org/mailman/listinfo/python-list
Re: New
On 10/28/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Hi! > Am new to Python and am looking for a sample project that demonstrates > how to connect to MySQL, save data in MySQL database using a form on a > web page. > > Regards, > Joseph > > -- > http://mail.python.org/mailman/listinfo/python-list > 1. Read this: http://catb.org/~esr/faqs/smart-questions.html 2. You can easily find what you're asking for on Google. -- http://mail.python.org/mailman/listinfo/python-list
Re: clear shell screen
Hmm...it works fine within the command line but then when I import os in
python and then try os.system("cls"), i get that very fast
opening/closing window and 0 inside the shell.
Gabriel Genellina wrote:
> En Mon, 29 Oct 2007 00:08:14 -0300, Shawn Minisall
> <[EMAIL PROTECTED]> escribi�:
>
>
>> Does anyone know how to clear the shell screen completely ? I tried
>> import os and then os.system("clear") was said to have worked in Windows
>> XP, but it's just bringing up another window, then it turns black and
>> then it closes in within about a second moving the prompt at the
>> os.system("clear") line . I've also tried os.system("cls") with the
>> same results.
>>
>
> Try running cls from a command prompt. If it works, it should work from
> inside Python, using os.system("cls")
>
>
>
--
http://mail.python.org/mailman/listinfo/python-list
