Re: [Tutor] Using pip

2018-07-05 Thread James Reynolds
On Thu, Jul 5, 2018 at 12:55 PM Hlavin, Matthew (GSFC-5460)[GSFC INTERNS] <
matthew.hla...@nasa.gov> wrote:

> I just downloaded Python to work on a project at work. I'm writing a
> pretty simple program for data collection for an experiment. In order to
> get the data, though I need to install PyVISA. The website for PyVISA says
> I can install the library using the line:
> $ pip install -U pyvisa
> When I type this line, I get a syntax error for using the $, and when I
> remove the $, I get a syntax error for using the word install. I even tried
> just using the word pip and an error said 'pip' is not defined. I'm not
> sure if I'm not using some syntax wrong, or if its a completely different
> issue.
>
> Thanks for any help and insight
> Matt Hlavin
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor



What version of Python did you install and what operating system are you
using?

the $ is just a command prompt and it isn't used for the above command.

The important bit from your message is the "I even tried just using the
word pip and an error said 'pip' is not defined".

This means either A.) You have pip installed, but it's not on your path or
B.) You don't have pip installed.

If you installed latest python (which is 3.7), then you can can create a
virtual env directly and just use that, which contains pip as well.

(this all assumes that python is on your path already)

python -m venv env

this will create a virtual environment called "env".

After you create your virtual environment, you activate it ".
env/bin/activate". If you are windows it would be "env\Scripts\activate"

Once activated, you can install your package like: pip install pyvisa

you may also enjoy using ipython (pip install ipython) for this kind of use
case.

James
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Can't install latest PIL

2013-05-16 Thread James Reynolds
You may want to consider pillow. Oil hasn't been maintained in some time.
 On May 16, 2013 6:12 PM, "Jim Mooney"  wrote:

> Make sure you have the correct architecture. The builds from
> PythonWare are 32-bit. Christoph Gohlke has 64-bit builds here:
>
> http://www.lfd.uci.edu/~gohlke/pythonlibs/#pil
>
> ==
> Okay, I installed the 64 bit for Py 2.7, it installed, I see  PIL
> directory in Site-Packages. (Actually, it's the Pillow fork, but it
> still seems to be named PIL)  I tried "import image from pil" and got
> the following error: SyntaxError   invalid syntax (python_init.py,
> line 1)
>
> I don't see where that prog is, so it's an install somewhere and I
> don't want to mess with it anyway.
>
> Oh well, be nice to get back to learning Python after wrestling with
> editors, installs, and Windows ;')
>
> Jim
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] building a website with python

2013-04-09 Thread James Reynolds
As far as hosts, I use digital ocean. It's a cloud based thing like EC2,
but it's cheap (5/10/20 and up). You will of course have to configure
everything yourself, but that's not such a bad thing.

It will give you good experience configuring a linux box as well and
learning about deployment.

Since I'm a django developer, I'm going to suggest you learn that of
course. But, there are others out there. However, with Django you get the
Django eco system, which is large and very helpful.

For example, you can use fabric for easy deployment, south for database
migrations, celery for task management and so and so forth.

Even simple websites could find some use in south and fabric.


On Tue, Apr 9, 2013 at 6:06 PM, Walter Prins  wrote:

> Hello Benjamin,
>
> On 9 April 2013 22:31, Benjamin Fishbein  wrote:
>
>> Hello. I learned Python this past year (with help from many of you) and
>> wrote many programs for my small business. Now I want to build a website. I
>> acquired the domain name through godaddy.com (bookchicken.com) but have
>> not found hosting yet.
>> I learned html, css, and javascript via codeacademy.org, but have never
>> built a website.
>> I would like to build it with Python, and was wondering if you could give
>> me some pointers about what I need to learn first: Django is the thing to
>> use? And do I need specific hosting to use python or are all hosts
>> basically the same.
>>
>
> Django is good but arguably big and a bit intimidating if you're starting
> out.  There are many alternatives, from so called "micro" frameworks like
> "bottle" (which is implemented in a single Python file) to CherryPy to
> Flask.  Personally, I'd suggest having a look at Web2Py.  It's not quite as
> heavy as Django but very capable nonetheless.  It also deploys easily,
> including to Google App Engine and elsewhere, and includes a very capable
> Admin interface that also includes a basic IDE, thus allowing you to tweak
> the site right from within the site should you have the need. Here's a nice
> little presentation about Web2Py:
> http://www.slideshare.net/blackthorne/web2pyweb-development-like-a-boss
> ... and a tutorial to get you going:
> http://killer-web-development.com/section/1/0
>
> Not all web hosts are the same -- you need to ensure you have Python
> available with the host you use.  There are dedicated Python hosts out
> there.  (PythonAnywhere comes to mind.)  As a slightly different
> possibility, you might consider running your own virtual host in the cloud.
>  You would need to learn a bit about administering a server box, but this
> route does give you the ultimate control over your website and environment.
>  Here's a link to Rackspace with which I've had good experiences thus far
> for your review:
> http://www.rackspace.com/cloud/servers/
>
> Walter
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Which pip for Ubuntu 12.04

2013-02-10 Thread James Reynolds
The bigger issue with mongo is the apt versions are old. Be sure to follow
the instructions on mongos site.

If you pip install pymongo with a ubunuto or mint build your gtg
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] PostreSQL

2012-11-15 Thread James Reynolds
Psycopg2 is the driver for postgres. Not sure if it is py3k compliant
On Nov 15, 2012 6:13 AM, "Válas Péter"  wrote:

> Two listings, of course. :-)
> I failed to tell that my PG version is "PostgreSQL 8.1.2" (and my client
> uses Windows 7, if this has relevance).
>
> 2012/11/15 Válas Péter 
>
>> Hi folks,
>>
>> Here are to listings of Python interfaces to PostgreSQL:
>> Postgres wiki: http://wiki.postgresql.org/wiki/Python
>> Python wiki: http://wiki.python.org/moin/PostgreSQL
>>
>> I have Python 3.2.3.
>> Does anybody have experiences with these modules? Which is worth to use?
>> Any point of view to compare them?
>>
>> Thanks, Péter
>>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What can I do if I'm banned from a website??

2012-10-10 Thread James Reynolds
On Wed, Oct 10, 2012 at 4:35 PM, Benjamin Fishbein wrote:

> I've been scraping info from a website with a url program I wrote. But now
> I can't open their webpage, no matter which web browser I use. I think
> they've somehow blocked me. How can I get back in? Is it a temporary block?
> And can I get in with the same computer from a different wifi?
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

A few thoughts:

1. Try using a proxy.
2. Ask the webadmin (nicely) to unban you
3. Use requests / urllib3 to se connection pooling
4. See if the site has an API designed for data extraction.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python cms

2012-08-19 Thread James Reynolds
I agree with Steven.

You will notice efficiency gains by moving to python.

I'm a django developer myself, but some of the other frameworks work well also.

That said the django community is fairly large, and there is an active cms 
project called django-cms.

https://www.django-cms.org/



Sent from my iPad

On Aug 19, 2012, at 3:10 AM, Steven D'Aprano  wrote:

> On 19/08/12 15:05, Douglas Kuo wrote:
>> Hi all,
>> 
>> I am mainly a php/drupal developer totally new to python.. Any experienced
>> python especially in term of cms developers out there can tell me what are
>> the benefits of python cms over php cms?
> 
> This might upset you, but the biggest advantage is that they aren't PHP.
> 
> http://www.codinghorror.com/blog/2012/06/the-php-singularity.html
> 
> http://me.veekun.com/blog/2012/04/09/php-a-fractal-of-bad-design/
> 
> I know what it's like to have people dissing your favourite language and
> telling you it isn't a "proper" programming language. But you know, sometimes
> there are good reasons why they do that, not just fashion.
> 
> I found this spirited defense of PHP here:
> 
> http://blog.ircmaxell.com/2012/04/php-sucks-but-i-like-it.html
> 
> which raises some good points, but I think when the author finds himself
> defending PHP's == operator in the comments by saying:
> 
> "It may not be sane, but it works..."
> 
> then I think he's just conceded the argument.
> 
> 
> The biggest disadvantage of using a Python CMS is that if you're not running
> your own web server, you might have to call up two or three ISPs to find one
> that will provide you with Python on the server.
> 
> In the Python ecosystem, we have Zope, which is a big, powerful heavyweight
> CMS. For a beginner, you might prefer to start with something more
> lightweight. Perhaps try Django:
> 
> https://www.djangoproject.com/
> 
> See also http://wiki.python.org/moin/ContentManagementSystems
> 
> 
> For a wiki, try MoinMoin:
> 
> http://moinmo.in/
> 
> For web frameworks, try CherryPy:
> 
> http://www.cherrypy.org/
> 
> 
> 
> -- 
> Steven
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I-Phone App in Python?

2012-08-04 Thread James Reynolds
the "native app" part of building an "app" is somewhat trivial in
comparison to the backend needs.

Read this article here on what instagram uses for their architecture:
http://instagram-engineering.tumblr.com/post/13649370142/what-powers-instagram-hundreds-of-instances-dozens-of


As you can see, most of it is Python libraries, some of which are django
specific, some of which aren't (note, theya are using custom written task
system instead of using Celery - not sure why this is).

As I understand it, interpreted languages on phones simply take up too much
space and memory.

I know some companies have used
http://www.appcelerator.com/<http://www.appcelerator.com/developers>
with
good success

That said, unless all you want to your app to do is only interact with the
user from within the phone and never get information from outside of it or
send information outside of it, then I suppose you won't be able to use
Python to any degree.

But, if you do, then you can write fantastic apps using python libraries
for the backend needs.

On Sat, Aug 4, 2012 at 2:28 PM, Chris Fox  wrote:

> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA1
>
> On 04/08/2012 19:18, James Reynolds wrote:
> > Instagram is written in python django.
> >
>
> Even if that were true (Django is, as I understand it, a web
> framework) - how does that information help the original poster?
>
> Chris
>
> -BEGIN PGP SIGNATURE-
> Version: GnuPG v2.0.17 (MingW32)
> Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/
>
> iEYEARECAAYFAlAdabcACgkQ/UgLKfoJxI5f9QCgwA1LR2S0EqUpxWqlFaGE9Dl6
> yGEAoLqYlTDn6kZWrZ+PN20uqpmsSbPJ
> =Oeru
> -END PGP SIGNATURE-
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I-Phone App in Python?

2012-08-04 Thread James Reynolds
To clarify, that is their server side arc. The native app itself...  I'm not 
sure what is written in. Probably java if I had to guess.

In making an app, most of your work is going to be backend in any event.

Also, what happens when an android user wants to download your app? 

Sent from my iPad

On Aug 3, 2012, at 7:13 PM, Fred G  wrote:

> I just googled whether it is possible to write an i-phone app in Python and 
> got very confusing, and not super good results.
> 
> Is it possible? And if so, what module(s) do I need to install?
> 
> Much thanks!
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I-Phone App in Python?

2012-08-04 Thread James Reynolds
Instagram is written in python django. 

Sent from my iPad

On Aug 3, 2012, at 7:13 PM, Fred G  wrote:

> I just googled whether it is possible to write an i-phone app in Python and 
> got very confusing, and not super good results.
> 
> Is it possible? And if so, what module(s) do I need to install?
> 
> Much thanks!
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] advice on global variables

2012-07-11 Thread James Reynolds
On Wed, Jul 11, 2012 at 10:30 AM, Chris Hare  wrote:

>
> On Jul 11, 2012, at 8:05 AM, Walter Prins wrote:
>
> > [snip]
>
> > Your original example modified as demonstration:
> >
> > a.py:
> > 
> > import shared
> > import b
> >
> > def func1():
> >print "global var in func1 = %s" % shared.global_var
> >
> > class intclass:
> >def func2(self):
> >print "global var in intclass = %s" % shared.global_var
> >
> > print "global_var = %s" % shared.global_var
> > func1()
> > f = intclass()
> > f.func2()
> > g = b.extclass()
> > g.func3()
> >
> > b.py:
> > 
> >
> > import shared
> >
> > class extclass:
> >def func3(self):
> >print "global var in extclass = %s" % shared.global_var
> >
> >
> > shared.py:
> > ===
> > global_var = "global"
> >
> >
> I like where this is going Walter.  I guess where I am confused is this:
>
> the globals are not static - they are set once and then won't change
> during the lifetime of the user's session.
>
> So, after messing around with the ram DB idea, I realized I was back to
> the same problem.
>
> Let's say I create a dictionary to store all of the "globals" and other
> data I want available everywhere and I put that in a class.  Every time I
> create an instance of the class to be able to access the data, a new
> instance of the dictionary is created that loads the same data in it.
>  Seems kinda inefficient for me, especially if the data changes in one
> instance - how do you keep the others all in sync, or does that just happen
> automatically?
>
> I think there is something that I fundamentally not understanding and I
> don't know what it is.   Am I making this too complicated?
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


You are making this too complicated.

I think you are getting hung up on instantiating objects. You don't need to
instantiate an object everytime you use it. Once you have it, it's a
variable like any other and you can pass it around.

Just have a class body with your variables:

class MyObj(object):
   def __init__(self, *args, **kwargs):
   do stuff with variables here

Then instantiate the object

m = myobject(pass in your parameters)

now pass around the instantiated object on an as needed basis, or, access
the instance directly

example 1:

def func(obj):
   do stuff with obj

to call it: func(m)

example 2:

File 1: #tests

def reset_m(m, settings):
m.settings = settings

File 2: #test_two

class MyObj(object):
def __init__(self, settings=True):
self.settings = settings



if __name__ == '__main__':
m = MyObj()


File 3: #main

import test_two
import tests

m = test_two.MyObj()

print m.settings

tests.reset_m(m, False)

print m.settings

The above will print True, False

But, you don't need to create a class that has a single attribute, which is
a dictionary. In that case, you can just create a dict and pass that around
(I generally prefer to have a class body and access things using dot
notation rather than dictionary syntax)

Generally though, I think this entire idea of settings dictionary or class
can be simplified. I'll bet most of the settings have some general
similarities or are repeated, or they are the same for each user, each time.

In that case, you should probably move to a more database driven approach,
or hardcode settings in a file and override those hardcoded settings on an
as needed basis.

In django, you have a "settings" file. In there, you hard code some most of
your settings, like apps you are using, where your database resides,
middleware, etc.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] advice on global variables

2012-07-10 Thread James Reynolds


Sent from my iPad

On Jul 10, 2012, at 3:11 PM, Chris Hare  wrote:

> 
> I know they are bad.  That is why I would prefer not to use it, but I am not 
> sure how else to handle this problem.
> 
> In this app, the user must log in.  Once authenticated, they have a userid 
> stored in the SQLite database.  Before splitting my app into multiple files, 
> I used a global variable.  I know its bad, but it worked.  Now that things 
> are split apart, the classes which used it previously now don't see it 
> anymore, even using the global keyword.  I think this is the expected 
> behavior.  See here
> 
> file: a.py
> 
> import b
> global_var = "global"
> 
> def func1():
>global global_var
>print "global var in func1 = %s" % global_var
> 
> class intclass:
>def func2(self):
>global global_var
>print "global var in intclass = %s" % global_var
> 
> print "global_var = %s" % global_var
> func1()
> f = intclass()
> f.func2()
> g = b.extclass()
> g.func3()
> 
> file: b.py
> 
> class extclass:
>def func3(self):
>global global_var
>print "global var in extclass = %s" % global_var
> 
> When I run it, I get what I think the expected behavior, that the external 
> class ext class won't be able to see the global_var
> 
> Big-Mac:t chare$ python a.py
> global_var = global
> global var in func1 = global
> global var in intclass = global
> Traceback (most recent call last):
>  File "a.py", line 18, in 
>g.func3()
>  File "/Users/chare/Development/python/animaltrax/pkg/t/b.py", line 5, in 
> func3
>print "global var in extclass = %s" % global_var
> NameError: global name 'global_var' is not defined
> 
> So - my question is this:  how do I solve the problem of multiple classes 
> needing to get access to a value which needs to be preserved across the 
> lifetime of the running application?
> 
> One thought was a RAM based SQLite database, but that seems like a lot of 
> work.  I dunno, maybe that is the option.
> 
> suggestions, ideas, criticisms are all welcome.  Python code aside, I just 
> don't know how to approach this problem in Python.
> 
> Thanks, as always for the feedback and guidance.
> 
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor



I'll admit it's a little tough for me to read your code.

If you need to store some information, store it to your db and access it later.

If would rather have he settings in the source code, study django's conf and 
how it handles configurations.

Better yet, why not just use django for your app?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] advice on global variables

2012-07-10 Thread James Reynolds
On Tue, Jul 10, 2012 at 4:32 PM, Prasad, Ramit wrote:

> > You should avoid using the global statement.
> >
> > In your case, I would think you could just add an argument to the method:
> >
> > class MyObj(object):
> > def __init__(self, arg):
> > self.arg = arg
> > def my_func(self, new_arg):
> > self.arg = new_arg
> >
> > to call it:
> >
> > arg = 1
> >
> > m = MyObj(arg)
> > print m.arg
> > new_arg = 2
> > m.my_func(new_arg)
> > print m.arg
>
> Just as a note, this would not really work if the variable needs to be
> changed and read from several places when the value is an immutable
> type such as numbers / strings. In that case, then you could use
> the same logic but instead place the value in a list and pass that
> and always check/update the first element of the list.
>
>
> Ramit
>
>
> Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
> 712 Main Street | Houston, TX 77002
> work phone: 713 - 216 - 5423
>
> --
>
> This email is confidential and subject to important disclaimers and
> conditions including on offers for the purchase or sale of
> securities, accuracy and completeness of information, viruses,
> confidentiality, legal privilege, and legal entity disclaimers,
> available at http://www.jpmorgan.com/pages/disclosures/email.
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


In this case, you can read the attribute of MyObj and you just pass an
instantiated MyObj around to where it is needed.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] advice on global variables

2012-07-10 Thread James Reynolds
On Tue, Jul 10, 2012 at 3:11 PM, Chris Hare  wrote:

>
> I know they are bad.  That is why I would prefer not to use it, but I am
> not sure how else to handle this problem.
>
> In this app, the user must log in.  Once authenticated, they have a userid
> stored in the SQLite database.  Before splitting my app into multiple
> files, I used a global variable.  I know its bad, but it worked.  Now that
> things are split apart, the classes which used it previously now don't see
> it anymore, even using the global keyword.  I think this is the expected
> behavior.  See here
>
> file: a.py
>
> import b
> global_var = "global"
>
> def func1():
> global global_var
> print "global var in func1 = %s" % global_var
>
> class intclass:
> def func2(self):
> global global_var
> print "global var in intclass = %s" % global_var
>
> print "global_var = %s" % global_var
> func1()
> f = intclass()
> f.func2()
> g = b.extclass()
> g.func3()
>
> file: b.py
>
> class extclass:
> def func3(self):
> global global_var
> print "global var in extclass = %s" % global_var
>
> When I run it, I get what I think the expected behavior, that the external
> class ext class won't be able to see the global_var
>
> Big-Mac:t chare$ python a.py
> global_var = global
> global var in func1 = global
> global var in intclass = global
> Traceback (most recent call last):
>   File "a.py", line 18, in 
> g.func3()
>   File "/Users/chare/Development/python/animaltrax/pkg/t/b.py", line 5, in
> func3
> print "global var in extclass = %s" % global_var
> NameError: global name 'global_var' is not defined
>
> So - my question is this:  how do I solve the problem of multiple classes
> needing to get access to a value which needs to be preserved across the
> lifetime of the running application?
>
> One thought was a RAM based SQLite database, but that seems like a lot of
> work.  I dunno, maybe that is the option.
>
> suggestions, ideas, criticisms are all welcome.  Python code aside, I just
> don't know how to approach this problem in Python.
>
> Thanks, as always for the feedback and guidance.
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


You should avoid using the global statement.

In your case, I would think you could just add an argument to the method:

class MyObj(object):
def __init__(self, arg):
self.arg = arg
def my_func(self, new_arg):
self.arg = new_arg

to call it:

arg = 1

m = MyObj(arg)
print m.arg
new_arg = 2
m.my_func(new_arg)
print m.arg
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] web design and python

2012-06-21 Thread James Reynolds
On Thu, Jun 21, 2012 at 6:53 PM, Tamar Osher wrote:

>  I have many questions, and eagerly ask you to please respond to me.  I
> value your expertise, and greatly appreciate you taking the time to share.
>  I want to find out, in elaborate detail, about the Python/Django
> relationship to web design.  Why does a person or a company seek out and
> choose a Python-Django website, instead of Drupal, or Joomla, or Wordpress,
> or something else?  What is the description of the unique, small niche that
> Python/Django has in the world of web design?  Who are these individuals
> and companies that want Python/Django/TurboGears websites?  What is the
> Python/Django/TurboGear relationship to "responsive web design" (which
> means the website is beautifully, perfectly view-able on all sizes of
> screens, including a smartphone, an ipad, and a desktop). What are the pros
> and cons of choosing Python/Django/TurboGears, compared to other web
> development options, such as Drupal, Joomla, and Wordpress?  Is it really
> true that Python/Django websites cannot use just any web hosting service,
> and are more expensive to maintain?  I have read several books about Python
> web development, and have extensively researched online, but have not found
> any of this information.  It would be nice if someone could write a full
> article about this, to explain the true, current situation and realistic
> 2012 options to beginners who don't have degrees in computer science.  I am
> very, very eager to hear from each one of you.  THANK YOU for your time and
> help!
>
>
> **
> *
>
>
>
> *
>
> * *
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


I'm not really sure how to respond to you, but I'll give it a go.

 Why does a person or a company seek out and choose a Python-Django
> website, instead of Drupal, or Joomla, or Wordpress, or something else


Well, Drupal, Joomla, Wordpress are all CMS (content management Systems).
They are also written in PHP. I think the goals of developing in django vs
having a wordpress site are quite a bit different, although they could be
the same, I suppose.

For example, if you wanted a site to just publish your daily thoughts, you
might use wordpress. However, if you want to identify a tree by an image
you took on your iphone, you might use django (and a lot of other stuff to
make that magic happen!)

Generally, I think, companies and people choose django because of the
community and how much you can get done with it in a short period of time.

What is the description of the unique, small niche that Python/Django has
> in the world of web design?


Not sure what this sentence means, but I wouldn't call Python / Django as
small niche in the world of web design. It's probably the third most
popular option right now, behind PHP and rails.

  What is the Python/Django/TurboGear relationship to "responsive web
> design" (which means the website is beautifully, perfectly view-able on all
> sizes of screens, including a smartphone, an ipad, and a desktop)


Turbogears is another framework.  I'm not sure of many sites built on it;
I'm sure they are out there, I just don't know of them.

You should check out: http://www.djangosites.org/

  Is it really true that Python/Django websites cannot use just any web
> hosting service, and are more expensive to maintain?


Django is just a set of libraries written in python. So long as the
webhosting service allows you to install python, install apache (or
something similar) and allows you to broadcast, you can host the website.
As for the second part, more expensive than what? Once you get the site,
they sort of run themselves. You just have to pay for bandwidth and
hosting. If your saving a lot of data and using a lot of bandwidth, that
could get costly, but... that is not an issue of django, but rather of
design / product needs.

Some webhosting companies make it easier to set up django though. Some
already have it installed, some do not.

to beginners who don't have degrees in computer science


I also do not have a degree in computer science. I am also a full time web
developer working in Python / Django.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Pymongo Error

2012-06-19 Thread James Reynolds
On Tue, Jun 19, 2012 at 1:22 AM, Ranjith Kumar wrote:

> Hi all,
> I tried Django with Mongodb while running manage.py syncdb I endup with
> this error
>
> note : it works fine with sqlite and mysql db
>
> (django-1.3)ranjith@ranjith:~/
> sandbox/python-box/hukkster-core-site/hukk$ ./manage.py syncdb
> /home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/pymongo/connection.py:385:
> UserWarning: must provide a username and password to authenticate to
> hukkster_testing
>   "to authenticate to %s" % (db,))
> Creating tables ...
> Traceback (most recent call last):
>   File "./manage.py", line 14, in 
> execute_manager(settings)
>   File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/core/management/__init__.py",
> line 438, in execute_manager
> utility.execute()
>   File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/core/management/__init__.py",
> line 379, in execute
> self.fetch_command(subcommand).run_from_argv(self.argv)
>   File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/core/management/base.py",
> line 191, in run_from_argv
> self.execute(*args, **options.__dict__)
>   File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/core/management/base.py",
> line 220, in execute
> output = self.handle(*args, **options)
>   File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/core/management/base.py",
> line 351, in handle
> return self.handle_noargs(**options)
>   File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/core/management/commands/syncdb.py",
> line 109, in handle_noargs
> emit_post_sync_signal(created_models, verbosity, interactive, db)
>   File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/core/management/sql.py",
> line 190, in emit_post_sync_signal
> interactive=interactive, db=db)
>   File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/dispatch/dispatcher.py",
> line 172, in send
> response = receiver(signal=self, sender=sender, **named)
>   File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/contrib/auth/management/__init__.py",
> line 41, in create_permissions
> "content_type", "codename"
>   File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/db/models/query.py",
> line 107, in _result_iter
> self._fill_cache()
>   File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/db/models/query.py",
> line 772, in _fill_cache
> self._result_cache.append(self._iter.next())
>   File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/django/db/models/query.py",
> line 959, in iterator
> for row in self.query.get_compiler(self.db).results_iter():
>   File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/djangotoolbox/db/basecompiler.py",
> line 229, in results_iter
> for entity in self.build_query(fields).fetch(low_mark, high_mark):
>   File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/djangotoolbox/db/basecompiler.py",
> line 290, in build_query
> query.order_by(self._get_ordering())
>   File
> "/home/ranjith/virtualenvs/django-1.3/local/lib/python2.7/site-packages/djangotoolbox/db/basecompiler.py",
> line 339, in _get_ordering
> raise DatabaseError("Ordering can't span tables on non-relational
> backends (%s)" % order)
> django.db.utils.DatabaseError: Ordering can't span tables on
> non-relational backends (content_type__app_label)
>
>
> DB settings in settings.py
>
> DATABASES = {
> 'default': {
> 'ENGINE': 'django_mongodb_engine',
> 'NAME': 'helloworld',
> 'USER': '',
> 'PASSWORD': '12424214',
> 'HOST': 'mongodb://staff.mongohq.com/',
> 'PORT': 'X',
> },
> }
>
> my requirement packages,
> Django==1.3
> dictshield==0.4.4
> django-mongodb-engine==0.4.0
> django-social-auth==0.6.9
> djangotoolbox==0.0.1
> httplib2==0.7.4
> mongoengine==0.6.10
> mongokit==0.8
> oauth2==1.5.211
> pymongo==2.2
> python-openid==2.2.5
> simplejson==2.5.2
> wsgiref==0.1.2
>
> Please point me what i missed here...
>
> --
> Cheers,
> Ranjith Kumar K,
> Chennai.
>
> http://ranjithtenz.wordpress.com
>
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


This list here is for new users to python. Using mongo with django is a
pretty advanced topic. I would suggest posting this on stackoverflow, or to
the django-users group (and there are a ton of resources on this already on
those two sites on this topic)

That said, having used mongo with django, I'll bet your problem is that you
are using the django version provided by the django pro

Re: [Tutor] Dictionary

2012-06-17 Thread James Reynolds
Does this language have grammar independent of english?

If no, just use .split() on the string and loop through that.

If yes, well, its much more complicated
On Jun 17, 2012 2:27 PM, "Selby Rowley-Cannon" 
wrote:

> Version: 2.7
> OS: Ubuntu 12.04 LTS
>
> I am writing a small translation app for Rydish (A language that exists in
> the same way Klingon does, invented by my company for a[n] RPG).
> Here is my current method of translation:
>
> Edictionary = {'English keys':'Rydish values'}
> TextEng = raw_input('Please enter your text: ')
> if TextEng in Edictionary:
> print(TextEng + ' traslates to ' + Edictionary[TextEng])
>
> But I have found that this is only going to translate one word at a time.
> I thought about a loop of somesort, but I can't seem to find one that won't
> still force the user to translate one word at a time. Can anyone tell me
> how to translate a full sentance/several sentances?
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Web Questionnaire

2012-06-04 Thread James Reynolds
I would say start using django.

The best way to learn is by doing.

This will let you learn about databases, servers, webapps, and you can get
some functionality out of it. Just start going through the django tutorial.
On Jun 4, 2012 11:57 AM, "Joel Goldstick"  wrote:

> On Mon, Jun 4, 2012 at 11:12 AM, Akeria Timothy 
> wrote:
> > Hello All,
> >
> > I am still new to learning Python and I wanted to know if anyone knew of
> a
> > script out there that would allow users to answer three basic questions,
> hit
> > submit and send that information to an excel spreadsheet?
> >
> > So, I would want them to submit the following information:
> >
> > Name:
> > Dept:
> > Software needed:
> > Semester requesting software for:
> >
> > I work for a college and I wanted to streamline the software requests for
> > the school year.
> >
> > Is this a basic script? I have started my script but I know it will
> probably
> > take me longer to write it so I figured I would ask if there was
> something
> > out there that I could just modify.
> >
> >
> > Thanks in advance
> >
> > ___
> > Tutor maillist  -  Tutor@python.org
> > To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
> >
> I'm not sure this is a 'python tutor' question.  You would need to
> have a website that presumable limits access to certain people so that
> anyone couldn't make a request.  Django could do that for you out of
> the box more or less, but then you would have to deploy it. So, its
> not just a small python script, but a website you would need to build.
>  Are you up to that yet?
>
> If you are thinking up useful projects to expand your python skills,
> perhaps publishing an email box for requests would be easier.  You
> could read the emails and enter the data in a simple command line
> program you could write in python to added data in csv format to a
> file.  This file could be viewed in excel.
>
> Such a project would help you learn about csv module, and how to
> request data from a user. -- both useful things to learn
>
>
> --
> Joel Goldstick
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Connecting to MySQLdb

2012-06-01 Thread James Reynolds
Virtualenv works just fine in windows
 On Jun 1, 2012 7:20 PM, "Corey Richardson"  wrote:

> On Fri, 1 Jun 2012 19:01:00 -0400
> Nicholas Picciano   wrote:
>
> > Hello,
> >
> > I have downloaded MySQLdb 1.2.3 from:
> >
> > http://pypi.python.org/pypi/MySQL-python
> >
> > Also, I'm using Python 2.7, but I can't even get past here:
> >
> > >>> import MySQLdb
> > Traceback (most recent call last):
> >   File "", line 1, in 
> > ImportError: No module named MySQLdb
> >
> > Thanks
>
> Did you install it?
>
> Assuming UNIX(-like):
>
> I highly, *highly* recommend you use a virtualenv [1] and, if you want
> a fancy UI, virtualenvwrapper [2]. From there you can install all the
> packages you want with pip, without having to worry about mucking up
> the system, versions of things, etc.
>
> Assuming Windows:
>
> Good luck!
>
> --
> Corey Richardson
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Benefit/Disadvantage to storing data as dictionary vs. in a class

2012-06-01 Thread James Reynolds
On Fri, Jun 1, 2012 at 9:12 AM, Adam  wrote:

> I'm working on a class that handles multiple rooms that generate a large
> amount of data. Currently my class model looks something like this (more
> apologies for any indentation errors):
> Class Model:
>rooms= {}
>for z in range(num_of_zones):
>for i in range(24):
>tmp[i] = { VAR:0, SD:0, AVG:0, READINGS:[] }
>tmp[i]['updated'] = datetime.utcnow()
>for j in OT_RANGE:
>tmp[i][j] = { VAR:0, SD:0, AVG:0, READINGS:[] }
>rooms[z] = tmp
>
> In case that gets complicated, I'm looking to store readings based off the
> current hour and current outside temperature. The Model class has other
> variables and functions that it uses to compare and manipulate the data as
> it comes in.
>
> My question is in regards to the storing all this data in a dictionary,
> which makes it easy to reference self.rooms[z][12][85][AVG]; however is
> this better/worse or the same as creating a 'Room' class to store the data?
> Since a 'Room' only contains a large amount of data, but doesn't contain
> any functions, which form of storing the data is considered 'better'?
>
> Thank you,
> Adam
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor
>

If you have functions (or in this case methods) which will be used on a
certain 'objects' data structure, a class representation of the data is the
natural fit. Otherwise, you will need to pass the dictionary around to
various functions and this will be seriously confusing.

However, you probably should consider how to represent that data within a
class body, that is, it is extremely confusing to access data such
as self.rooms[z][12][85][AVG].

Instead, you should break down what the data structure into like-things and
how they are related, for example, you might consider something like this:

class Weather(object):
def __init__(self, temp, precipitation, humidity, bara_pres):
self. temp = temp
self. temp = precipitation
self. temp = humidity
self. temp = bara_pres
def my_func(self, *args,**kwargs):
pass #do stuff here

However, if you need to either further define the datapoints of if you want
the datapoints to be able to "do things" then you could do something like
this:

class Temperature(object):
def __init__(self, temp):
self. temp = temp
self.other_stuff_about_temp = stuff

def my_temp_func(self, *args,**kwargs):
pass #do stuff here


class Weather(object):
def __init__(self, temp, precipitation, humidity, bara_pres):
self. temp =  Temperature(temp)
self.precipitation = precipitation
self.humidity = humidity
self.bara_pres = bara_pres
def my_func(self, *args,**kwargs):
pass #do stuff here

from here you could either put your instantiated objects into a list and do
math on the elements thereof, or you could put them into another class
object like this:

class WeatherOverTime(object):
def __init__(self, my_list):
self.my_list =  my_list

def avg(self, attr): #attr is the attribute you want to take an average
of, so humidity, temp, whatever.
temp_list = map(lambda x: getattr(x, attr), my_list)
return sum(temp_list) / count(temp_list)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How install Pyramid on a Windows 7 computer?

2012-05-31 Thread James Reynolds
I don't think django 1.5 is ready, but they are targeting python3k. There
is a fork of django i think on bitbucket that works as well.
On May 31, 2012 12:33 PM, "Vince Spicer"  wrote:

> Step 1)  install Ubuntu
>
> OK sorry couldn't resist.
>
> This should help.
>
> http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/install.html#installing-pyramid-on-a-windows-system
>
> Vince
>
> On Thu, May 31, 2012 at 10:20 AM, Tamar Osher 
> wrote:
>
>>  Months ago, I learned Python version 3.  I have read a few books, and
>> want to learn how to use Python for the web.  Pyramid is a Python web
>> framework that is ready for Python version 3, but I don't know how to
>> install it on my Windows 7 computer.  Online, there are no Pyramid
>> installation instructions that discuss how to install Pyramid on a Windows
>> 7 computer.  Can someone please help me?
>>
>> from Tamar Osher, emeraldoff...@hotmail.com
>>
>>
>> **
>> *
>>
>>
>>
>> *
>>
>> * *
>>
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] summing lists

2012-04-10 Thread James Reynolds
On Tue, Apr 10, 2012 at 11:22 AM, Hs Hs  wrote:

> Hi:
>
> I have 4 lists:
>
> >>> a
> [40]
> >>> b
> [2]
> >>> c
> [23]
> >>> d
> [12]
>
>
> how is it possible to do add elements in list. I can do this using
> tupples, but I do not know how to append elements to tuple, thats the
> reason I am using list.
>
> I want to find the value of a+c/a+b+c+d - which is 40+23/40+2+23+12.
>
> Any help appreciated.
>
> thanks
> Hs.
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
In python, the '+' operator when applied to lists will concatenate the
lists together. So:

>>> a = [1]
>>> b = [2]
>>> print a+b
[1,2]

the 'sum' function in python can be used on lists.

>>> a = [1]
>>> b = [2]
>>> print sum(a+b)
3
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Lists and While Loops

2012-03-28 Thread James Reynolds
On Wed, Mar 28, 2012 at 2:53 PM, Ricky Brown  wrote:

> So I have to write a program that reads a message from the user and prints
> a new message that contains all the words from the original message but in
> the same order without repeating any of them unless they show up more than
> once in the original message.
>
> What I have thus far looks like this:
>
> message = input("Your message:")
> myList = message.split()
> y = random.choice(myList)
> z = len(myList)
> while z !=0:
> myList.remove(y)
> print(y)
>
> I can't figure out
> 1) How to remove "y" from the list and continue the loop; when I use
> .remove etc. it runs once then give me the error that "y" is not in the
> list.
>
> I imagine the answer is quite simple I'm just getting really frustrated
> trying to get this done any advice is appreciated.
>
> Thanks
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

You have two main issues, one, you are not designing the program to do what
is specified in the directions, and two, the program you did write has a
few things that you need to work on. For the later portion, I've provided
some commentary below in the body of your code that I have copied over.

message = input("Your message:")
myList = message.split()
y = random.choice(myList)

#here you have saved some random choice from your list to the variable y.

z = len(myList)

#Here you save the length of the list to the variable z.

while z !=0:
#the above says, keep doing this loop while z is not equal to 0.
myList.remove(y)
#Here you remove an item from the list, the item stored to the variable
y from above.
#it's important to note that this does not change the value of z and
this does not change the value of y.
print(y)
#y gets printed once

The loop then goes back up and since z has not changed (and in fact never
will change, because you have never told it to change) the while loop runs
through another iteration.

However, once myList.remove(y) is evaluated again for the second time it
throws an error because y is no longer in the list.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] FW: null inputs

2012-03-15 Thread James Reynolds
On Thu, Mar 15, 2012 at 10:32 AM, ADRIAN KELLY wrote:

>
>
> Adrian Kelly
> 1 Bramble Close
> Baylough
> Athlone
> County Westmeath
>
> 0879495663
>
>
>  --
> From: kellyadr...@hotmail.com
> To: tutor@python.org
> Subject: null inputs
> Date: Thu, 15 Mar 2012 14:19:16 +
>
> Hi guys,
> how do i prevent a user from leaving a blank when inputting?
>
> e.g.
> age=int(input("what age are you? ")).. i want to stop the
> user pressing enter
>
> if age==""?
>
>
>   
> age=raw_input("what age are you? ")
> if age=="":
> age=int(age)
> print "please enter your age"
> else:
> print "your age is ",age
>  *
> i have tried this but still no luck, if anyone can help i would
> apprecitate it
>
>
>
> Adrian Kelly
> 1 Bramble Close
> Baylough
> Athlone
> County Westmeath
>
> 0879495663
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

You can't prevent users from entering whatever they feel like it, but you
can prevent your program from processing that input and force them to try
again.

The typical way this is done is through a while loop:

age = ''

while age != ''
age=raw_input("what age are you? ")

this will continue to loop until you give it something other than ''.

Of course, you can build on this, you know, something like:

checker = False

while checker:
age=raw_input("what age are you? ")
try:
age = int(age)
checker = True
except TypeError:
  print "you didn't enter an integer for an age!"
  print "try again!!!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting sql Was: Some help Please

2012-02-15 Thread James Reynolds
On Wed, Feb 15, 2012 at 1:30 PM, Alan Gauld wrote:

> On 15/02/12 18:03, James Reynolds wrote:
>
>  >In you table the acc_id is 'mn0001'
>> >In your sql Acc_ID = 'MN0001'
>> >Why the difference in case?
>>
>> Normally, sql doesn't care about case with respect to table names. I
>> believe in certain implementations they are always lower case, even if
>> you pass an upper.
>>
>
> The issue is not the table (or even column name) its the value within it.
> Comparing 'mn0001' to 'MN0001' will fail.
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>


I think this depends on the settings of the column and what you have set in
your sql statement.

Example:

if ('j' = 'J')
select 'True'
else
select 'False'

This comes out True

if ('j' = 'k')
select 'True'
else
select 'False'

This comes out False

I suppose this could be by implementation, but at least in sql server, I
think Oracle, and maybe some others, you have to set the database (or
column) to case sensitive by changing it through a collation statement.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] formatting sql Was: Some help Please

2012-02-15 Thread James Reynolds
On Wed, Feb 15, 2012 at 12:13 PM, bob gailer  wrote:

> Welcome to python help. We are a few volunteers who donate time to assist.
>
> To assist you better:
> 1 - provide a meaningful subject line - such as "formatting sql"
> 2 - tell us what OS and Python version you are using.
> 3 - what is your prior Python experience?
>
>
> On 2/15/2012 9:17 AM, JOSEPH MARTIN MPALAKA wrote:
>
>> take an example of updating Bank Accounts,
>> gaving the following table:
>>
>> acc_id  acc_namestanding_Balance
>> mn0001  computer 2
>>
>> my problem is how can i credit the standing balance from user data,as
>> in making a deposit onto the computer account, using the code below:-
>>
>>
>>
>> import MySQLdb as mdb
>> import sys
>>
>> con = mdb.connect('localhost', 'joseph', 'jmm20600', 'savings');
>>
>> dep = input('Enter Amount: ')
>>
>> cur.execute("UPDATE accounts SET Standing_Amount =
>> (Standing_Amount + dep) WHERE Acc_ID = 'MN0001'")
>>
> In you table the acc_id is 'mn0001'
> In your sql Acc_ID = 'MN0001'
> Why the difference in case?
> Why the () around Standing_Amount + dep?
>
>
>>conn.commit()
>>
>> HOw do i format "dep" in order to be added onto the standing_Amount,to
>> make an increment?
>>
>> Please, is it the same thing with the withdrawing format, in case i
>> want to decrement the account as in withdrawing??
>>
>>
>> joseph
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>
> --
> Bob Gailer
> 919-636-4239
> Chapel Hill NC
>
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor
>


Normally, sql doesn't care about case with respect to table names. I
believe in certain implementations they are always lower case, even if you
pass an upper.

The problem, as Bob pointed out above, cur.execute("UPDATE accounts SET
Standing_Amount =
(Standing_Amount + dep) WHERE Acc_ID = 'MN0001'")

here, specifically, (Standing_Amount + dep)

Sql isn't going to have any idea what "dep" is when passed, because it is
going to see a string called "Dep". Well, it will know what it is, it will
be a string and will through an error that it can't add a string and
integer.
When i want to update a value in sql, normally i extract to python, do the
math there, and then update. You can do this in sql if you prefer and I'm
sure there are good reasons for doing it, I'm just more comfortable working
in python than I am sql.

Also, when passing variables to SQL, if you are doing raw queries and not
using some ORM, I would get used to using the "?" within the sql string and
then passing your variables in the following list. Otherwise, you are going
to leave yourself open to injection attacks (provided you are doing direct
string manipulations).

To do this in sql, you need to run a select statement first, saving the
results to a @variable. use that @variable later (after passing in an
integer) to add the two numbers.

To do this in python, also run a select statement, save it to some python
variable. Add your new result to it, and send that new result along to the
DB using your update query.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] decimal precision in python

2012-02-06 Thread James Reynolds
On Mon, Feb 6, 2012 at 10:25 AM, Kapil Shukla wrote:

> i tried writing a small code to calculate option price using the binomial
> tree model. I compared my results with results of the same program in
> excel. There seems to be a minor difference due to decimal precision as
> excel is using 15 decimal precision and python (both 2.7 and 3.1) using 11.
> (at least that's what shown on shell)
>
> can some one guide me whats the equivalent of using a double datatype on
> python and i can't use long() in 3.1 any more.
>
> Please also suggest a free editor for python which can at least repeat
> previous command with a key stroke
>
> regards
> kapil
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
Have you looked into the decimal module? (you need to import decimal)

http://docs.python.org/library/decimal.html

You can specify the amount of precision needed.

Also, i would suggest using 3.2, if it's not too late in your project.

As for editors, I hear VIM is good. I use Eclipse as an IDE personally.
People seem to have some fairly definite ideas on what editor other people
should use, bordering on religious fanaticism.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using Python for a client interactive map application

2012-01-05 Thread James Reynolds
On Thu, Jan 5, 2012 at 10:58 AM, Alexander  wrote:

> Dear friends,
> I'm emailing regarding a general question about working with Python and a
> web-browser based interactive map application. Over the summer I had asked
> a similar question and heard some things about the Django framework, does
> anybody have any other suggestions? For example there is a server with all
> the info about a map, and from a browser a user will be able to view and
> interact with the map at high speeds.
> And please remember to reply to all.
> Thanks,
> --
> Alexander
> 7D9C597B
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

Django will (most likely) do what it is you want it to do, but you will
also need some javascript. For my current project, I'm using JQuery, but I
happen to know that Dojo has an interactive
mapfeature
in their toolset, so I would check that out dojo.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with script

2011-12-27 Thread James Reynolds
On Tue, Dec 27, 2011 at 8:31 PM,  wrote:

> hello, my name is nick. i got python for software design by Allen B.
> Downey as a gift for christmas. i am completely new to programming and i am
> having trouble figuring out how to do an exercise concerning script..
> my problem
> 5
> x=5
> x+1
> im ok when it comes to using python so far. but it has asked me to put the
> problem into a script and run it. my question is how do i put that problem
> into a script and then how do i run it in python. im learning by myself at
> home so im having trouble figuring this out on my own. my os is win 7 i
> have python 2.7
> sorry about punctuation!
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
Follow these steps:

1. Start
2. All Programs
3. Python > Python 2.7 This will open "Python Shell"
4. Go to File, New window
5. A new window (untitled) will open. Save this to your desktop. Call it
"test" or "box" or "cloud"
5. You can now write python to a file. Go ahead and try it. You will need
to save it before you run it.
6. Do this by pressing F5 or by going up to run (after you save)

For example, by running this:

x=5
print x
print x+1
print x


will print this in the shell:

>>>
5
6
5
>>>

You can also just run from the shell itself, but I mostly use this for
simple one liners and stuff (which is what you are doing above)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A few Python Mysteries

2011-12-20 Thread James Reynolds
On Tue, Dec 20, 2011 at 9:32 PM, Wayne Watson
wrote:

> I changed Python25 to Python27, and rebooted.  I got the same two dll msgs
> again.
>
>
> On 12/19/2011 7:33 PM, Wayne Watson wrote:
>
>> It became apparent during the other part of this thread that I had not
>> uninstalled Python 2.7, as I thought I had.  As pointed out in the PATH
>> discussion (James R.), the last item in the system variable PATH was
>> Python25. I would think then changing it to Python27 might Python rolling
>> again.
>>
>>
> --
>   Wayne Watson (Watson Adventures, Prop., Nevada City, CA)
>
> (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
>  Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet
>
> CE 1955 October 20 07:53:32.6 UT
>-- "The Date" The mystery unfolds.
>
>Web 
> Page:http://www.speckledwithstars.net/>
> >
>
>
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor
>

Did you also verify that Python is installed at C:\Python27 and not some
other place?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A few Python Mysteries

2011-12-19 Thread James Reynolds
On Mon, Dec 19, 2011 at 2:21 PM, Wayne Watson
wrote:

>
>
> On 12/19/2011 8:50 AM, James Reynolds wrote:
>
>
>
> On Mon, Dec 19, 2011 at 11:35 AM, Wayne Watson <
> sierra_mtnv...@sbcglobal.net> wrote:
>
>> Win 7, 64-bit
>>
>> I had Py 2.5 installed on my PC earlier this year, and it began failing
>> around June. I finally ...
>>
>> CE 1955 October 20 07:53:32.6 UT
>>-- "The Date" The mystery unfolds.
>>
>>Web Page:
>>
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
>
>
>
>  Did you change the PATH to the right directory? It may still be pointing
> to the old directory, or you may have never set it to begin with.
>
> Someone suggested this several months when I was having an install problem.
> ===
> That being said, it sounds an awful lot like the python.exe isn't in your
> path. To get it there you can open windows explorer (WIN+E) right click on
> computer > properties then click advanced system settings. In the window
> that pops up, click the "environment variables" button. In the "system
> variables" portion, find the path variable and click the "Edit..." button.
> Assuming that your new installation was placed in C:\Python25\ you will
> want to add ";C:\Python25\" (the semicolon is important!) to the end of
> your path.
> ===
> Is that what you are suggesting? I brought up WE and clicked on
> properties, and got a six tab dialog.  Pushed Advanced. Tabs are: Sharing,
> Security, Prev versions, general, tools, h/w, quota. I don't see anything
> about  about a PATH, sys or env vars.
>
> --
>Wayne Watson (Watson Adventures, Prop., Nevada City, CA)
>
>  (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
>   Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet
>
>  CE 1955 October 20 07:53:32.6 UT
> -- "The Date" The mystery unfolds.
>
> Web Page: 
>
>
>
>  In windows 7,

1. Go to start
2. Right click on "Computer"
3. Select Properties. This will bring up the "System" menu.
4. Select "Advanced system Settings" on the left hand side.
5. In this new window, select Environment variables... at the bottom
6. In the bottom window area, scroll down until you find "PATH"
7. Select "Edit" (do NOT delete anything contained in this or will screw
some stuff up)
8. scroll to the very end and put a ; as a deliminator if there isn't one
on the end already. Then put the direct path to you Python install you care
about. (it should be something like this:(;C:\Python27) - this is mine in
fact.
9. Hit OK. Then accept your way out. You will have to reboot.
10. To test, open a cmd prompt and and type simply "python". if you get
Python 2.7.2 (some more stuff) then python is now on your path.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A few Python Mysteries

2011-12-19 Thread James Reynolds
On Mon, Dec 19, 2011 at 11:35 AM, Wayne Watson  wrote:

> Win 7, 64-bit
>
> I had Py 2.5 installed on my PC earlier this year, and it began failing
> around June. I finally uninstalled it, and tried 2.6.  Still had problems
> that centered around getting to IDLE. Uninstalled 2.6, and went to 2.7.
> Same problem. I completely uninstalled 2.7. I do have several folders of py
> programs. No Python.
>
> After that episode, I began to notice the following messages when I signed
> on to my PC after a boot. I do not bring my PC down very often.
>
> Specified module could not be found: Loadlib python.dll failed, and
> another of the same for Python25.dll failed (maybe not found).  I did a
> search for both, but neither were found.
>
> I ignored this inconvenience for a few weeks, and had developed a need to
> copy a particular python program on Win 7 to another computer. Call it
> abc.py.  I copied it to a thumb drive, and plugged the drive into the other
> PC, which has Python on it.  abc.py was missing from the drive.  I tried
> this about three times, and even went to yet another PC. No abc.py.
>
>  Finally, I pulled xyz.py from an XP PC on to the drive. When I put it on
> yet another PC, xyz.py was there, and I copied it on to the PC. Very
> strange.  Note again, I did not have Python installed on the Win 7 PC.  I
> have no idea if any of this is relevant to the attempt to install Py on my
> Win 7 PC, but it and the sign-on msgs may indicate something is twisted in
> the registry.
>
> Comments?
>
> It would be nice to get rid of the two msgs upon sign-on.
>
> --
>   Wayne Watson (Watson Adventures, Prop., Nevada City, CA)
>
> (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
>  Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet
>
> CE 1955 October 20 07:53:32.6 UT
>-- "The Date" The mystery unfolds.
>
>Web 
> Page:http://www.speckledwithstars.net/>
> >
>
>
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor
>




Did you change the PATH to the right directory? It may still be pointing to
the old directory, or you may have never set it to begin with.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need Explanation...

2011-12-12 Thread James Reynolds


Sent from my iPad

On Dec 12, 2011, at 7:08 AM, "Homme, James"  wrote:

> Hi,
> Alan said:
> Because app() returns the result of append().
> But append() returns None, since it modifies the list in place.
> 
> This is one of the few features of Python I dislike. It would not have been 
> difficult to make these modifier methods return the thing modified.
> This style would then allow chained methods.
> 
> We do it with strings:
> 
> "foobar is a string".rstrip('ing').upper()
> 
> because strings are immutable. But we could have done it with other sequence 
> types too. Sadly we didn't and history/tradition leaves us with these 
> counterintuitive modifiers that return None. It catches everybody out at some 
> point...
> 
> 
> Is that the same problem with using the len function on sequences and open on 
> files, or is it different?
> 
> Thanks.
> 
> Jim


But a python list is mutable. I'm hardly an expert, but the idea is you are 
modifying the list. Why would you create another copy of the same list via a 
return statement?

At it's fundamentals python is really an object oriented language. When you use 
append, extend, pop, sort, etc on the list you retain the object but change 
some of the attributes stored in the object. Your string example isn't 
analogous because they are, as you noted, immutable.

I don't see this as a weakness but a strength. It cuts back on confusion and 
extraneous variables. 

Your example of Len also doesn't apply. It isn't modifying anything. It's 
returning the length of the list, in this case. You change nothing.

Open, if I recall, creates a file object in the same way class A:  a = A() 
creates an instance of A.

But like I said I'm not an expert.







> -Original Message-
> From: tutor-bounces+james.homme=highmark@python.org 
> [mailto:tutor-bounces+james.homme=highmark@python.org] On Behalf Of Alan 
> Gauld
> Sent: Saturday, December 10, 2011 4:16 AM
> To: tutor@python.org
> Subject: Re: [Tutor] Need Explanation...
> 
> On 10/12/11 07:41, sunil tech wrote:
> 
>> /def app(x):/
>> / return x.append(100)/
>> /
>> /p = app(a)/
>> /
>> /now list holds appended value [1,2,3,100]/
>> /but p is empty... why it is?/
> 
> Because app() returns the result of append().
> But append() returns None, since it modifies the list in place.
> 
> This is one of the few features of Python I dislike. It would not have
> been difficult to make these modifier methods return the thing modified.
> This style would then allow chained methods.
> 
> We do it with strings:
> 
> "foobar is a string".rstrip('ing').upper()
> 
> because strings are immutable. But we could have done it with other
> sequence types too. Sadly we didn't and history/tradition leaves us with
> these counterintuitive modifiers that return None. It catches everybody
> out at some point...
> 
> 
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> 
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> 
> This e-mail and any attachments to it are confidential and are intended 
> solely for use of the individual or entity to whom they are addressed. If you 
> have received this e-mail in error, please notify the sender immediately and 
> then delete it. If you are not the intended recipient, you must not keep, 
> use, disclose, copy or distribute this e-mail without the author's prior 
> permission. The views expressed in this e-mail message do not necessarily 
> represent the views of Highmark Inc., its subsidiaries, or affiliates.
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] print method name

2011-12-08 Thread James Reynolds
On Thu, Dec 8, 2011 at 9:49 AM, rail shafigulin
wrote:

> i created a class and in some instances when i use it call some of its
> methods i need to print a method name. the online search did produce some
> results but none of them seem to work for me. for example one of them said
> just to use __name__ or func_name but it didn't work for me. i'm using
> python 3.1.1
>
> any help is appreciated.
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
Can you show the code?

This works for me:

class A(object):
def __init__(self):
pass

def addr(self,a,b):
return a + b

a = A()
print a.addr.__name__

>>addr
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pass tuples to user defined function(beginner)

2011-11-28 Thread James Reynolds
On Mon, Nov 28, 2011 at 12:32 PM, Mayo Adams  wrote:

> I am trying to pass a set of tuple strings from a file to a function I
> have defined.  Each tuple is on a separate line, and looks something
> like this:
>  ('note',2048)
> The function has two parameters , and is defined thus: def
> findindex(dval,ticks):
> Apparently, I need to cast the second value as an integer in the body
> of the function in order to work with it as such, but when I attempt
> int(ticks) I get
> ValueError: invalid literal for int() with base 10: '2048)'
>
> Upon searching for elucidation of this on the internet I find nothing
> but esoterica, at least as far as I am concerned.
> Any pointers would make me happy.
>
> --
> Mayo Adams
>
>
>
> mayoad...@gmail.com
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



Your problem is in the error message:

ValueError: invalid literal for int() with base 10: '2048)'

observer, Python tells you this isn't a number: '2048)'

Indeed, this is correct, because you '2048)' is not a number.

What you really want to pass to '2048', which int('2048')

can understand just fine.

So, trim off the parenthesis, or something.

Alternatively, since you aren't actually passing a "tuple" but something
that looks like a python tuple as a string, you could eval it:

a = "('note',2048)"
b = eval(a)

print a, type(a), b, type(b)

>> ('note',2048)  ('note', 2048) 

In working with the second, you do normal tuple operations, like b[1] to
access that index

When passing to a function, you do this: findindex(*b)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to shorten this code using classes?

2011-11-23 Thread James Reynolds
On Wed, Nov 23, 2011 at 10:35 AM, Mic  wrote:

> Hi.
> I have written a simple GUI program. It works just like it is intended to
> do, but there
> is a problem, I feel like I could make it shorter. I thought of using
> classes instead of
> doing it the way I have done.
>
> Here is my code:
>
> from tkinter import*
>
> button1_color="green"
> button1_value=False
>
> button2_color="green"
> button2_value=False
>
>
> class Window(Frame):
>   def __init__(self,master):
>   super (Window,self).__init__(master)
>   self.grid()
>   self.create_widgets()
>
>   def create_widgets(self):
>
>   #Creates hello button1
>   self.hello_bttn1=Button(self,**bg=button1_color, text="Hi_1",
> command=self.button1_clicked)
>   self.hello_bttn1.grid()
>
>   #Creates hello button2
>   self.hello_bttn2=Button(self,**bg=button2_color, text="Hi_1",
> command=self.button2_clicked)
>   self.hello_bttn2.grid()
>
>
>
>   def button1_clicked(self):
>   """ This method runs if button one is clicked"""
>
>   def change_button1_value():
>   global button1_value
>   button1_value=not button1_value
>
>   change_button1_value()
>
>   if button1_value:
>
>   self.hello_bttn1.configure(bg=**"red", text="Hi_2")
>
>   def change_button1_color_red():
>   global button1_color
>   button1_color=("red")
>   change_button1_color_red()
>
>
>
>
>   else:
>   self.hello_bttn1.configure(bg=**"green", text="Hi_1")
>
>
>
>
>   def change_button1_color_green():
>   global button1_color
>   button1_color=("green")
>   change_button1_color_green()
>
>   #-**
>
>   def button2_clicked(self):
>   """This method runs if button two is clicked"""
>
>   def change_button2_value():
>   global button2_value
>   button2_value=not button2_value
>
>   change_button2_value()
>
>   if button2_value:
>
>   self.hello_bttn2.configure(bg=**"red", text="Hi_2")
>
>
>
>   def change_button2_color_red():
>   global button2_color
>   button2_color=("red")
>   change_button2_color_red()
>
>
>
>
>   else:
>   self.hello_bttn2.configure(**text="Hi_1", bg="green")
>
>
>
>
>   def change_button2_color_green():
>   global button2_color
>   button2_color=("green")
>   change_button2_color_green()
>
>
>
>
> As you can button1_clicked and button2_clicked are very similiar. Imagine
> that I would use more buttons than just the two that I am using now.
>
> It would be a lot of functions then, one for each button. How do I
> accomplish
> the same thing as my code does now, but using one function for all buttons
> instead of one function for each button? Is it possible?
>
> I hope these questions aren't stupid.
>
> Thank you for your time!
>
>
> Mic
>
>
>
>
>
>
>
>
>
>
>
>
>
>
> root=Tk()
> root.title("Test")
> root.geometry("200x200")
> app=Window(root)
> root.mainloop()
>
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor
>








Button 1 and Button 2 already are classes, so unless you need to subclass,
you are simply being redundant.

A couple things first: don't use globals all over the place unless you want
to have a serious headache.

You have a wicked about of redundancy in your code, you don't need an
object oriented approach to condense, but it can be helpful at times.

However, as far as your question. For the two functions, you could subclass
Button and add them to your new Button object:

(untested)


class MyButton(Button):
button_color="green"
button_value=False

def __init__(self, *args, **kwargs):
super(Button, self).__init__(*args, **kwargs)

def change_value_and_color(self):
self.button_value = not self.button_value
if self.button_value:
self.button_color="red"
self.configure(bg=self.button_color, text="Hi_2")
else:
self.button_color="green"
self.hello_bttn1.configure(bg=self.button_value, text="Hi_1")

def button_clicked(self):
""" This method runs if button one is clicked"""
self.change_value_and_color()


I left in the button_clicked method, but as you can see it is utterly
pointless to have it. Just rename your first function and call it directly.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] IndexError: list index out of range

2011-11-21 Thread James Reynolds
On Tue, Nov 22, 2011 at 12:28 AM, John  wrote:

>
> Hi all,
>
> I have wriiten the following code:
> [Segment]
>
>   def survivor(names, step):

>>>index = step - 1
>next = names
>while len(next)>  1:
>next.remove (next[index])
>
>
>
> However when ever i run it i get this error message:
>
> Traceback (most recent call last):
>  File "", line 1, in
>survivor(["Andrew", "Brenda", "Craig", "Deidre", "Edward",
> "Felicity", "Greg", "Harriet"], 4)
>  File "", line 5, in survivor
>next.remove (next[index])
> IndexError: list index out of range
>
> Any ideas about whats causing this error?
>
> Big thanks,
>
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor
>


I don't really know what it is you are trying to achieve, but I can tell
you this, if you add a print statement you can see very clearly why you are
getting the error:

def survivor(names, step):
index = step - 1
next = names
while len(next)>  1:
print next, index
next.remove (next[index])
survivor(["Andrew", "Brenda", "Craig", "Deidre", "Edward",
"Felicity", "Greg", "Harriet"], 4)


['Andrew', 'Brenda', 'Craig', 'Deidre', 'Edward', 'Felicity', 'Greg',
'Harriet'] 3
['Andrew', 'Brenda', 'Craig', 'Edward', 'Felicity', 'Greg', 'Harriet'] 3
['Andrew', 'Brenda', 'Craig', 'Felicity', 'Greg', 'Harriet'] 3
['Andrew', 'Brenda', 'Craig', 'Greg', 'Harriet'] 3
['Andrew', 'Brenda', 'Craig', 'Harriet'] 3
['Andrew', 'Brenda', 'Craig'] 3
Traceback (most recent call last):
  File "C:\Users\user\workspace\pricing\pricing\pricer\tests.py", line 40,
in 
"Felicity", "Greg", "Harriet"], 4)
  File "C:\Users\user\workspace\pricing\pricing\pricer\tests.py", line 38,
in survivor
next.remove (next[index])
IndexError: list index out of range


As you can see in this line: ['Andrew', 'Brenda', 'Craig'] 3

It looks for index "3" and there isn't one, so it throws an error. The
indexes available are 0,1 and 2.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of objects?

2011-11-15 Thread James Reynolds
On Tue, Nov 15, 2011 at 8:40 AM, Elwin Estle wrote:

> I am attempting to write a text based spider solitaire game.  I have  a
> pretty simple card class, and a deck class, which has a list of card
> objects, which are shuffled, then individual elements are put into
> self.dealt, which is a 'list of lists' when the cards are dealt.
>
> I am trying to control the visibility of the cards.  There is a small
> "for" loop in the "deal" method of the deck class, this is intended to
> toggle the visibility of four of the cards.  It does that just fine, but
> for some reason, it seems to be randomly toggling the visibility of other
> cards in the self.dealt list and I am thoroughly confused as to why that
> is.  Is it something to do with the way objects are referenced?  Is my list
> of card objects a bad way to approach this?
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


A few thoughts first:

class Card(object):

def __init__(self):
self.value = ''
self.display = 'X'

I would change the above to:

class Card(object):

def __init__(self, value):
self.value = value
self.display = 'X'

(because you always have a card with a value)

Which allows you to save a line here:

for value in values:
card = Card(value)
card_list.append(card)

like that

Another idea would be to use "extend" here:

values = []

for i in range(1, 11):
values.append(str(i))

values.append('J')
values.append('Q')
values.append('K')

So, you would do something like this instead:

mylist = range(1, 11)
mylist.extend(['J', 'Q', 'K'])

for i in mylist:
values.append(str(i))

What extend does is it extends one list with another list.

Also, you can build the string conversion into the card class:

Further saving you the above loop:

class Card(object):

def __init__(self, value):
self.value = str(value)
self.display = 'X'

and then in the create_cards def:

mylist = range(1, 11)
mylist.extend(['J', 'Q', 'K'])

#for i in mylist:
#values.append(str(i))

for value in mylist:
card = Card(value)
card_list.append(card)


(as an aside, I'm not sure why you do this:

card_list = card_list * 8

if you need two decks, I think you should have a variable like 4*decks so
you can shuffle the right amount of decks)

I don't think you need to shuffle twice here (which in turn calls into
question why you need a separate method, but maybe you were going to build
on it - i do that all the time):

def shuffle(self):
random.shuffle(self.cards)
#random.shuffle(self.cards)


Now onto your question:

You can see that there are four card values that are shown visible in any
given run. There are always four values and they are always random from run
to run.

If you comment out this loop

#for index, card in enumerate(self.dealt[5]):
#print index, card
#self.dealt[5][index].display  = self.dealt[5][index].value

You won't get that anymore.

If you want to control whether to display any particular card or not, I
would add a variable to the display_cards method:

def display_cards(self, display = True):

for row in self.dealt:
for card in row:
if display:
print '%5s ' % card.display,
else:
print '%5s ' % card.value,
print ''

Or you can add another value to the card class, if you want to control the
display of cards on a unique basis:

class Card(object):

def __init__(self, value):
self.value = str(value)
self.display = 'X'
self.display_or_value = True

then you can change your method above to be:

def display_cards(self):

for row in self.dealt:
for card in row:
if card.display_or_value:
print '%5s ' % card.display,
else:
print '%5s ' % card.value,
print ''


Long story short, if I wanted to control the visibility of any card, I
would do it within the Card class (since presumably that is an attribute of
any given card - think about it in real life, a card can be up, or a card
can be down, yet it still retains its other properties, like color, value,
creases, etc)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] range question

2011-09-22 Thread James Reynolds
On Thu, Sep 22, 2011 at 11:08 AM, Steven D'Aprano wrote:

> Joel Knoll wrote:
>
>> Given a range of integers (1,n), how might I go about printing them in the
>> following patterns:
>> 1 2 3 4 ... n2 3 4 5 ... n 13 4 5 6 ... n 1 2 etc., e.g. for a "magic
>> square". So that for the range (1,5) for example I would get
>>
>> 1 2 3 42 3 4 13 4 1 24 1 2 3
>>
>
>
> I'm not sure what you want, because the formatting is all broken in
> Thunderbird. Your "magic square" looks more like a straight line.
>
> I'm going to take a wild stab in the dark and *guess* that you want
> something like this:
>
>
> 1 2 3 4
> 2 3 4 1
> 3 4 1 2
> 4 1 2 3
>
> Look at the pattern: each row is the same as the previous row, except the
> first item is moved to the end. You can move an item from the front to the
> end with pop() to delete it, and append() to re-add it.
>
> There are the same number of rows as columns. Putting this together:
>
>
> n = 4  # number of columns
> row = range(1, n+1)
> for row_number in range(n):
># print the row without commas and []
>for item in row:
>print item,  # note the comma at the end
>print  # start a new line
># Pop the first item from the list, then add it to the end.
>x = row.pop(0)
>row.append(x)
>
>
>
> --
> Steven
>
>
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor
>


An easier way to print without the comma, assuming 2.6 or 2.7 is to add
this:

 from __future__ import print_function

and then print like this:

print(*a)

or if you are already using python 3.0+ you just print like that without the
import.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] range question

2011-09-22 Thread James Reynolds
On Thu, Sep 22, 2011 at 10:27 AM, Joel Knoll  wrote:

>  Given a range of integers (1,n), how might I go about printing them in the
> following patterns:
>
> 1 2 3 4 ... n
> 2 3 4 5 ... n 1
> 3 4 5 6 ... n 1 2
>
> etc., e.g. for a "magic square". So that for the range (1,5) for example I
> would get
>
> 1 2 3 4
> 2 3 4 1
> 3 4 1 2
> 4 1 2 3
>
> I just cannot figure out how to make the sequence "start over" within a
> row, i.e. to go from 4 down to 1 in this example.
>
> I have been grappling with this problem for 2.5 days and have gotten
> nowhere!
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

I would probably do something like this:

a = [1,2,3,4]
> print a
> b = a.pop(0)
> a.append(b)
> print a


Probably an easier way of doing it though.

If you wanted to do that four times:

for item in a:
> print a
> b = a.pop(0)
> a.append(b)




You just need to think of it as a register and shifting bits left or right
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] databases

2011-09-10 Thread James Reynolds
On Sat, Sep 10, 2011 at 3:39 PM, Andre' Walker-Loud wrote:

> Hi All,
>
> I am completely new to databases as well as using python to access/create
> databases.  I started googling about it and found so much info, I wasn't
> sure where to begin to answer my first question.  So I thought I would query
> this group by asking a question I am sure has been asked before - but you
> all are so friendly, I thought I would give it a try.
>
> I have databases (many of them) which I want to manipulate, averaging data,
> merging databases, etc.
>
> Do I need to install separate modules to access the databases?
>
> Do I need to know the specific style the databases were created in to open
> manipulate them with python (2.7)?  I ask this because with xml files, I was
> able to just use
>
> from xml.dom import minidom
>
> and then by trial and error in an interactive session, I could figure out
> how to walk through the xml file to find what I wanted.  I am wondering if I
> can do something similar with a database, or if there are more pre-defined
> formats.  I do not actually know what format my databases are in (someone
> else wrote the c-code to create them).
>
>
> While waiting for suggestions, I have started to read Alan Gauld's tutorial
> on the subject
>
> http://www.alan-g.me.uk/tutor/index.htm
>
>
>
> Thanks,
>
> Andre
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


What type of databases? sql server, mysql, sqllite?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] need advice about a dictionary ({})

2011-09-08 Thread James Reynolds
On Thu, Sep 8, 2011 at 10:03 AM, Alan Gauld wrote:

> On 08/09/11 11:58, Richard D. Moores wrote:
>
>> I've succeeded in writing a dictionary ({}) that I can use as a small
>> personal phone book. The dictionary (very shortened and simplified)
>> looks like this in the script;
>>
>> p = {}
>>
>> p['bp1'] = 'xxx'
>> p['bp2'] = 'ooo'
>> p['ch'] = 'zzz'
>> p['me'] = 'aaa'
>> p['mg'] = 'vvv'
>> p['pu1'] = 'bbb'
>> p['pu2'] = 'ccc'
>> p['pw'] = 'kkk'
>>
>>
> You could have done that in one line if you preferred:
>
> > p = {
>  'bp1':'xxx',
>  'bp2':'ooo'
>   etc/...
>  'pw':'kkk'
>
> }
>
>
>  But I'd like to put the lines of the dictionary in a text file so that
>> I can add key/value items to it by writing to it with another script.
>>
>
> Consider using a shelve (See the shelve module)
> It is basically a file that you can treat as a dictionary...
>
> Try:
>
> >>> import shelve
> >>> help(shelve)
>
> For examples and info.
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor
>



Another option would be for you to use XML and base it off of a schema.

There's a really nifty tool called generate DS (just google it) that will
turn any valid schema into a python module.

I pasted an example schema that you might use here:
http://pastebin.com/AVgVGpgu

 Once you install generateds, just cd to where it is installed and type:
python generateds.py -o pn.py PhoneNumber.xsd

This assumes you named the above schema as PhoneNumber.xsd

That will create a file called pn.py. For some reason it generated a bad
line on line 452, which I just commented out.

I then made a script in just a few lines to make a phonebook:

http://pastebin.com/h4JB0MkZ

This outputs XML that looks like this:


> 
> aaa
> 
> 1231231234
> 
> 
> 
> bbb
> 
> 1231231234
> 
> 
> 6789231234
> 
> 
> 
> ccc
> 
> 1231231234
> 
> 
> 
> ddd
> 
> 1231231234
> 
> 
> 


The advantage is, you can immediately grab the generated xml and create
python instances using the build() method for further editing. You would of
course need to create a schema that fits your needs. Mine was just a quick
and dirty example of what you could do.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 'function' object has no attribute 'writer'

2011-09-05 Thread James Reynolds
On Mon, Sep 5, 2011 at 12:08 PM, Susana Iraiis Delgado Rodriguez <
susana.delgad...@utzmg.edu.mx> wrote:

> I want to write a csv file, but I need the final user to give me some
> values to open and update the file. My code is:
> from Tkinter import * #Llamo las librerias graficas de Tk
> import tkSimpleDialog #Libreria de almacenamiento de dialogos
> import tkMessageBox #Libreria de mensajes
> import tkFileDialog
> import sys, os, csv, time, socket, stat
> from osgeo import ogr,gdal,osr
> from osgeo.gdalconst import *
> from PIL import Image
> dir = ""
> extn = ""
> csv_name = ""
> def directorio():
>  global dir
>  print 'Seleccione directorio donde empezar'
>  dirname =
> tkFileDialog.askdirectory(parent=root,initialdir="/",title='Selecciona la
> ruta a escanear')
>  if len(dirname ) > 0:
>   print "You chose %s" % dirname
>  dir = dirname
> def extension():
>  global extn
>  print "Escribe la extension que necesitas buscar"
>  ext=tkSimpleDialog.askstring('Extension a buscar:','')
>  print 'Buscando archivos: ',ext
>  extn = ext
> def csv():
>  global csv_name
>  print "Nombre del csv a crear"
>  inv=tkSimpleDialog.askstring('Nombre de .csv:','')
>  print 'Archivo de salidad: ',inv
>  csv_name = inv
> def boton4():
>  print 'Iniciando...'
>  gdal.AllRegister()
>  file_list = []
>  folders = None
>  for root, folders, files in os.walk(dir):
>   file_list.extend(os.path.join(root,fi) for fi in files if
> fi.endswith(extn))
>  f = open(csv_name, 'wb')
>  log = open ('log_errores.txt','w')
>  writer = csv.writer(f)
> ... more code
> But when I run it,console shows:
> Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 b
> win32
> Type "help", "copyright", "credits" or "license" for more informa
> >>> import win
> >>> Seleccione directorio donde empezar
> You chose C:/
> Escribe la extension que necesitas buscar
> Buscando archivos:  .shp
> Nombre del csv a crear
> Archivo de salidad:  gui.csv
> Iniciando...
> Exception in Tkinter callback
> Traceback (most recent call last):
>   File "C:\Python26\lib\lib-tk\Tkinter.py", line 1410, in __call_
> return self.func(*args)
>   File "win.py", line 43, in boton4
> writer = csv.writer(open(csv_name, 'w'))
> AttributeError: 'function' object has no attribute 'writer'
> I read a tutorial and csv has a writer function, I'm lost
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


You have a function called "csv()" in your code.

So when you go csv.blahbittyblob, you've overriden your imported module
called "csv" with the function called "csv", python then tries to look up
the attribute blahbittyblob and can't find it. it then throws an error.

Change your csv function to be csvx() or _csv or something other than csv
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is there a test for hashability?

2011-09-01 Thread James Reynolds
On Thu, Sep 1, 2011 at 11:37 AM, Hugo Arts  wrote:

> On Thu, Sep 1, 2011 at 5:28 PM, Richard D. Moores 
> wrote:
> > Thanks, James, from your ideas I've come up with this function as a
> > general test for hashibility of any object:
> >
> > def is_hashable(object):
> >try:
> >if hash(object):
> >return True
> >except TypeError:
> >return False
> >
> > But is it?  It returns True for ints, floats, sets, tuples, strings,
> > functions; and False for lists
> >
> > Dick
>
> Are you sure? In my testing it returns False for sets, but True for
> frozensets as it should.
>

I agree with hugo, I just tested with all of these:

a = 'a'
b = []
c = 1
d = ()
e = set()
f = frozenset()

it gave the correct response for each

a = 'a' - True
b = [] - False
c = 1 - True
d = () - True
e = set() - False
f = frozenset() - True
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is there a test for hashability?

2011-09-01 Thread James Reynolds
On Thu, Sep 1, 2011 at 10:32 AM, Richard D. Moores wrote:

> The glossary defines "hashable" as:
>
> hashable
> An object is hashable if it has a hash value which never changes
> during its lifetime (it needs a __hash__() method), and can be
> compared to other objects (it needs an __eq__() method). Hashable
> objects which compare equal must have the same hash value.
>
> Hashability makes an object usable as a dictionary key and a set
> member, because these data structures use the hash value internally.
>
>
> All of Python’s immutable built-in objects are hashable, while no
> mutable containers (such as lists or dictionaries) are. Objects which
> are instances of user-defined classes are hashable by default; they
> all compare unequal, and their hash value is their id().
>
> I'm trying to write a general test for hashability. How can I test if
> an object has both a  __hash__() method and an __eq__() method?
>
> Thanks,
>
> Dick Moores
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



To test for a method within any object you can just go like this:

>>> a = ()
>>> type(a)

>>> if '__hash__' in dir(a): print True
True
>>> if '__eq__' in dir(a): print True
True
>>>

But, I think the method you are approaching it from will only test for
hashability. For example, you could do this:

>>> a = []
>>> type(a)

>>> if '__hash__' in dir(a): print True
True
>>> if '__eq__' in dir(a): print True
True
>>>

and then do this:

>>> b = []
>>> c = {b:1}

Traceback (most recent call last):
  File "", line 1, in 
c = {b:1}
TypeError: unhashable type: 'list'

here is the dir for a list (not hashable):

>>> dir(b)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
'__delslice__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__',
'__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__',
'__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__',
'__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append',
'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

here is the dir for a tuple (hashable):

>>> dir(())
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__',
'__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__',
'__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__', 'count', 'index']

What I would probably do though is use the built in method hash

so you could do something like this:

>>> a = 'a'
>>> b = ()
>>> c = []
>>> print type(a), type(b), type(c)
  
>>> print hash(a)
-468864544
>>> print hash(b)
3527539
>>> print hash(c)

Traceback (most recent call last):
  File "", line 1, in 
print hash(c)
TypeError: unhashable type: 'list'
>>>


You can then use try, except to catch it on an as needed basis.

Not sure if this answers the question you are asking though.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with 'organization'

2011-08-25 Thread James Reynolds
On Thu, Aug 25, 2011 at 1:51 PM, John  wrote:

> Hello, I am writing a module that will have two classes ('runners') I
> am calling them, as they will ultimately use subprocess to run a
> command line program, so they are basically option parsers, etc...
>
> As I wrote the second 'runner', I realized many of the methods are
> going to be the same as the first, so I would actually like to create
> a third class that has the methods which are mutual between the two.
> The problem are the 'self' calls
>
> I know a code example might help, so I try to show it here (my code
> I'm afraid is too complex and ugly at the moment). You can see the it
> fails because MyTools doesn't have 'this' attribute...
>
> class MyTools:
>def f(self, this):
>print(this)
>
>def foo(self):
>this = self.this
>print(this)
>
> class MyProcess:
>def __init__(self):
>self.tools = MyTools()
>
>self.this = 'My Process, this'
>
>self.tools.f(self.this)
>
>self.tools.foo()
>
> if __name__ == "__main__":
>mp = MyProcess()
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



I am having a very difficult time following what you are trying to do, but
then, i'm not that bright, so it's probably me.

But, I will say this:

class MyTools:
   def f(self, this):
   print(this)

   def foo(self):
   this = self.this
   print(this)

In the second method (foo) you have it creating a local variable called
this, which is equal to the class variable self.this. Why not just use the
class variable throughout that method?

So, print(self.this).

My second thing, and this is just a personal pet peeve, why not create
descriptive names for your variables? Creating things called this or that
(and in this case, literally this or that) is hyper confusing.

My third thing. I think you are going to end up with an attribute error
because I don't see where the class has ever created a class variable called
this.

Maybe you meant to do something like this instead:

class MyTools:
  def __init__(self, this):
self.this = this

 def f(self):
   print(self.this)

   def foo(self):
   print(self.this)

so in your other object, it would then look something like this:

class MyProcess:
   def __init__(self):

   self.this = 'My Process, this'

   self.tools = MyTools(self.this)



   self.tools.f()

   self.tools.foo()



But, every time you instantiate MyProcess (not call it) you are going to
call the two methods of Tools class. If you want to seperate this, so you
can do something like tools.foo() and then later on go tools.f() you can do
that in a few ways:

One, you can just get rid of


   self.tools.f()

   self.tools.foo()

and once you create a MyProcess object you are free to call tools methods at
your leisure. For example
m = MyProcess()
m.tools.foo()
m.tools.f()

Unless you really do want those methods once you create the instance because
it's relevent to the creation of the object, then leave them where they are.

Lastly, I don't understand what you mean by "self" calls. This seems rather
academic to me, do you have a real example? I also don't understand what a
Runner is. Maybe its some compsci term or something.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Zip - password protect

2011-08-23 Thread James Reynolds
On Tue, Aug 23, 2011 at 4:11 PM, James Reynolds  wrote:

>
>
> On Tue, Aug 23, 2011 at 3:49 PM, Emile van Sebille  wrote:
>
>> On 8/23/2011 12:31 PM James Reynolds said...
>>
>>  I'm trying the 7-zip solution, but I can't get past this
>>> error: WindowsError: [Error 2] The system cannot find the file specified
>>>
>>> The line it fails at is here: z = subprocess.call(['7z', 'a', '1234',
>>> '-y', name + '.zip'] + self.file_locs)
>>>
>>> (from now)
>>>
>>> oddly enough, when I open up a python shell, i can run the above just
>>> fine and it creates a .zip file.
>>>
>>> But when I run it from eclipse, the exact thing, I get the error.
>>>
>>
>> I'd try providing the full path to 7z -- maybe that's why it probably
>> can't find the file specified.
>>
>> Emile
>>
>>
>>
>> __**_
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>>
>
>
> It was a silly problem.
>
> I guess Eclipse saves your PATH variables once the program is started,
> instead of referencing the os directly. (I just did print "Current path is
> %s" % os.path.expandvars("$PATH")) and that told me what was going on.
>
> Anyway, it's saving the files a .7z which isn't doing me much good. i was
> under the impression i could save them as .zip, if not I'm just going to
> have to password protect manually.
>
>
got it working, had a flag in the wrong spot. Seems to work better than the
Zip module in some ways.

Thanks for the help.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Zip - password protect

2011-08-23 Thread James Reynolds
On Tue, Aug 23, 2011 at 3:49 PM, Emile van Sebille  wrote:

> On 8/23/2011 12:31 PM James Reynolds said...
>
>  I'm trying the 7-zip solution, but I can't get past this
>> error: WindowsError: [Error 2] The system cannot find the file specified
>>
>> The line it fails at is here: z = subprocess.call(['7z', 'a', '1234',
>> '-y', name + '.zip'] + self.file_locs)
>>
>> (from now)
>>
>> oddly enough, when I open up a python shell, i can run the above just
>> fine and it creates a .zip file.
>>
>> But when I run it from eclipse, the exact thing, I get the error.
>>
>
> I'd try providing the full path to 7z -- maybe that's why it probably can't
> find the file specified.
>
> Emile
>
>
>
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>


It was a silly problem.

I guess Eclipse saves your PATH variables once the program is started,
instead of referencing the os directly. (I just did print "Current path is
%s" % os.path.expandvars("$PATH")) and that told me what was going on.

Anyway, it's saving the files a .7z which isn't doing me much good. i was
under the impression i could save them as .zip, if not I'm just going to
have to password protect manually.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Zip - password protect

2011-08-23 Thread James Reynolds
On Tue, Aug 23, 2011 at 2:57 PM, Alan Gauld wrote:

> On 23/08/11 19:23, James Reynolds wrote:
>
>> I tried that already.
>>
>> that's only to set the default password to read the zip, not to set a
>> pasword (wording is misleading I think)
>>
>>
> I'm confused.
>
> Which password are you thinking of?
>
> Is it at the OS level to prevent access to the file
>  - in which case the fact that its a zipfile is immaterial.
> Or is it the zipfile's own password? In which case what
> is different from the "default password to read the file"?
>
>
> What exactly are you trying to achieve?
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>

(from earlier)



I need to password protect a zip file I am creating from within python.

I would rather not have a user open the zip and set the password manually.

I'm trying the 7-zip solution, but I can't get past this
error: WindowsError: [Error 2] The system cannot find the file specified

The line it fails at is here: z = subprocess.call(['7z', 'a', '1234', '-y',
name + '.zip'] + self.file_locs)

(from now)

oddly enough, when I open up a python shell, i can run the above just fine
and it creates a .zip file.

But when I run it from eclipse, the exact thing, I get the error.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Zip - password protect

2011-08-23 Thread James Reynolds
I tried that already.

that's only to set the default password to read the zip, not to set a
pasword (wording is misleading I think)

On Tue, Aug 23, 2011 at 1:42 PM, Emile van Sebille  wrote:

> On 8/23/2011 10:19 AM James Reynolds said...
>
>  Does anyone know if a way to password protect a zip file? I have no
>> issues creating the zip file, but I would like to password protect as
>> well. I'm aware of a commercial solution, but I would like something
>> open source.
>>
>>
>
> The standard zipfile library includes a setpassword option.
>
> help(zipfile.PyZipFile.**setpassword)
>
> Help on method setpassword in module zipfile:
>
> setpassword(self, pwd) unbound zipfile.PyZipFile method
>Set default password for encrypted files.
>
>
> Emile
>
>
>
>
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Zip - password protect

2011-08-23 Thread James Reynolds
Does anyone know if a way to password protect a zip file? I have no issues
creating the zip file, but I would like to password protect as well. I'm
aware of a commercial solution, but I would like something open source.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] converting string to float

2011-08-10 Thread James Reynolds
On Wed, Aug 10, 2011 at 3:16 PM, Shwinn Ricci  wrote:

> I am reading values from excel using xlrd and using a variable to store
> them in (as part of a loop), as such:
>
>  position = sheet.cell(j, i).value
>
> however, I want to convert position to a floating point number, as the
> actual cell value is in the form of X.XXX (where X = digits). When I try
> float(position) I get a ValueError saying that the string could not be
> converted to a float. What am I doing wrong?
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


Have you tried printing the value to see what position actually holds?

If it has an apostrophe or something or something, you're not going to be
able to convert.

Also, as always, you should post the entire trace.

It could be helpful here, for example:

>>> x = '1. 1 '
>>> float(x)

Traceback (most recent call last):
  File "", line 1, in 
float(x)
ValueError: invalid literal for float(): 1. 1
>>>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: KeyError?

2011-07-28 Thread James Reynolds
-- Forwarded message --
From: Shwinn Ricci 
Date: Thu, Jul 28, 2011 at 1:13 PM
Subject: Re: [Tutor] KeyError?
To: James Reynolds 




On Thu, Jul 28, 2011 at 12:42 PM, James Reynolds  wrote:

>
>
> On Thu, Jul 28, 2011 at 12:11 PM, Prasad, Ramit  > wrote:
>
>> *From:* tutor-bounces+ramit.prasad=jpmchase@python.org [mailto:
>> tutor-bounces+ramit.prasad=jpmchase@python.org] *On Behalf Of *Shwinn
>> Ricci
>> *Sent:* Thursday, July 28, 2011 10:51 AM
>> *To:* tutor@python.org
>> *Subject:* [Tutor] KeyError?
>>
>> ** **
>>
>> I have an excel file that I am reading cell values from and putting them
>> into a dictionary. the dictionary looks like this:
>>
>> scafPositions = {position[j]: direction[j]}
>>
>> where position[j] is exclusively floating/numerical values and
>> direction[j] is exclusively strings.
>>
>> When I try to find whether a test value val is in the array of positions,
>> and then try to look its direction up with ScafPositions[val], I get a
>> KeyError. Is this because my data isn't standalone numbers, but numbers that
>> are calculated based off other cells? Or can I not test for val?
>>
>> ==
>>
>> ** **
>>
>> Your problem is probably that you are reassigning a new dictionary to the
>> name scafPositions each time instead of updating it. You should have
>> something like the following.
>>
>> ** **
>>
>> scafPositions = {}
>>
>> ** **
>>
>> #loop structure here:
>>
>> #do stuff
>>
>> scafPositions[ position[j] ] = direction[j]
>>
>>
>>
>
> this is my code:
>

def LookUp(helix, scafPos):

 # create dictionaries (keyed by vstrand #) of
 # scaffold position with value representing orientation

book = xlrd.open_workbook('CoordinatesSpreadsheet.xls')
sheet = book.sheet_by_index(0)
cols = sheet.row_values(2,1,150)
   9
position = {}
direction = {}
scafPositions = {}
for i in range(len(cols)):
rows = sheet.col_values(i+2, 5, 500)

#create lists of position and direction, sets up dictionary
for j in range(len(rows)):
  position[j] = float(sheet.cell(j+5, i+3).value)
  direction[j] = sheet.cell(j+5, i+1).value

  scafPositions[position[j]] = direction[j]
i += 5


   #returns value for appropriate caDNAno position, which is represented as
a concatenation of the input helix and scaffold position
val = float(helix) + (float(scafPos) * 0.001)

if (scafPositions[val] == "out"):
   print "Warning: Base pointing outwards"



return scafPositions[val]


def main(argv):
return LookUp(sys.argv[1], sys.argv[2])


if __name__ == "__main__":
main(sys.argv[1:])

perhaps im on the wrong sheet? all the tutorials say "sheet0" but I'm on
openoffice and the first sheet is 'sheet1'

>
> Or it could be it's not introspecting the formula within excel and his key
> is the string "=A1*sheet2!$B$1"or it could be he's looking for a float / int
> when in reality it's a string (because it must be converted explicitly).
>
> Without a traceback and the code, it's hard to know for sure.
>
> My guess is leading towards introspection.
>
> As far as printing the contents, once you create your dict with all the
> data just use the print statement / function depending on your version of
> python
>
> print scafPositions or print(scafPositions)
>
> You could loop through it as well
>
> for key, value in scafPositions.items():
> print key, value
>
> This will give you an idea of what is in the dict.
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

Sending this whole thing to the entire list. You should send replies to the
list as well.

going to go bit by bit here:


def LookUp(helix, scafPos):
> book = xlrd.open_workbook('CoordinatesSpreadsheet.xls')
> sheet = book.sheet_by_index(0)


ok good so far (but don't capitalize functions)

cols = sheet.row_values(2,1,150)


Here you are getting a slice of columns, from a single row. About 149
columns worth.

position = {}
> direction = {}


You don't need these dictionaries for anything useful as far as I can tell,
so drop them

for i in range(len(cols)):
> rows = sheet.c

Re: [Tutor] KeyError?

2011-07-28 Thread James Reynolds
On Thu, Jul 28, 2011 at 12:11 PM, Prasad, Ramit
wrote:

> *From:* tutor-bounces+ramit.prasad=jpmchase@python.org [mailto:
> tutor-bounces+ramit.prasad=jpmchase@python.org] *On Behalf Of *Shwinn
> Ricci
> *Sent:* Thursday, July 28, 2011 10:51 AM
> *To:* tutor@python.org
> *Subject:* [Tutor] KeyError?
>
> ** **
>
> I have an excel file that I am reading cell values from and putting them
> into a dictionary. the dictionary looks like this:
>
> scafPositions = {position[j]: direction[j]}
>
> where position[j] is exclusively floating/numerical values and direction[j]
> is exclusively strings.
>
> When I try to find whether a test value val is in the array of positions,
> and then try to look its direction up with ScafPositions[val], I get a
> KeyError. Is this because my data isn't standalone numbers, but numbers that
> are calculated based off other cells? Or can I not test for val?
>
> ==
>
> ** **
>
> Your problem is probably that you are reassigning a new dictionary to the
> name scafPositions each time instead of updating it. You should have
> something like the following.
>
> ** **
>
> scafPositions = {}
>
> ** **
>
> #loop structure here:
>
> #do stuff
>
> scafPositions[ position[j] ] = direction[j]
>
>
>



Or it could be it's not introspecting the formula within excel and his key
is the string "=A1*sheet2!$B$1"or it could be he's looking for a float / int
when in reality it's a string (because it must be converted explicitly).

Without a traceback and the code, it's hard to know for sure.

My guess is leading towards introspection.

As far as printing the contents, once you create your dict with all the data
just use the print statement / function depending on your version of python

print scafPositions or print(scafPositions)

You could loop through it as well

for key, value in scafPositions.items():
print key, value

This will give you an idea of what is in the dict.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] KeyError?

2011-07-28 Thread James Reynolds
On Thu, Jul 28, 2011 at 11:50 AM, Shwinn Ricci  wrote:

> I have an excel file that I am reading cell values from and putting them
> into a dictionary. the dictionary looks like this:
>
> scafPositions = {position[j]: direction[j]}
>
> where position[j] is exclusively floating/numerical values and direction[j]
> is exclusively strings.
>
> When I try to find whether a test value val is in the array of positions,
> and then try to look its direction up with ScafPositions[val], I get a
> KeyError. Is this because my data isn't standalone numbers, but numbers that
> are calculated based off other cells? Or can I not test for val?
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

Did you try printing the contents of scafPositions to see what it contains,
first?

Also, a traceback is helpful.

As far as introspection, which module are you using to read the excel files?
There's at least two that I know of.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Object Management

2011-07-27 Thread James Reynolds
On Wed, Jul 27, 2011 at 9:51 AM, Alexander  wrote:

> Hello everyone. I'm having trouble wrapping my mind around a project I'm
> working on. My goal is to create a program that manages (allows its users to
> manipulate, search by criteria and edit) objects. There is one type of
> object, for example I'll say it's a car.
>
> There will be a central data file containing all of the cars and multiple
> users will have access to it at once. I'm having trouble here, I've done
> some research on MOO and twisted but I'm not sure where to turn.
>
> Additionally I'll need a GUI! tkinter? Does anyone have any suggestions on
> how to get started with tkinter? I'm overwhelmed with the amount of
> documentation I've had to read and think I have to read to accomplish my
> goal.
>
> Thanks for reading, Alex.ander
>
> --
> Alexander
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>





It sounds like your learning a lot of this as you go. Honestly, I would
scrap the GUI idea and just use Django. This will solve your mulit-user,
front end, and back end problems in one go.

Of course, that's an entire skillset onto itself and it may not be worth the
time investment. But if you already know some HTML, it would be an asset for
years to come, if you picked it up.

In which case, simply use SQlite as your backend (it comes with Python) and
then chose a GUI toolkit from there. Designing a GUI is not for the feint of
heart. Tkinter is an option, but you may want to use Wx or GTK.

A third option is to use Django to manage your backend (by creating models
and such) and then designing a gui on top of that.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What's the difference between %s and %r?

2011-07-23 Thread James Reynolds
I just use string{0}.format(arg) format and that solves needing to memorize
% whatevers.

On Sat, Jul 23, 2011 at 11:08 AM, Martin A. Brown wrote:

>
> Hello everybody,
>
>  : > Hello! I'm having troubles understanding what is the difference
> between %s
>  : > and %r(format characters). I did google  and found something on
>  : > StackOverflow but I don't understand the explanation as it's not
> beginner
>  : > orientated.
>  : >
>  : >
>  : > Also, I have this code from learn python the hard way. Why at line 9
> does
>  : > he uses %r? Why did he didn't wrote print "I said: %s." %x ?
>  : >
>  : > 1x = "There are %d types of people." % 10
>  : > 2binary = "binary"
>  : > 3do_not = "don't"
>  : > 4y = "Those who know %s and those who %s." % (binary, do_not)
>  : > 5
>  : > 6print x
>  : > 7print y
>  : > 8
>  : > 9print "I said: %r." % x
>  : > 10  print "I also said: '%s'." % y
>  : > 11
>  : > 12  hilarious = False
>  : > 13  joke_evaluation = "Isn't that joke so funny?! %r"
>  : > 14
>  : > 15  print joke_evaluation % hilarious
>  : > 16
>  : > 17  w = "This is the left side of..."
>  : > 18  e = "a string with a right side."
>  : > 19
>  : > 20  print w + e
>  : >
>  : >
>  : >
>  : > Thanks in advance!
>  :
>  : I have recently worked through that exact question myself.  And
>  : it isn't well explained.
>  :
>  : So - the simplistic answer, gleaned (hopefully not erroneously)
>  : from this list:  s means a string, d means a number and r can be
>  : either or both.  y has only words, so is a string, and x has a
>  : number (specifically referred to as d) and words, so needs r.
>
> I am not horrendously well-versed here, but consider the mnemonic.
>
>  %f   float
>  %d   digit
>  %s   string
>  %r   representation
>
> A representation is something that (might?) allow for some sort of
> round-trip, later (re)construction of the object.  A string is
> intended for general consumption.  Do you really need to distinguish
> them?  Only if you plan on re-consuming your own output, at which
> point you should consider the representation rather than the string.
>
> There are doubtless more experienced hands here who will suggest
> concretely what you might do, but I would suggest that you use %s
> (string) for anything that you want to show to an end user and %r
> iif* you are planning to (re-)consume your own printed output.
>
> -Martin
>
>  * iif = if and only if
>
> --
> Martin A. Brown
> http://linux-ip.net/
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question regarding xml.dom.minidom: How do you send an unsignedByte in an wsdl request

2011-07-22 Thread James Reynolds
On Fri, Jul 22, 2011 at 2:18 PM, Garry Bettle wrote:

> Howdy all,
>
> Hope this message finds everyone well - roll on the weekend!
>
> I'm trying some calls to an wsdl API I've subscribed to.
>
> But I'm struggling to know what they want when sending an unsignedByte in a
> request.
>
> I'm using xml.dom.minidom so to start with I have:
> from xml.dom.minidom import Document, parseString
> import httplib, urlparse
>
> And later on I create a doc with:
> doc=Document()
>
> And I have a using a little helper to add a text element:
> def add_text_element(doc, parent, name, value):
> element=doc.createElement(name)
> element.appendChild(doc.createTextNode(str(value)))
> parent.appendChild(element)
>
> Should I have a separate class for an unsignedByte? i.e. def
> add_byte_element
>
> What should it look like?
>
> This is what their API helpdesk have said:
>
> "In this instance, the PriceFormat is defined as an unsignedByte.
>
>
>
>  **
>
> * *
>
> **"
>
> Many thanks!
>
> Cheers,
>
> Garry
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

this, *type=**xs:**unsignedByte*, is an attribute. I'm assuming "doc" above
is an instance of class Document, so you can get the element by using
doc.getElementsByTagName('complexType') or whatever it is you are talking
about for the element.

That will return an Element instance, and from there you can go haywire
adding attributes. The Element class has a method called
"setAttribute('string')".

You would do this right here:

element=doc.createElement(name)
<-- wave <--- element.setAttribute('string') <-- your argument here
element.appendChild(doc.createTextNode(str(value)))
parent.appendChild(element)

The node from your example has two attributes, and not one. I'm not sure how
important this is for you.

Anyway, that's my answer. I'm a newb though, and even more of a newb with
XML.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Viability of Python

2011-07-21 Thread James Reynolds
Source files for the 3.2 branch are located here:

http://hg.python.org/cpython/file/f0475f78d45c

the modules and objects directory has a lot of c files. there some
elsewhere. In modules theres some that start with XX. those are
demonstration i believe.

On Thu, Jul 21, 2011 at 6:46 PM, Prasad, Ramit wrote:

> >How would one acces the code base? Some time ago, someone responded to a
> question on this list by reccomending to study the built-in modules, where
> are those stored?
> >I'm using Mac OS X 10.7 with python 3, in case this is relevant.
>
> General documentation is located http://docs.python.org/py3k/ , but I
> think you want http://docs.python.org/py3k/library/index.html . The full
> list of modules is located http://docs.python.org/py3k/py-modindex.html .
>
>
> Ramit
>
>
> Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
> 712 Main Street | Houston, TX 77002
> work phone: 713 - 216 - 5423
>
>
> This communication is for informational purposes only. It is not
> intended as an offer or solicitation for the purchase or sale of
> any financial instrument or as an official confirmation of any
> transaction. All market prices, data and other information are not
> warranted as to completeness or accuracy and are subject to change
> without notice. Any comments or statements made herein do not
> necessarily reflect those of JPMorgan Chase & Co., its subsidiaries
> and affiliates.
>
> This transmission may contain information that is privileged,
> confidential, legally privileged, and/or exempt from disclosure
> under applicable law. If you are not the intended recipient, you
> are hereby notified that any disclosure, copying, distribution, or
> use of the information contained herein (including any reliance
> thereon) is STRICTLY PROHIBITED. Although this transmission and any
> attachments are believed to be free of any virus or other defect
> that might affect any computer system into which it is received and
> opened, it is the responsibility of the recipient to ensure that it
> is virus free and no responsibility is accepted by JPMorgan Chase &
> Co., its subsidiaries and affiliates, as applicable, for any loss
> or damage arising in any way from its use. If you received this
> transmission in error, please immediately contact the sender and
> destroy the material in its entirety, whether in electronic or hard
> copy format. Thank you.
>
> Please refer to http://www.jpmorgan.com/pages/disclosures for
> disclosures relating to European legal entities.
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Stack problem usind Python2.6

2011-07-21 Thread James Reynolds
On Thu, Jul 21, 2011 at 5:16 PM, David Merrick  wrote:

> ##from stack import Stack
>
> class Stack:
> def __init__(self):
> self.items =[]
>
> def isEmpty(self):
> return self.items ==[]
>
> def push(self,item):
> self.items.append(item)
>
> def pop(self,item):
> self.items.pop()
>
> def peek(self):
> return  self.items[len(self.items)-1]
>
> def size(self):
> return len(self.items)
>
> def parChecker(symbolString):
> s = Stack()
>
> balanced = True
> index = 0
> while index < len(symbolString) and balanced:
> symbol = symbolString[index]
> if symbol in "([{":
> s.push(symbol)
> else:
> if s.isEmpty():
> balanced = False
> else:
> top = s.pop()
> if not matches(top,symbol):
> balanced = False
> index+=1
> if balanced and  s.isEmpty():
> return True
> else:
> return False
>
> def matches(open,close):
> opens = "([{"
> closers = ")]}"
>
> opens.index(open) == closers.index(close)
>
> symbolString = "()"
> print(parChecker(symbolString))
>
> *Output*
>
> () returns False should be true
> (() returns False which is correct
>
> I can't find the error please help me
>
> --
> Dave Merrick
>
> merrick...@gmail.com
>
> Ph   03 3423 121
> Cell 027 3089 169
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>




A couple more points:

* I did just run it with the break statements where you have 'balanced =
False'
* the method Stack needs a return statement (otherwise, it will return
None), as all functions without a return statement do.
* you should either get rid of the argument for pop in Stack or make it an
optional argument (item = None) if you intended to do something with item.
* You of course need to tab in this block if you decide to go the 'break'
route:

if s.isEmpty():
return True
else:
return False
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Stack problem usind Python2.6

2011-07-21 Thread James Reynolds
On Thu, Jul 21, 2011 at 5:16 PM, David Merrick  wrote:

> ##from stack import Stack
>
> class Stack:
> def __init__(self):
> self.items =[]
>
> def isEmpty(self):
> return self.items ==[]
>
> def push(self,item):
> self.items.append(item)
>
> def pop(self,item):
> self.items.pop()
>
> def peek(self):
> return  self.items[len(self.items)-1]
>
> def size(self):
> return len(self.items)
>
> def parChecker(symbolString):
> s = Stack()
>
> balanced = True
> index = 0
> while index < len(symbolString) and balanced:
> symbol = symbolString[index]
> if symbol in "([{":
> s.push(symbol)
> else:
> if s.isEmpty():
> balanced = False
> else:
> top = s.pop()
> if not matches(top,symbol):
> balanced = False
> index+=1
> if balanced and  s.isEmpty():
> return True
> else:
> return False
>
> def matches(open,close):
> opens = "([{"
> closers = ")]}"
>
> opens.index(open) == closers.index(close)
>
> symbolString = "()"
> print(parChecker(symbolString))
>
> *Output*
>
> () returns False should be true
> (() returns False which is correct
>
> I can't find the error please help me
>
> --
> Dave Merrick
>
> merrick...@gmail.com
>
> Ph   03 3423 121
> Cell 027 3089 169
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
























The class stack seems to basically be a list. Why not just use a list (which
is already an object) to do the things that you want it to do? All of the
methods of the class are already methods of a list, so it seems like your
creating code that is already in python (unless there is more to it than I'm
missing)


In your ParChecker function, instead of setting a variable to false, why not
add a "break" statement? This will allow you to do things like "if
s.isEmpty():" instead of "if balanced and  s.isEmpty():"



Basically, what's going on here,

if balanced and  s.isEmpty():
return True
else:
return False

so long as this s.isEmpty() evaluates to false (which it is in the first few
loops) you will get the "else" part, which is "return false".

If you throw in some print statements, like dummy prints (print index, or
print "a" or whatever) you will see how many loops it's making.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python editor for Ipad

2011-07-21 Thread James Reynolds
Thanks for the input.

I received another email off list and I think i'm going to look into "
Textastic".

The Cloud9 seems interesting, but I'm not assured to have internet access
all the time (even if I do live in NYC).

Thanks for all the replies!


On Thu, Jul 21, 2011 at 5:09 PM, ian douglas wrote:

> On 07/21/2011 01:46 PM, Corey Richardson wrote:
>
>> Excerpts from ian douglas's message of Thu Jul 21 16:44:17 -0400 2011:
>>
>>> Yes, Cloud9 supports running/debugging/testing. They've also got github
>>> support for pulling in your projects. It's a pretty clever tool.
>>>
>>>  Could you share your secret? I didn't dig enough to figure it out. I saw
>> the
>> "Run" button and its configuration, but it looks like it wants a JS file
>> and
>> args? Or...maybe not?
>>
>
> Ah, my bad. Creating files should be allowed, but running *Python* files
> seems to still be on their TODO list as of March 23rd. Sorry for the
> misinformation.
>
> As soon as they Email me a password recovery message, (I signed up in May
> at Google IO), I can get more information to the list.
>
> -id
>
>
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Removing characters in a string using format()

2011-07-21 Thread James Reynolds
Since you're using python 3, you can just use a star to unpack the list

like so:

>>> print(*x)
a b
>>> print(*x, sep = ', ')
a, b

You can use sep to change the separator if you want the commas still.


On Thu, Jul 21, 2011 at 1:53 PM, Ryan Porter wrote:

> Hi there,
>
> In one part of a program I'm writing, I want a list to be printed to the
> string. Here's my code:
>
> # Begin snippet
> listString = input('Please enter a single item: >').strip();
>
> /print();
>itemList.append(listString);
> /
>
> /...
> /
>
> /print('And here it is in alphabetical order:', itemList)
> # End Snippet
> /
>
> However, when I print the list, I get something like this: ['Python',
> 'best', 'ever', 'is', 'language', 'programming', 'the'] with brackets. Is
> there a way to use format() to remove the brackets before the list is
> printed?
>
> Thanks for the help!
> //
>
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python editor for Ipad

2011-07-21 Thread James Reynolds
I might have to discuss some routines I've written in Python (and possibly
C). It would be easier to whip out the Ipad and show them some of the things
I've done, rather than a bulky laptop.

I could of course PDF everything with highlighting off of eclipse, but
ideally Ideally I would prefer a way for the user to interact with the text,
rather than an image.

So basically, an IDE or text editor with syntax highlighting for python.

If you have any thoughts, I would greatly appreciate it!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Web Programming

2011-07-20 Thread James Reynolds
If it doesn't interest you, skip it and move on. You can always come back
and learn it later, which will be easier anyway, with a more robust
background.

On Wed, Jul 20, 2011 at 11:22 AM, Dharmit Shah wrote:

> Hi all,
>
> I have been reading Head First 
> Python since
> some time now. I am stuck in a chapter on Web Development. Web Development
> has never been an area of my interest and hence I feel stuck in there. If
> anyone here has read the book, I wish to know if it's okay to skip that
> chapter and read further?
>
> --
> Regards
>
> Dharmit Shah 
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] getting error while solving a series that estimates the value of pi

2011-07-18 Thread James Reynolds
On Mon, Jul 18, 2011 at 12:10 PM, surya k  wrote:

> Hi,
>
> The problem is to estimate the value of pi using the following series.
>  *1 / pi  = (( 2 * sqrt(2) )/ 9801 )  * SIGMA of k[ (4k)! (1103 + 26390*k)
> / (k!^ 4 ) * 396^(4k)  ]*
> *where k is [0, infinity)*
> * Problem is located at : ThinkPython Book, www.thinkpython.org
>*Pg 89, Exercise 7.5, Think Python Book. *
> *
> *
> the series should be considered till the last term of the sigma must be <
> 1e-15
> I have written the below code :
>
> *# program estimates the value of pi*
> *# Ramanujan's series... *
> *import math*
> *
> *
> *def fact(n) : # def of factorial function.*
> *if n > 0 :*
> *   return n * fact(n-1)*
> *if n == 0 :*
> *   return 1*
> *
> *
> *k = 0*
> *tot = 0*
> *temp1 = 0*
> *while k >= 0 and temp1 == 0 :*
> *
> *
> *  a = ( 2 * math.sqrt(2) ) / 9801 # first term before sigma *
> *  nu = fact (4*k) * (1103 + (26390*k) )  # numerator of series*
> *  de = pow( fact(k), 4 ) * pow ( 396, 4*k )  # denominator of series*
> *  *
> *  if de / nu > 1e-15 : *
> *temp = nu / de*
> *tot = tot + temp*
> *temp1 = 0 *
> *k = k + 1 *
> *  elif de / nu  == 1e-15 :*
> * series = a * tot  *
> * k = k + 1*
> * temp1 = 0*
> *  elif de / nu < 1e-15 :*
> * print series*
> * temp1 = 1*
>
>
> I am getting the following error : which is completely surprising!
>
> *Traceback (most recent call last):*
> *  File "pi.py", line 30, in *
> *print series*
> *NameError: name 'series' is not defined*
>
> *
> *
> Thus I have removed name 'series' and replaced with  *a*tot, *
> now I am getting this error
>
> *Traceback (most recent call last):*
> *  File "pi.py", line 30, in *
> *print 1 / (a * tot)*
> *ZeroDivisionError: float divisio*n
>
>
>
> Thus I changed the first highlighted lines to
>
>  *nu = float (fact (4*k) * (1103 + (26390*k) ) )*
> *  de = float (pow( fact(k), 4 ) * pow ( 396, 4*k )) *
>
>
> now I am getting
>
> * Traceback (most recent call last):*
> *  File "pi.py", line 18, in *
> *de = float (pow( fact(k), 4 ) * pow ( 396, 4*k ) )*
> *OverflowError: long int too large to convert to float*
>
> *help me out of this problem, how could I fix this*
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


I am getting the following error : which is completely surprising!


You only define "series" when nu/de == XXX. Just don't print series outside
of where it is defined, or print it outside of the while loop if you can be
assured it is defined when the while loop ends.

Even so, you would still end up with the overflow error, because you have de
/ nu and I'm assuming you want nu / de. As an aside, you might want to
consider creating a variable above all the if statements called nude = nu /
de and replace all of the nu / de 's to nude. This way you only divide once
and not (potentially) three times per loop.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Reading opened files

2011-06-17 Thread James Reynolds
Your problem is right here:

>>> whole=file.read
>>> print whole

Your re-assigning the method "read()", which is a method of the object
"file" to the variable "whole"

So, when you print "whole" you can see that it is printing the location of
the method in memory. If you were to print file.read you would get the same
results.

Now, to call the method (or a function) you need to add the parentheses with
any arguments that it may need. In your case, you need to do "read()".

This principle holds true with any object.

So, let's say we created a list object by doing this mylist = []

mylist now has all of the methods that a list has. So, for example, I can
append something to the list by going:

mylist.append(1)

printing my list will show a list like this [1]

IDLE 2.6.5
>>> mylist = []
>>> mylist.append(1)
>>> print mylist
[1]

but instead lets say I did this:

>>> b = mylist.append
>>> print b


Which can be handy if i needed to do appending all the time, for example:

>>> b(1)
>>> print mylist
[1, 1]

My last piece of advice here is, use the Python documentation in addition to
googling. It's actually very readable (I think anyway)


On Fri, Jun 17, 2011 at 12:20 PM, Lisi  wrote:

> Hello :-)
>
> I have got as far as I have,i.e. apparently succeeding in both opening and
> closing two different files, thanks to google, but my struggles to _do_
> something with a file that I have opened are getting me nowhere.  Here is
> my
> latest failure:
>
> >>> file=open("/home/lisi/CHOOSING_SHOES.txt", "r")
> >>> file.close()
> >>> file=open("/home/lisi/CHOOSING_SHOES.txt", "r")
> >>> whole=file.read
> >>> print whole
> 
> >>> print "%r" % whole
> 
> >>> print "whole is %r" %whole
> whole is 
> >>> print "whole is %r" % whole
> whole is 
> >>>
>
> I'd be extremely grateful if one of you was willing to drop a hint, give me
> some pointers (even e.g. guide me to asking the correct question of
> Google),
> or tell me where I am going wrong.
>
> In general, the author advises leaving any of the extra credit questions
> that
> you are struggling with and coming back to them later.  And in general I
> have
> found that that works.  But this set of extra-credit questions he advises
> mastering before moving on.  And I am stuck on this one at this stage. :-(
> (I think that I have cracked the others.)
>
> Thanks.
>
> Lisi
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] File parsing

2011-06-16 Thread James Reynolds
use split on the list to split it up. search each element for something
like:

if '"' == element[:-1]:

if that evaluation is True, I would remove the quote mark from the word on
the right side, and place a new one on the left side using something like
'"' + element.

I would do the same thing for the other side in the same for loop, instead
the evaluation would be:

if '"' == element[:1]:




On Thu, Jun 16, 2011 at 1:03 PM, Neha P  wrote:

> Hi all,
> I know below query may sound silly, but can somebody suggest any better way
> of doing this:
> It would be helpful.
>
> I need to read a file line by line and print each line starting from the
> last word first:
>
> C:\Python26>type file_reversing_program.txt
> import sys
> import string
>
> f_obj=open(sys.argv[1],"r")
>
> for eachline in f_obj:
> eachline=eachline[ :-1] # to eliminate the trailing "\n"
> list_words=eachline.split(" ")
> list_words[0]=list_words[0]+"\n" # to add "\n" so that after line 1 is
> printed, line 2 should start on a new line
> list_words.reverse()
> for every_word in list_words:
>  print every_word, #  'comma' helps in printing words on same
> line,hence for last word we append "\n"
>
> f_obj.close()
>
> C:\Python26>type input_file.txt
> "Hi ther, how are you?"
> I are doing fine, thank you.
>
> C:\Python26>file_reversing_program.py input_file.txt
> you?" are how ther, "Hi
> you. thank fine, doing are I
>
> Is there a better way of doing the above program, mainly the text
> highlighted in yellow,
> Also if that is settled can there be a logic for getting the ouput more
> properly formatted (for text in blue) ,
> say giving an output like  :
> "you? are how ther, Hi"
> you. thank fine, doing are I
>
>
> Thanks,
> Neha
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] step value

2011-06-15 Thread James Reynolds
I am copying and pasting your code here from the previous email:


def ask_number(question, low, high):
> """Ask for a number within a range."""
> response = None
> if response in range(low, high, 1):
>   return response
> while response not in range(low, high):
> response = int(input(question))
> return response
> I tried to find clues by looking at the later section that calls on the
> ask_number function:
> def human_move(board, human):
> """Get human move."""
> legal = legal_moves(board)
> move = None
> while move not in legal:
> move = ask_number("Where will you move? (0 - 8):", 0, NUM_SQUARES)
> if move not in legal:
> print("\nThat square is already occupied, foolish human.
>  Choose another.\n")
> print("Fine...")
> return move



As to the question, I think what you are missing is, how do you make a
default value in a function parameter?

So, for example, let's say I have a function called, enchilada with a few
parameters. guac, spicey,

so it might look like this:

def enchildada(guac, spicey):
  do stuff with guac and spiceyness.
  return tasty_ness

And I can call that function like this:

a = enchilada(True, True)

But, let's say I want there to be a default vale for Spicey. Maybe I have
heartburn and I happen to enjoy heartburn every day at around noontime, so
my default option for spcicey is True.

I would then write the function like this:

def enchildada(guac, spicey=True):
  do stuff with guac and spiceyness.
  return tasty_nes

Now, when I call my enchilada function, I can call it like this:

a = enchilada(True) and the default value for spicey is True and it returns
a tasty encilada.

But, lets say my heartburn is beyond all rationality and I want a non-spicey
enchilada, i can override that default:

a = enchilada(True, False)

That is what the author meant by a default value and this just becomes a
variable you enter into the range function (so, a default of 1, and you can
change this to 2,3,etc)




On Wed, Jun 15, 2011 at 4:02 PM, Vincent Balmori
wrote:

> The question to that code I am trying to solve is
>
> "Improve the function *ask_number()* so that the function can be called
> with a step value. Make the default value of step *1*."
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Step Value

2011-06-15 Thread James Reynolds
Without looking at your code,

What is it that you know that's wrong about it? Are you getting a return
value which you know is incorrect, is the program throwing error and you
aren't sure why? or do you just suspect it is wrong but you aren't sure?

When posing a question, it's helpful to know the things above because those
answering might not know exactly what your problem is.

with regards to the step value of range, here,  "if response in range(low,
high, 1)" the default step value of range() is 1, so you don't need to have
that. range(1,3) will give you a list [1,2], for example.


On Wed, Jun 15, 2011 at 3:35 PM, Vincent Balmori
wrote:

> I am still working on that one question in the absolute beginners with the
> the ask_number function and step value. Honestly, I still have no idea what
> to do. This is one of my many attempts, but I know that it's wrong.
>
> def ask_number(question, low, high):
> """Ask for a number within a range."""
> response = None
> if response in range(low, high, 1):
>   return response
> while response not in range(low, high):
> response = int(input(question))
> return response
>
> I tried to find clues by looking at the later section that calls on the
> ask_number function:
>
> def human_move(board, human):
> """Get human move."""
> legal = legal_moves(board)
> move = None
> while move not in legal:
> move = ask_number("Where will you move? (0 - 8):", 0, NUM_SQUARES)
> if move not in legal:
> print("\nThat square is already occupied, foolish human.
>  Choose another.\n")
> print("Fine...")
> return move
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Break stament issue

2011-06-14 Thread James Reynolds
On Tue, Jun 14, 2011 at 2:59 PM, Susana Iraiis Delgado Rodriguez <
susana.delgad...@utzmg.edu.mx> wrote:

> Hello members!
>
> I'm doing a script that needs to loop to get some information, in order to
> do that I'm using modules from OGR and Mapnik. These to get data from
> shapefiles, but some of the files have 0 elements, I wrote a line to
> validate it, but it hasn't worked, so I added a break to keep working. When
> I run the scipt I got the next error:
> Traceback (most recent call last):
>   File "", line 1, in 
> import mapnik_punto_sin_duda
>   File "C:\Python26\mapnik_punto_sin_duda.py", line 23
> break
>^
> IndentationError: unexpected indent
>
> But I've read about this stamentet's use and I don't understand the reason
> I'm failing, the complete script is:
> import mapnik
> import os,fnmatch
> from mapnik import LineSymbolizer,PolygonSymbolizer,PointSymbolizer
> from osgeo import ogr,gdal,osr
>
> #Registra todos los drivers de GDAL
> file_list = []
> #Crear variable para buscar dentro de carpetas en el sistema
> folders = None
> #Se asigna el directorio raiz donde se van buscar los archivos, se hace un
> recorrido en la raiz
> for root, folders, files in os.walk( "c:\\" ):
> #Agregar a la lista los elementos que traiga os.path.join, los
> archivos que terminen en extension .shp
> for filename in fnmatch.filter(files, '*.shp'):
> file_list.append(os.path.join(root, filename))
> #Recorrer la lista que se creo
> for row, filepath in enumerate(file_list, start=1):
> #Dividir la ruta en dos: directorio y nombre de archivo
> dir(LineSymbolizer().stroke)
> shapeData = ogr.Open(filepath)
> shp = 'Error al abrir el archivo' +filepath
> if shapeData is None:
> print shp
> break
> else:
> layer = shapeData.GetLayer()
> defn = layer.GetLayerDefn()
> geo = defn.GetGeomType()
> (ruta, filename) = os.path.split(filepath)
> archivo = os.path.splitext(filename)
> i = archivo[0]+'.png'
>
> m = mapnik.Map(800,500,"+proj=latlong +datum=WGS84")
> m.background = mapnik.Color('#EBEBEB')
> s = mapnik.Style()
> r=mapnik.Rule()
>
> if geo == 3:
> print "Trabajando mapa "+ruta+"\\"+filename+" con
> geometria "+ str(geo)
>
> r.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color('#EB784B')))
>
> r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('rgb(170%,170%,170%)'),0.9))
> s.rules.append(r)
> m.append_style('My Style',s)
> lyr = mapnik.Layer('world',"+proj=latlong
> +datum=WGS84")
> lyr.datasource =
> mapnik.Shapefile(base=ruta,file=archivo[0])
> lyr.styles.append('My Style')
> m.layers.append(lyr)
> m.zoom_to_box(lyr.envelope())
> mapnik.render_to_file(m,i, 'png')
> print "La imagen " +i+ " fue creada."
> elif geo == 2:
> print "Trabajando mapa "+ruta+"\\"+filename+" con
> geometria "+ str(geo)
>
> r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('#EB784B'),0.9))
> s.rules.append(r)
> m.append_style('My Style',s)
> lyr = mapnik.Layer('world',"+proj=latlong
> +datum=WGS84")
> lyr.datasource =
> mapnik.Shapefile(base=ruta,file=archivo[0])
> lyr.styles.append('My Style')
> m.layers.append(lyr)
> m.zoom_to_box(lyr.envelope())
> mapnik.render_to_file(m,i, 'png')
> print "La imagen " +i+ " fue creada."
> elif geo == 1:
> print "Trabajando mapa "+ruta+"\\"+filename+" con
> geometria "+ str(geo)
> blue =
> mapnik.PointSymbolizer('C:\Python26\icono.png','png',50,50)
> blue.allow_overlap = True
> s=mapnik.Style()
> r=mapnik.Rule()
> r.symbols.append(blue)
> s.rules.append(r)
> #s.rules.append(blue)
> m.append_style('My Style',s)
> lyr = mapnik.Layer('world',"+proj=latlong
> +datum=WGS84")
> lyr.datasource =
> mapnik.Shapefile(base=ruta,file=archivo[0])
> lyr.styles.append('My Style')
> m.layers.append(lyr)
> m.zoom_to_box(lyr.envelope())
> mapnik.render_to_file(m,i, 'png')
> print "La imagen " +i+ " fue creada."
> else:
> 

Re: [Tutor] Medical Decision-Making Question

2011-06-13 Thread James Reynolds
I would start by getting a lot of the parameters you need in a database such
as SQLite (comes with python).

So for example, you would have a disease with known symptoms. You could
structure your tables with diseases symptoms

So, say the disease is a cold in the table you will have a row for cold and
columns identifying each symptom (by unique IDs).

In your symptom table you would have a row for each symptom and a column for
its parameters and probabilities and such.  For example, gender exclusive,
age exclusive, geographic exclusive, workplace, etc.

>From there you can build your select statements on the fly using python's
string formating.

That's how i would do it anyway.

I'm sure there are other ways as well.

On Mon, Jun 13, 2011 at 10:22 AM, Fred G  wrote:

> Hello--
>
> I'm a pre-med student interested in decision-making as applied to medical
> decisions.  I am trying to build a medical decision-making algorithm and am
> pretty stuck on a few things.
>
> I've built a file that contains a list of many diseases and their
> associated symptoms.  For example, here are the column headers and two
> sample rows (the "|" = "or"):
> DiseaseSymptoms
> Cold
> sore_throat|runny_nose|congestion|cough|aches|slight_fever
> Flu
> sore_throat|fever|headache|muscle_aches|soreness|congestion|cough|returning_fever
>
> My questions are the following:
> a)  How's the best way to make it so I can have a user type in a list of
> symptoms and then have the computer tell the user the possible diseases that
> share those symptoms? In other words, on a high-level I have a pretty good
> idea of what I want my algorithm to do-- but I need help implementing the
> basic version first.  I'd like to do the following:
> >>>Please enter a list of symptoms
> >>>[user_input]
> >>>Possible diseases include: x, y, z
>
> b)Once I get that working, could anyone point me to good code already
> written in Python such that I could have a model (for syntax and overall
> structure) for figuring out how to make the computer evaluate more factors
> such as: patient age, patient history, and even downloading archival data
> for patients in the same demographic group?
>
> Thanks!
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Syntax for Simplest Way to Execute One Python Program Over 1000's of Datasets

2011-06-10 Thread James Reynolds
Honestly no idea.

At work I use 2.6 / 2.7. At home it's 3.2 / 2.7.

I've never actually tried doing this at home, so I don't know.

They have a mail list though, I would post there to find out.

2011/6/10 Válas Péter 

>
>
> 2011. június 10. 15:51 James Reynolds írta, :
>
>
>> Regarding Excel, you can write your output directly to an Excel file from
>> python using the Python-Excel module. Just install all three packages. I use
>> them all the time.
>>
>>
>> Do they work with Py3K?
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Syntax for Simplest Way to Execute One Python Program Over 1000's of Datasets

2011-06-10 Thread James Reynolds
>
> 3) Open the .txt file in Excel, remove the few lines I don't need (ie
> single quotes, etc)


Regarding Excel, you can write your output directly to an Excel file from
python using the Python-Excel module. Just install all three packages. I use
them all the time.

Here is something that I wrote just yesterday which writes data to sheets
one and three in an existing notebook.

from xlrd import open_workbook
> from xlutils.copy import copy
> from xlwt import easyxf


def insert_excel(self, exfile, insert_list):
> book = open_workbook(exfile, formatting_info = True)
> copy_book = copy(book)
> copy_sheet = copy_book.get_sheet(0)
> copy_sheet_two = copy_book.get_sheet(2)
> plain = easyxf('')
> allp = len(insert_list)
> for row, listx in enumerate(insert_list):
> listx = self.formater(listx)
> print row +1, ' of ', allp
> if len(listx) > 250:
> first_list = listx[0:250]
> second_list = listx[250:]
> for i, cell in enumerate(first_list):
> copy_sheet.write(row+2, i, cell, plain)
> for i, cell in enumerate(second_list):
> try:
> copy_sheet_two.write(row+2, i, cell, plain)
> except ValueError:
> break
> else:
> for i, cell in enumerate(listx):
> copy_sheet.write(row+2, i, cell, plain)
> copy_book.save(exfile)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Syntax for Simplest Way to Execute One Python Program Over 1000's of Datasets

2011-06-09 Thread James Reynolds
My advice would be to stay away from generic names, like:

for item in items:
   do stuff with item

For a couple of lines its ok, but when programs get large, your program will
get confusing even to you as the author.

Sometimes, it's best just to do "for all in listx: but I think that's rare.

Usually, you know what the contents of a list are, and you know what the
list is, so for example

for assets in portfolio:
   do stuff with assets

for loans in cdo:
   do stuff with loans

for protein in gen_sequence:
   do stuff with protein.

etc.

The other piece of advice I would give you is, make it more object oriented.
This should get you away from having to rename things, as you say, and use
self referential path finding mechanisms, such as os.getcwd() (get current
working directory) and use listdir as mentioned previously.



On Thu, Jun 9, 2011 at 4:30 PM, Corey Richardson  wrote:

> On 06/09/2011 03:49 PM, B G wrote:
> > I'm trying to analyze thousands of different cancer datasets and run the
> > same python program on them.  I use Windows XP, Python 2.7 and the IDLE
> > interpreter.  I already have the input files in a directory and I want to
> > learn the syntax for the quickest way to execute the program over all
> these
> > datasets.
> >
> > As an example,for the sample python program below, I don't want to have
> to
> > go into the python program each time and change filename and countfile.
>  A
> > computer could do this much quicker than I ever could.  Thanks in
> advance!
> >
>
> I think os.listdir() would be better for you than os.walk(), as Walter
> suggested, but if you have a directory tree, walk is better. Your file
> code could be simplified a lot by using context managers, which for a
> file looks like this:
>
> with open(filename, mode) as f:
>f.write("Stuff!")
>
> f will automatically be closed and everything.
>
> Now for some code review!
>
> >
> > import string
> >
> > filename = 'draft1.txt'
> > countfile = 'draft1_output.txt'
> >
> > def add_word(counts, word):
> > if counts.has_key(word):
> > counts[word] += 1
> > else:
> > counts[word] = 1
> >
>
> See the notes on this later.
>
> > def get_word(item):
> > word = ''
> > item = item.strip(string.digits)
> > item = item.lstrip(string.punctuation)
> > item = item.rstrip(string.punctuation)
> > word = item.lower()
> > return word
>
> This whole function could be simplified to:
>
> return item.strip(string.digits + string.punctuation).lower()
>
> Note that foo.strip(bar) == foo.lstrip(bar).rstrip(bar)
>
> >
> >
> > def count_words(text):
> > text = ' '.join(text.split('--')) #replace '--' with a space
>
> How about
>
> text = text.replace('--', ' ')
>
> > items = text.split() #leaves in leading and trailing punctuation,
> >  #'--' not recognised by split() as a word
> separator
>
> Or, items = text.split('--')
>
> You can specify the split string! You should read the docs on string
> methods:
> http://docs.python.org/library/stdtypes.html#string-methods
>
> > counts = {}
> > for item in items:
> > word = get_word(item)
> > if not word == '':
>
> That should be 'if word:', which just checks if it evaluates to True.
> Since the only string that evaluate to False is '', it makes the code
> shorter and more readable.
>
> > add_word(counts, word)
> > return counts
>
> A better way would be using a DefaultDict, like so:
>
> from collections import defaultdict
> [...]
>
> def count_words(text):
>counts = defaultdict(int) # Every key starts off at 0!
>items = text.split('--')
> for item in items:
>word = get_word(item)
> if word:
>counts[word] += 1
>return counts
>
>
> Besides that things have a default value, a defaultdict is the same as
> any other dict. We pass 'int' as a parameter because defaultdict uses
> the parameter as a function for the default value. It works out because
> int() == 0.
>
> >
> > infile = open(filename, 'r')
> > text = infile.read()
> > infile.close()
>
> This could be:
>
> text = open(filename).read()
>
> When you're opening a file as 'r', the mode is optional!
>
> >
> > counts = count_words(text)
> >
> > outfile = open(countfile, 'w')
> > outfile.write("%-18s%s\n" %("Word", "Count"))
> > outfile.write("===\n")
>
> It may just be me, but I think
>
> outfile.write(('=' * 23) + '\n')
>
> looks better.
>
> >
> > counts_list = counts.items()
> > counts_list.sort()
> > for word in counts_list:
> > outfile.write("%-18s%d\n" %(word[0], word[1]))
> >
> > outfile.close
>
> Parenthesis are important! outfile.close is a method object,
> outfile.close() is a method call. Context managers make this easy,
> because you don't have to manually close things.
>
> Hope it helped,
> --
> Corey Richardson
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://m

Re: [Tutor] Python Extensions in C

2011-06-02 Thread James Reynolds
I fixed it. I find if I sleep on things I have a better chance at fixing
them. Maybe I will get some real work done today instead of going all OCD on
this side project?

Here's the dif: http://pastebin.com/KYBab3H9

I'll address your points in a second, but here's how I found the problem
(Python is so much easier to work with, it's scary).

1. I thought to myself last night, I knew there was a problem with the sums
not adding up properly in the var() function (the sumall variable).

2. I then thought to myself, well, let me trace out every last variable in
the first step. I then found that sumall was being raised to the third
power, not the second power.

3. I traced out "moment" and it indeed was sending through a "3", or at
least seemed to be.

4. Meanwhile, back at line 362, I am calling the same function, but with "3"
in the moment arg.

5. It occurs to me that I need to save the value of the address that the
pointer returned from "return_varp" to a variable. I actually have such a
variable already, but just below the "third moment". The skew function now
seems to work correctly. My guess is Kurt is still broken, but most likely
this is the same problem.

I guess what happens is, the static variable in var() func is saving the
value to the same exact address. Thinking back on it, this would be
consistent with Python itself if I was to have a class like Class A(): a = 1
def update_a: A.a +=1. After calling update_a, if I print A.a my answer
should be 2.

But, what I was thinking was that each new call to var() would be like a
instance of class A above, in other words, it would create a static variable
called "temp_r", but in thinking about it, this isn't the case. Declaring
something static means (please correct me if I'm wrong) that the address you
using for "temp_r" is now and forever will be the address assigned
when initially created. So, any pointer pointing to this address will return
its changing content, whether intended to do so or not.

The entire reason why I was using static variables in the those functions
was so they didn't lose their values when returned to their calling
functions.

So anyway, back to your points.

I had gone through must of it to bring it in line with your suggestions from
earlier, but I'm afraid you caught me getting lazy.

This section:


avg = *return_avgp;
samp = 0;
return_varp = var(seq, count, &avg, samp, 2);
third_moment = var(seq, count, &avg, 0, 3);

Was an artifact from troubleshooting. It should have been (and I think is
now) how you suggested.


So at any rate, thank you for the help and if you see something else, please
don't hesitate to point it out!





On Wed, Jun 1, 2011 at 8:40 PM, ALAN GAULD wrote:

> OK, It seems to have grown a bit! :-)
>
> Your use of static seems a little odd. In particular the definition of avg
> as a static double.
> You then never use avg except here:
>
>
>1. avg = *return_avgp;
>2. samp = 0;
>3. return_varp = var(seq, count, &avg, samp, 2);
>4. third_moment = var(seq, count, &avg, 0, 3);
>
> You assign the content of a pointer to avg then take use address
> of avg in var() - effectively making avg back into a pointer?
>
> Why not just use *return_avgp inside the var() function?
> And why is avg static? - do you understand what static is doing?
> And the side effects of that? Is there a reason to use static?
> If so its a bit too subtle for me...
>
> BTW, On style issues:
> While I prefer the braces style you have made the mistake of mixing styles,
>
> particularly confusing when done inside a single function as in the middle
> of
> stat_kurt()
>
> And I don't personally like variables being declared in the middle of code.
>
> (eg lines 365 and 430) I can just about accept at the start of a block,
> but I prefer at the start of the function. It's just easier to find if they
>
> are all together.
>
> Other than that I can't see the error, but its late and thats
> quite a lot of code for a Python programmer to wade through! :-)
>
>
> Alan Gauld
> Author of the Learn To Program website
>
> http://www.alan-g.me.uk/
>
>
> --
> *From:* James Reynolds 
> *To:* Alan Gauld 
> *Cc:* tutor@python.org
> *Sent:* Wednesday, 1 June, 2011 20:49:44
>
> *Subject:* Re: [Tutor] Python Extensions in C
>
> So I've been continuing with my experiment above, and I've made some good
> progress and learned some new things as I've been going. I've expanded it
> out a little bit, and you can see the code here:
>
> http://pastebin.com/gnW4xQNv
>
> &l

Re: [Tutor] Python Extensions in C

2011-06-01 Thread James Reynolds
So I've been continuing with my experiment above, and I've made some good
progress and learned some new things as I've been going. I've expanded it
out a little bit, and you can see the code here:

http://pastebin.com/gnW4xQNv

<http://pastebin.com/iCNJVyKr>I've tried to incorporate most of your
suggestions (although, the code itself looks more condensed in my editor
than what it appears there).

Unfortunately, I am stuck and I have no clue how to free myself from the
mud.


On line 370, you will notice I have "*return_varp" as the return value and
not "skew". This is because I am trying to figure out why the variance
function is not working properly from this function call.

Earlier today it was working fine, so I know it works at least in theory.

When variance is called from stats.var it works just fine and the output is
as expected.

so for example,

a = [1,2,3,4,4,5]
stats.var(a) = 2.16 (correct)

stats.skew(a) = -0.74 (not correct)

Again, for this I have the return value of skew set to show me the the
second moment. Skew is calling the same exact function as var and with the
same exact same inputs as var(), or should be.

I've looked at every single variable in variance to see what is going on and
here is what I know for now:

1. sumall is adding up to the wrong number when called from skew (or kurt).
2. avg, count, and moment all are what they should be.
3. The sequence passed is always the same from Python (a = [1,2,3,4,4,5])

I'm guessing this is some nuance of C code dealing static variables or
something to do with memory, but again, I no even less about C than I do
about Python (which is my objective here - learning some of this should make
me better at both, hopefully)

A couple other points: There are three parameters now, not one. The later
two are optional. they are (list, avg, and sample) sample is True by
default.

So you can pass it an average already.

Lastly, any other pointers would be greatly appreciated.

James















On Thu, May 26, 2011 at 7:50 PM, Alan Gauld wrote:

>
> "James Reynolds"  wrote
>
>
>  As far as the null point goes, it shouldn't be null at all once it gets to
>> the point Alan pointed out. The pointer is set in (for example) stat_avg
>>
>>   seq = PySequence_Fast(obj, "Expected a Sequence");
>>
>
> Can the function fail? If so what does it return? That was
> my point. Can seq ever still be NULL after the function call?
> For example if the function is allocating memory it could fail
> to grab enough and then return a NULL
>
> But it depends on how reliable the Python function is in
> its return value...
>
>
>  But maybe I am missing something that you have seen?
>>
>
> Don't rely on functio  returns being valid values.
> It is common practice in industrial strength C to return a NULL
> and expect the user to check. Manyb of the standard library
> functions work that way too.
>
> So you often see code like
>
> if (foo = someFunction() ){   // notice it is an assignment not equality
> test
> process(foo);
> }
>
> HTH,
>
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] checking if a variable is an integer?

2011-05-31 Thread James Reynolds
If prime numbers were finite (an ability to find *all *prime numbers) that
would cause havoc with the fundamental theorem of arithmetic ;)

On Tue, May 31, 2011 at 5:40 PM, Rachel-Mikel ArceJaeger <
arcejae...@gmail.com> wrote:

> Isn't one of the unsolved millenium prize problems one that includes the
> ability to find all of the prime numbers? I'm not sure if your program is
> possible if the input number is large.
>
> But to check if a number x is an int, just do this:
>
> x == int(x)
>
>
> Rachel
>
>
> On Tue, May 31, 2011 at 2:38 PM, Hugo Arts  wrote:
>
>> On Tue, May 31, 2011 at 11:30 PM, Joel Goldstick
>>  wrote:
>> >
>> >
>> >
>> http://stackoverflow.com/questions/1265665/python-check-if-a-string-represents-an-int-without-using-try-except
>> >
>> > def RepresentsInt(s):
>> >
>> > try:
>> > int(s)
>> >
>> > return True
>> > except ValueError:
>> >
>> > return False
>> >
>>  print RepresentsInt("+123")
>> >
>> > True
>>  print RepresentsInt("10.0")
>> >
>> > False
>> >
>>
>> For strings, that works, but not for integers:
>>
>> >>> int(10.0)
>> 10
>>
>> And if you want to check if one number is divisible by another, you're
>> not going to call it on strings.
>>
>> A better way is to use the modulo operator, which gives the remainder
>> when dividing:
>>
>> >>> a = 6
>> >>> a % 3
>> 0
>> >>> a % 4
>> 2
>>
>> So, if the remainder is zero the left operand is divisible by the right
>> one.
>>
>> Hugo
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Extensions in C

2011-05-26 Thread James Reynolds
On Thu, May 26, 2011 at 3:07 PM, Stefan Behnel  wrote:

> Stefan Behnel, 26.05.2011 18:10:
>
>  James Reynolds, 26.05.2011 17:22:
>>
>>> As an intellectual exercise, I wanted to try my hand at writing some
>>> extensions in C.
>>>
>>
>> This is fine for en exercise, and I hope you had fun doing this.
>>
>> However, for real code, I suggest you use Cython instead. Your module
>> would
>> have been substantially simpler and likely also faster.
>>
>> http://cython.org
>>
>
> Oh, and one more thing: it makes it easier to write safe, portable and
> versatile code. As others have pointed out, your code has unnecessary bugs.
> It also doesn't compile in Python 3 and lacks the ability to calculate the
> averages of a set or deque, for example. Instead, it only handles tuples and
> lists. That reduces the usefulness of your implementation.
>
>
> Stefan
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


Stefan,

Thank you for point out the above. Could you kindly please point out some of
those unnecessary bugs?

I'm not sure that it matters that it won't work in sets and deque's, so long
as the documentation is clear, no? (Which I'm still not sure how to do, just
yet)

But, I did test it for sets and deque and it works just fine.

setx = set([])
print type(setx)
for i in r:
setx.add(random.choice(r))
print stats.mean(setx)
dequex = deque([])
print type(dequex)
for i in r:
dequex.append(random.choice(r))
print stats.mean(dequex)

I'll see what I can do about making it work with P3k, I think the only thing
that would need to be changed would be "PyMODINIT_FUNC initstats(void)" I
believe. Please correct me if I'm wrong though.

Thank you again for the feedback.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Extensions in C

2011-05-26 Thread James Reynolds
Someone once told me I was a "kinetic learner" and it seemed to fit with my
learning habbits, I wasn't aware there is an entire branch of education
theory revolving around "learning specialties", which was interesting to
learn about.





On Thu, May 26, 2011 at 1:52 PM, Patty  wrote:

>
> - Original Message - From: "Stefan Behnel" 
> To: 
> Sent: Thursday, May 26, 2011 9:10 AM
> Subject: Re: [Tutor] Python Extensions in C
>
>
>
>  James Reynolds, 26.05.2011 17:22:
>>
>>> As an intellectual exercise, I wanted to try my hand at writing some
>>> extensions in C.
>>>
>>
>> This is fine for en exercise, and I hope you had fun doing this.
>>
>> However, for real code, I suggest you use Cython instead. Your module
>> would have been substantially simpler and likely also faster.
>>
>> http://cython.org
>>
>> Stefan
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>>
> Hello James -
>
> I saw in your email 'Being a kinetic learner' and I had to look that up  -
> is there a difference between
> the words 'kinetic' and 'kinesthetic'?  When I googled it, I am sure I am a
> kinetic learner also and I come
> up with programming exercises for myself as well.  I am originally a C
> programmer and now I really like
> Python.   I don't know what it will be like for you to learn these
> languages the other way around, I am not
> the teacher-type.
>
> And thanks to Rachel-Mikel for that really nice piece of code to save for
> the future.
>
> Regards,
>
> Patty
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Extensions in C

2011-05-26 Thread James Reynolds
Thank you Rachel and Alan for the feedback.

Oddly enough, I had created an exception between the time I sent this and
your response to catch occasions when the list is empty (I will need to test
a few other things, like what if the list holds items other than strictly
numbers?)

I did utilize some of the suggestions that Rachel suggested because that is
how I generally code in Python in any event, the extra variables were more
for my personal readability, but now that I understand the flow a little I
eliminated some of them (especially the ones that go directly to return
without doing much else)

Interestingly, I ran this through the profiler comparing it to similar
Python algorithms and the stats.mean is twice as slow as just staying in
Python. But, stats.var and stats.stdev are 4-5X faster.

As far as the null point goes, it shouldn't be null at all once it gets to
the point Alan pointed out. The pointer is set in (for example) stat_avg

seq = PySequence_Fast(obj, "Expected a Sequence");

if the point is NULL it won't make it to that, because of:

if (seq == NULL)
return NULL;

But maybe I am missing something that you have seen?

I'm going to try to force it to fail in some of the ways you pointed out,
and maybe some others.

I look forward to more feedback from you all!

I'll look into your suggestion regarding comprehension (i'm not sure what
that means in a programing sense, but I'm sure I'll find out!)







On Thu, May 26, 2011 at 2:55 PM, Stefan Behnel  wrote:

> Rachel-Mikel ArceJaeger, 26.05.2011 17:46:
>
>  A couple small things that will help improve memory management
>>
>> Rather than avg = sumall / count; return avg; Just return sumall/count
>> instead. Then you don't have to waste a register or assignment
>> operation.
>>
>> Division is expensive. Avoid it when you can.
>>
>> Here, for (a=0; a != count; a++) { temp =
>> PyFloat_AsDouble(PySequence_Fast_GET_ITEM(seq,a)); sumall += temp;
>> Again, save variables and operations. Write this as:
>>
>> for (a=0; a != count; a++) { sumall +=
>> PyFloat_AsDouble(PySequence_Fast_GET_ITEM(seq,a));
>>
>> Similar corrections in var()
>>
>> It's cheaper when you're using powers of two to just right or
>> left-shift:>>  or<<. Since you want to increase by a power of two, do:
>>
>> (avg - PyFloat_AsDouble(PySequence_Fast_GET_ITEM(seq,a)<<  1;   // This
>> means (...)^(2^1)
>>
>> Division by powers of two is>>. Note that these only works for powers of
>> two.
>>
>
> Oh please! You are seriously insulting my C compiler here. Believe me, it's
> a *lot* smarter than this.
>
> None of this is even faintly necessary.
>
> Stefan
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python Extensions in C

2011-05-26 Thread James Reynolds
Hello All:

As an intellectual exercise, I wanted to try my hand at writing some
extensions in C.

I was wondering if you all could look over my code and give some feedback.

Here is the link for the code: http://pastebin.com/jw3ihfsN

I have zero experience coding in C (and not much more coding in Python!).
Being a kinetic learner, I thought this would be a good exercise to teach me
some of the underpinnings of Python, how it works, why it works the way it
does, and as an added bonus, skills to actually write my own extensions if I
ever wanted to.

I had to learn about pointers to do this, and I'm still not 100% on if I
used them correctly herein.

I am also very concerned with memory management because I am not sure when I
should be calling the memory allocation macros to decref or incref when
needed.

I would also like to get feedback on how I am constructing C algorithms.

As far as the module itself goes, I was able to compile and use it on a
windows machine compiling with mingw (I use distutils to do the work, so for
me I do "python setup.py build" in my CMD.

There are three functions, stats.mean, stats.var, stats.stdev (and they do
what you would expect). One thing though, these are the "population"
statistics and not "sample" in case you want to test it out.

Also, anything else that you think would be worthwile pointing out, tips and
tricks, common pitfalls, etc.

Thanks in advance for you feedback.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Making a script part of the terminal

2011-05-20 Thread James Reynolds
We just had a similar question yesterday.

Just make sure Python is on your PATH. CD to the directory where your file
is located and then you can just type "python myfile.py" where myfile is the
name of your file.

On Fri, May 20, 2011 at 1:43 PM, michael scott wrote:

> Okay, my title might be undescriptive, let me try to explain it better. I
> want to take a script I've written and make it usable by typing its name in
> the terminal. Perfect example is the python interpreter. You just type in
> the word python to the terminal and then the interpreter runs. I know other
> programs can do this as well (like mozilla or nautilus or rhythmbox).  So
> how do I make my scripts executable from the terminal?
>
> 
> What is it about you... that intrigues me so?
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error in executing 'Python Filename.py'.

2011-05-19 Thread James Reynolds
You're in the python interpreter.

Hit control C to go back to cmd and then you can do "python hello.py"

On Thu, May 19, 2011 at 4:14 PM, Neha P  wrote:

> C:\>python hello.py
> 'python' is not recognized as an internal or external command,
> operable program or batch file.
>
> C:\>cd python26
>
> C:\Python26>python
> Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit
> (Intel)] on
> win32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> python hello.py
>   File "", line 1
> python hello.py
>^
> SyntaxError: invalid syntax
> >>> python
> Traceback (most recent call last):
>   File "", line 1, in 
> NameError: name 'python' is not defined
> >>>
>
> Above is the snapshot of the error.
> M running Windows 7 Home Premium, OS: NT
> Have  ;C:\Python26 added to the PATH variable , still unable to execute
> any file :( same error.
>
> Please help!! Thanks in advance..
>
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] String Processing Query

2011-05-16 Thread James Reynolds
concatenate the entire thing together, including the "*".

Once you have that as a single string, use string.split('*') and you will
have your two strings.

On Mon, May 16, 2011 at 9:51 AM, Spyros Charonis wrote:

> I have a file with the following contents:
>
> >from header1
> abcdefghijkl
> mnopqrs
> tuvwxyz
> *
> >from header2
> poiuytrewq
> lkjhgfdsa
> mnbvcxz
> *
>
> My string processing code goes as follows:
>
> file1=open('/myfolder/testfile.txt')
> scan = file1.readlines()
>
> string1 = ' '
> for line in scan:
> if line.startswith('>from'):
> continue
> if line.startswith('*'):
> continue
> string1.join(line.rstrip('\n'))
>
> This code produces the following output:
>
> 'abcdefghijkl'
> 'mnopqrs'
> 'tuvwxyz'
> 'poiuytrewq'
> 'lkjhgfdsa'
> 'mnbvcxz'
>
> I would like to know if there is a way to get the following
> output instead:
>
> 'abcdefghijklmnopqrstuvwxyz'
>
> 'poiuytrewqlkjhgfdsamnbvcxz'
>
> I'm basically trying to concatenate the strings
> in order to produce 2 separate lines
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] create an xls file using data from a txt file

2011-05-11 Thread James Reynolds
Yes, thank you.

Actually, I never knew that about the windows separators, since I've just
always used the '\' out of habit.



On Wed, May 11, 2011 at 2:39 PM, Prasad, Ramit wrote:

>
>
> >your "\" is a "/"
>
>
>
> >when writing out a string, such as 'C:\test.xls', the "/" is an escape in
> python. So you have two choices, You can either write
>
> out path = 'C:\\test.xls', which will be 'C:\test.xls' or you can write out
> path = r'C:\test.xls' the "r" bit tells python that the following is a
> regular expression. or regex.
>
>
>
>
>
> ‘/’ is perfectly valid Windows separator. See the *tested* examples below.
> It works just fine pretty much anywhere I have ever tried it, including the
> command line. (except apparently for an MSOffice file save dialog that I
> tried just now)
>
>
>
> >>> import xlwt
>
> >>> workbook = xlwt.Workbook()
>
> >>> sheet = workbook.add_sheet('test')
>
> >>> sheet.write(0,0,'test')
>
> >>> workbook.save('C:/test')
>
> >>> workbook.save('C:/test.xls')
>
> >>> workbook.save('C:\\test2.xls')
>
> >>> workbook.save(r'C:\test3.xls')
>
> >>>
>
>
>
>
>
> The error he is getting may be unrelated to actually saving. I am not very
> familiar with the xlwt, but I know it does not write everything to file on
> the sheet.write() command. Save() actually does some writing and then saves
> the file. This can lead to misleading errors. I have had a similar error
> when writing non-ASCII data (and not changing the default ASCII encoding
> type).
>
>
>
>
>
> Furthermore, the escape character is ‘\’ not ‘/’,
>
>
>
> And r’string‘  means raw string not* *regular expression.
>
> “String literals may optionally be prefixed with a letter 'r' or 'R'; such
> strings are called *raw strings* and use different rules for interpreting
> backslash escape sequences.” ~
> http://docs.python.org/reference/lexical_analysis.html
>
>
>
>
>
> Ramit
>
>
>
>
>
>
>
> *Ramit Prasad **| JPMorgan Chase Investment Bank | Currencies Technology*
>
> *712 Main Street **| Houston, TX 77002*
>
> *work phone: 713 - 216 - 5423*
>
>
>
> This communication is for informational purposes only. It is not intended
> as an offer or solicitation for the purchase or sale of any financial
> instrument or as an official confirmation of any transaction. All market
> prices, data and other information are not warranted as to completeness or
> accuracy and are subject to change without notice. Any comments or
> statements made herein do not necessarily reflect those of JPMorgan Chase &
> Co., its subsidiaries and affiliates. This transmission may contain
> information that is privileged, confidential, legally privileged, and/or
> exempt from disclosure under applicable law. If you are not the intended
> recipient, you are hereby notified that any disclosure, copying,
> distribution, or use of the information contained herein (including any
> reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any
> attachments are believed to be free of any virus or other defect that might
> affect any computer system into which it is received and opened, it is the
> responsibility of the recipient to ensure that it is virus free and no
> responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and
> affiliates, as applicable, for any loss or damage arising in any way from
> its use. If you received this transmission in error, please immediately
> contact the sender and destroy the material in its entirety, whether in
> electronic or hard copy format. Thank you. Please refer to
> http://www.jpmorgan.com/pages/disclosures for disclosures relating to
> European legal entities.
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] create an xls file using data from a txt file

2011-05-11 Thread James Reynolds
your "\" is a "/"

when writing out a string, such as 'C:\test.xls', the "/" is an escape in
python. So you have two choices, You can either write out path
= 'C:\\test.xls', which will be 'C:\test.xls' or you can write out path =
r'C:\test.xls' the "r" bit tells python that the following is a regular
expression. or regex.

You can also use Walter's method above.

On Wed, May 11, 2011 at 1:10 PM, tax botsis  wrote:

> James,
> how would you save the workbook into a specific directory? I tried to run
> that:
>
> workbook.save('C:/test.xls')
>
> but I get the following error:
>
>
> Traceback (most recent call last):
>   File "", line 1, in 
> wbk.save("C:/test.xls")
>   File "C:\Python26\lib\site-packages\xlwt\Workbook.py", line 634, in save
> doc.save(filename, self.get_biff_data())
>   File "C:\Python26\lib\site-packages\xlwt\Workbook.py", line 615, in
> get_biff_data
> self.__worksheets[self.__active_sheet].selected = True
> IndexError: list index out of range
>
> Thanks
> Tax
>
>
> 2011/5/11 James Reynolds 
>
>> Slow day at work, so I tried something a little different mostly as a
>> learning exercise for myself, let me know what you all think.
>>
>> I thought it would be useful to have a writer that scales and that
>> organizes the data. For example, you might have 20 tests one day, and 5 the
>> next.
>>
>> I broke up the data into dictionaries where the IDs were keys, and
>> everything that follows is a tuple of testX and result.
>>
>> Instead of iterating through each column, it only writes to the columns
>> where data is present.
>>
>> Disclaimer: I am copying and pasting into Gmail, which sometimes screws up
>> indents.
>>
>> I also put it into pastebin, which was pretty exciting considering I have
>> never used it before:
>>
>> http://pastebin.com/2Dke5FtX
>>
>> import xlwt
>>
>>
>> class Parser:
>> '''
>> classdocs
>> '''
>>
>>
>> def __init__(self, test, result):
>> '''
>> Constructor
>> '''
>> self.result = result
>> self.test = test
>> self.id = int(self.test[4:])
>>
>> x = open('test.txt')
>>
>> id_dict = {}
>>
>> for all in x:
>> y = all.split(" ")
>> y[-1] = y[-1].strip()
>> id_dict[y[0]] = y[1:]
>>
>> max_test = 0
>> for key, lists in id_dict.items():
>> length = len(lists)/2
>> a = 0
>> parser_list = []
>> for items in range(length):
>> t = (lists[a], lists[a+1])
>> p = Parser(*t)
>> parser_list.append(p)
>> if max_test < p.id:
>> max_test = p.id
>> a +=2
>> id_dict[key] = parser_list
>>
>>
>> workbook = xlwt.Workbook()
>> worksheet = workbook.add_sheet("testruns", cell_overwrite_ok=True)
>> header = 'TEST{0}'
>> headers = ['ID']
>> range_id = range(max_test +1)
>> for all in range_id[1:]:
>> headers.append(header.format(all))
>>
>> for i, colno in enumerate(headers):
>> print i, type(i)
>> worksheet.write(0, i, colno)
>> rowno = 1
>> for keys, values in id_dict.items():
>> worksheet.write(rowno, 0, keys)
>> for object_lists in values:
>> worksheet.write(rowno, object_lists.id , object_lists.result)
>> rowno +=1
>>
>>
>> workbook.save("test.xls")
>>
>>
>>
>>
>> On Wed, May 11, 2011 at 9:58 AM, Walter Prins  wrote:
>>
>>>
>>>
>>> On 11 May 2011 14:34, tee chwee liong  wrote:
>>>
>>>>  hi all,
>>>>
>>>> thanks for this sharing. when i copy and run this code, i got this
>>>> error:
>>>>
>>>> Traceback (most recent call last):
>>>>   File "C:/Python25/myscript/excel/sampleexcel.py", line 1, in 
>>>> import csv
>>>>   File "C:/Python25/myscript/excel\csv.py", line 3, in 
>>>> w=csv.writer(open('output.csv','w'))
>>>> AttributeError: 'module' object has no attribute 'writer'
>>>>
>>>>
>>> Well, reading the error message, it's saying that module "csv", coming
>>> from file "C:/Python25/myscript/excel\
>>> csv.py" has no member "writer".  So, it seems you've called your test
>>> script (module) "csv" which effecitvely hid the standard python "csv"
>>> module.
>>>
>>> Try renaming your script file to something else ('testcsv.py' maybe) so
>>> its name doesn't conflict with the standard "csv" module and try again.
>>>
>>> Walter
>>>
>>> ___
>>>
>>> Tutor maillist  -  Tutor@python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>>
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] create an xls file using data from a txt file

2011-05-11 Thread James Reynolds
Slow day at work, so I tried something a little different mostly as a
learning exercise for myself, let me know what you all think.

I thought it would be useful to have a writer that scales and that organizes
the data. For example, you might have 20 tests one day, and 5 the next.

I broke up the data into dictionaries where the IDs were keys, and
everything that follows is a tuple of testX and result.

Instead of iterating through each column, it only writes to the columns
where data is present.

Disclaimer: I am copying and pasting into Gmail, which sometimes screws up
indents.

I also put it into pastebin, which was pretty exciting considering I have
never used it before:

http://pastebin.com/2Dke5FtX

import xlwt


class Parser:
'''
classdocs
'''


def __init__(self, test, result):
'''
Constructor
'''
self.result = result
self.test = test
self.id = int(self.test[4:])

x = open('test.txt')

id_dict = {}

for all in x:
y = all.split(" ")
y[-1] = y[-1].strip()
id_dict[y[0]] = y[1:]

max_test = 0
for key, lists in id_dict.items():
length = len(lists)/2
a = 0
parser_list = []
for items in range(length):
t = (lists[a], lists[a+1])
p = Parser(*t)
parser_list.append(p)
if max_test < p.id:
max_test = p.id
a +=2
id_dict[key] = parser_list


workbook = xlwt.Workbook()
worksheet = workbook.add_sheet("testruns", cell_overwrite_ok=True)
header = 'TEST{0}'
headers = ['ID']
range_id = range(max_test +1)
for all in range_id[1:]:
headers.append(header.format(all))

for i, colno in enumerate(headers):
print i, type(i)
worksheet.write(0, i, colno)
rowno = 1
for keys, values in id_dict.items():
worksheet.write(rowno, 0, keys)
for object_lists in values:
worksheet.write(rowno, object_lists.id , object_lists.result)
rowno +=1


workbook.save("test.xls")




On Wed, May 11, 2011 at 9:58 AM, Walter Prins  wrote:

>
>
> On 11 May 2011 14:34, tee chwee liong  wrote:
>
>>  hi all,
>>
>> thanks for this sharing. when i copy and run this code, i got this error:
>>
>> Traceback (most recent call last):
>>   File "C:/Python25/myscript/excel/sampleexcel.py", line 1, in 
>> import csv
>>   File "C:/Python25/myscript/excel\csv.py", line 3, in 
>> w=csv.writer(open('output.csv','w'))
>> AttributeError: 'module' object has no attribute 'writer'
>>
>>
> Well, reading the error message, it's saying that module "csv", coming from
> file "C:/Python25/myscript/excel\
> csv.py" has no member "writer".  So, it seems you've called your test
> script (module) "csv" which effecitvely hid the standard python "csv"
> module.
>
> Try renaming your script file to something else ('testcsv.py' maybe) so its
> name doesn't conflict with the standard "csv" module and try again.
>
> Walter
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to develop a python exe file in windows using python3.1

2011-04-14 Thread James Reynolds
We literally just answered this question a couple days ago, but if you need
to make an executable in 3.1, CX freeze i believe should work.

On Thu, Apr 14, 2011 at 9:42 AM, ema francis  wrote:

> I am using python3.1 in windows environment.How can I create a python
> executable file?
> I tried with py2exe package but it is not compatible with python3.1.Isthere 
> any other way...
> pls help me...
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python 3.2 - Running in Idle but not in command window

2011-04-13 Thread James Reynolds
Oh, belay my last, I misread the question. My apologies.

On Wed, Apr 13, 2011 at 1:04 PM, James Reynolds  wrote:

> I double clicked it from my desktop and it opens just fine (though I didn't
> attempt to run it, because I have 2.6 on my work machine and I'm sure that
> will cause it to fail).
>
> Have you added python to Path environment variables in windows?
>
> On Wed, Apr 13, 2011 at 11:14 AM, Gary Beynon wrote:
>
>>  -- Voice of a Noob! --
>>
>> I am currently running through Python Programming for the Absolute
>> Beginner and have written the attached program.
>>
>> It's not the code I've got a problem with (I think).
>>
>> In idle (Windows) when i press f5 it runs perfect but when I run it by
>> double click from folder the program ignores my input (from menu)
>>
>>
>>
>> I do have ArcGIS (Python 2.6) & Python 2.5 installed.  Are these causing a
>> problem?
>>
>> Thanks for your help.
>> Gary
>>
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python 3.2 - Running in Idle but not in command window

2011-04-13 Thread James Reynolds
I double clicked it from my desktop and it opens just fine (though I didn't
attempt to run it, because I have 2.6 on my work machine and I'm sure that
will cause it to fail).

Have you added python to Path environment variables in windows?

On Wed, Apr 13, 2011 at 11:14 AM, Gary Beynon wrote:

>  -- Voice of a Noob! --
>
> I am currently running through Python Programming for the Absolute Beginner
> and have written the attached program.
>
> It's not the code I've got a problem with (I think).
>
> In idle (Windows) when i press f5 it runs perfect but when I run it by
> double click from folder the program ignores my input (from menu)
>
>
>
> I do have ArcGIS (Python 2.6) & Python 2.5 installed.  Are these causing a
> problem?
>
> Thanks for your help.
> Gary
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Retrieve data

2011-04-12 Thread James Reynolds
NYtimes has an API http://developer.nytimes.com/

No clue on how well it works or even if the
weather is in the API. Looks like a lot of fluff, like comments and such.

At any rate, maybe you can request they add weather to their API.

On Tue, Apr 12, 2011 at 12:36 PM,  wrote:

> Hello everyone,
>
> I would to retrieve data, and especially the temperature and the weather
> from http://www.nytimes.com/weather. And I don't know how to do so.
>
> Thank you,
>
> Louis
> Sent from my BlackBerry® on the MetroPCS Network
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Running python on windows

2011-04-11 Thread James Reynolds
At least in my case it was about simplicity. If it was a simple matter of
using a base python program, that would be one thing, but the last program
i distributed here at work used pygtk as it's GUI (which at the time
required four different packages, I believe they have consolidated this down
to one, thank god), a month / date arithmetic module a few other modules I
can't remember off the top of my head.

It doesn't make sense to say, go here, install this, ok, now drop this in
this folder, ok now drop this in that folder, ok now open your command
prompt and type this string of words. But don't typo while your at it.

It took all of five minutes to learn how to use CX enough so I could freeze
something and send it around to people here to use. It would have taken 30
minutes to explain how to install each component to people who just want
stuff to work.

On Mon, Apr 11, 2011 at 4:44 PM, Alan Gauld wrote:

>
> "Mike Silverson"  wrote
>
>  installed on the target computer.  I am trying to send a program to a
>> friend
>> using windows and he does not have python installed, and does not want to
>> take the time to install it.
>>
>
> Given how quickly Python installs compared to many other apps I
> can only assume he uses Wordpad as his word processor?! Honestly
> you could just build an installer that installed Python and your files
> and I doubt he'd notice the install time as being excessive!
>
> However, there is no way to run Python without installing an interpreter.
> If you don't use a standalone install you need to build the interpreter
> into an exe and then install a separate python installation for every app
> he uses. Its mad. Does he refuse to install .Net or Java or the
> VisualBasic runtime?
>
> But if he must there are several options available, the best known
> is py2exe but there are others out there.
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Running python on windows

2011-04-11 Thread James Reynolds
I use http://cx-freeze.sourceforge.net/ personally. I found py2exe to be a
headache compared to cx.

On Mon, Apr 11, 2011 at 9:01 AM, Mike Silverson wrote:

> Hi, I need to know if there is any way to run a python file without Python
> installed on the target computer.  I am trying to send a program to a friend
> using windows and he does not have python installed, and does not want to
> take the time to install it.  Is there any way to send him the file (or a
> group of files) that will run right away?
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] counting a list of elements

2011-04-01 Thread James Reynolds
The nice thing about Python is you don't have to build things from scratch,
and I imagine most people would discourage on account of it being a waste of
time, other then education value.

But the "best practice" in my humble opinion would be to use the built in
len function. If what you are after is to see how often 1e3 comes up in your
list, then you would use list.count('1e3').

In general, its best to use the python built ins.


On Fri, Apr 1, 2011 at 1:16 PM, Karim  wrote:

>
>
> Hello,
>
> I would like to get advice on the best practice to count elements in a list
> (built from scractch).
> The number of elements is in the range 1e3 and 1e6.
>
> 1) I could create a generator and set a counter (i +=1) in the loop.
>
> 2) or simply len(mylist).
>
> I don't need the content of the list, indeed, in term of memory I don't
> want to wast it. But I suppose len() is optimized too (C impementation).
>
> If you have some thought to share don't hesitate.
>
> Karim
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Data frame packages

2011-03-31 Thread James Reynolds
On Thu, Mar 31, 2011 at 11:10 AM, Blockheads Oi Oi
wrote:

> On 31/03/2011 09:38, Ben Hunter wrote:
>
>> Is anybody out there familiar with data frame modules for python that
>> will allow me to read a CSV in a similar way that R does? pydataframe
>> and DataFrame have both befuddled me. One requires a special stripe of R
>> that I don't think is available on windows and the other is either very
>> buggy or I've put it in the wrong directory / installed incorrectly.
>> Sorry for the vague question - just taking the pulse. I haven't seen any
>> chatter about this on this mailing list.
>>
>>
>>
> What are you trying to achieve?  Can you simply read the data with the
> standard library csv module and manipulate it to your needs?What makes
> you say that the code is buggy, have you examples of what you tried and
> where it was wrong?  Did you install with easy_install or run setup.py?
>
>
>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
> Regards.
>
> Mark L.
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>














I'm not familiar with it, but what about http://rpy.sourceforge.net/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] String formatting question.

2011-03-29 Thread James Reynolds
On Tue, Mar 29, 2011 at 4:21 PM, Corey Richardson  wrote:

> On 03/29/2011 03:41 PM, Prasad, Ramit wrote:
> > Is there a difference (or preference) between using the following?
> > "%s %d" % (var,num)
> > VERSUS
> > "{0} {1}".format(var,num)
> >
> >
> > Ramit
>
> If you're using Python 3, use the second one. If you're using Python 2,
> you have no option but to use the first, as far as I know. Maybe Python
> 2.7 has that formatting, I'm not sure.
>
> --
> Corey Richardson
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>




you can use string{0}.format(var) in python 2.6. I use it all the time. I
never use the other % method.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] if value not in dictionary, do a?

2011-03-25 Thread James Reynolds
On Fri, Mar 25, 2011 at 7:52 AM, Robert Sjoblom wrote:

> Hi again, list! A quick question about dictionary behaviour. I have a
> dictionary of keys, and the user should be able to enter values into
> said dictionary. My idea was this:
>
> def addData(key, value):
>dictionary[key] += int(value)
>return None
>
> dictionary = {"a":0, "b":0, "c":0, "d":0}
>
> for key in dictionary:
>a = input("Enter key: ")
>b = int(input("Enter value: "))
>try:
>addData(a, b)
>except:
>continue
>
> Which works fine, but the problem is that I need to ensure that every
> key gets a value above 0; the try/except is clearly not doing that
> (and it can't deal with b=int(input("Enter value:" )) because there's
> no try for that, which I suppose there should be). How would I go
> about making sure that each key gets a value above 0 in this case?
> Also, is there a better way to do what I'm trying to do than what I've
> come up with? I'm trying to translate a paper form into data arrays
> for later use (and this particular part is simple in comparison to
> some other parts where you get one name and multiple values to that
> name, which I have no idea how to solve, but I figure one step at a
> time, and the current step is this one), but I'm quite the newbie at
> programming. Still.
>
> best regards,
> Robert S.
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>















How would I go
> about making sure that each key gets a value above 0 in this case?


I would probably add a separate function with an if / then type structure.
The separate function would simply be activated if the value is 0, at which
point the input would say "You didn't enter a value greater than 0, please
enter a value" or some such.

Also, is there a better way to do what I'm trying to do than what I've
> come up with?


I'm not 100% what you are trying to accomplish.

 I'm trying to translate a paper form into data arrays
> for later use (and this particular part is simple in comparison to
> some other parts where you get one name and multiple values to that
> name


This sounds like a database. For example, I have many attributes, some of
these I share with others, some are unique to me, some are variations on a
common theme.

So, for example, Jamie is 6'00, brown eyes, brown hair, etc. Or {Jamie :
[72, Brown, Brown,...]}

You can store the attributes in a list so long as they are always in the
same order, and then just look up the attributes as you need them, so
person[Jamie][0] will yield 72.

The other way to go, depending on your data of course and its complexity
would be to use a relational database. Python comes with SQlite in it, and
if you don't know SQL, this could be a good opportunity to learn some of
it.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Saving information for my program

2011-03-21 Thread James Reynolds
On Mon, Mar 21, 2011 at 11:11 AM, michael scott wrote:

> I apologize now but I'm going to be spamming  the tutor list as I have just
> decided to create an extremely ambitious project for someone of my level.
> Anyhow, I will start with my first question.
>
> How do I save user created information in python?
>
> In my progam I will have users input various "attributes" of people they
> like (age, height, movies they have been in, songs they sung in, favorite
> part of them,  important links dealing with them, etc), and I'd like to know
> how to save these things so that even after you stop running the program
> they are saved and when you start the program again, these variables are
> loaded. This part of my program will be sort of like an
> offline-wiki-gui-thingie.
>
> I was planning on using classes for each person so that I could store their
> attributes that way .
> jessica = Profile()
> jessica.name = "jessica ngorn"
> jessica.age = 25
> jessica.favorite_song = "chinpo no  uta"
>
> I was thinking I have 2 options, which is save the information to a text
> file a write / read it in every session, but I have no idea how to do this
> with class attributes. I know how to do it for like a paragraph of text, but
> I have no idea how to do it with classes and their attributes.
>
> The other option I was thinking about was using the pickle module. I have
> never used it, but I read the documentation, and I'm not exactly sure how to
> use it... it says it only saves the class "name", but not the body (same for
> functions), but how would that help me?
>
> Well if you can contribute to helping me please do. Linking me to stuff to
> read is great, explaining it here is great, writing short example code is
> great too, anything helps.
> 
> What is it about you... that intrigues me so?
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>







This would probably be a good opportunity for you to learn about SQL and
specifically SQlite3, which comes with current versions of Python. For what
you are describing, you could probably have a single table in a database
handle all of this. For it to populate immediately, have your program call
in its __init__ whatever program you have to extract all the data from the
database, then create all of  your Profile objects.

I think if you just read up on SQlite3 and what it can do, or SQL more
generally, you will have an Aha! moment on your own.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Processing Financial Calculations using Python

2011-03-16 Thread James Reynolds
For all of these, I wrote my own class with methods to create the correct
output. there is not built in python functionality that I know, although
there may be a package.

For IRR, the method expects a list and at least one negative value. I
believe the way I did NPV was a dictionary, where the key was the discount
rate and the value was a list of cash flows.

For NPV specifically, I wrote this as a C module, but I need to rewrite this
because I didn't know much about C at the time. It works and all, but I feel
it could be more efficient. For my purposes, NPV and IRR calculations are
fairly slow using native Python and you will may want to consider writing
some of this in C as a python extension if you can. My view is if you aren't
doing a large number of calculations, just use excel. If you are, speed
becomes an issue.

On Tue, Mar 15, 2011 at 8:00 PM, Carla Jenkins wrote:

> Are there specific Python commands to process present value, future value
> and net present value?  Thanks.
>
> Sincerely,
> Carla Jenkins
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


  1   2   >