Re: How to print something only if it exists?

2012-09-07 Thread Hans Mulder
On 6/09/12 19:59:05, tinn...@isbd.co.uk wrote:
> I want to print a series of list elements some of which may not exist,
> e.g. I have a line:-
> 
>  print day, fld[1], balance, fld[2]
> 
> fld[2] doesn't always exist (fld is the result of a split) so the
> print fails when it isn't set.

How about:

 print day, fld[1], balance, fld[2] if len(fld) > 2 else ''


If you really want to avoid the keyword 'if', then you'd have to
do something like:

 print day, fld[1], balance, (fld[2:3] or [''])[0]

That may be shorter, but it isn't very readable.


Hope this helps,

-- HansM
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python newbie here! No module named settings

2012-09-07 Thread chandraganeshchowdary
On Thursday, June 2, 2011 8:59:48 PM UTC+5:30, Neeraj Agarwal wrote:
> Hello all,
> 
> I'm a newbie to Python and its my 2nd day exploring it.
> 
> I was trying to use Python wrapper for Google Charts API and was
> tweaking the examples.
> https://github.com/gak/pygooglechart/raw/master/examples/pie.py
> 
> This is the script which I was trying.
> 
> And the python interpreter gives the following error:
> import settings
> ImportError: No module named settings
> 
> I installed Django as well before this (if its causing the problem,
> dunno)
> 
> Please help me.
> 
> Thanks,
> Neeraj
hi neeraj, 
I am also experiencing the same problem and in my pygooglechart file i am not 
having both settings.py and __init__.py file so can you send me the link from 
where you downloaded api
 Best Regards,
ganesh
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Accessing dll

2012-09-07 Thread Chris Angelico
On Fri, Sep 7, 2012 at 1:44 AM, Helpful person  wrote:
> FYI
>
> My Python version is 2.5.4

You may wish to upgrade, that's quite an old version. Unless
something's binding you to version 2.x, I would strongly recommend
migrating to 3.2 or 3.3.

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Division help in python

2012-09-07 Thread Ramyasri Dodla
Hi All,

I am brand new to python. checking over basic stuff. I came across the
problem while doing so. If any body aware of the problem, kindly respond me.

>>> 5/10
0
>>> - 5/10
-1

The second case also should yield a 'zero' but it is giving a -1

some other examples for your review.

>>> -10/5
-2
>>> -5/-5
1
>>> 1/2
0
>>> -1/2
-1
>>> -1 /4
-1

I would be thankful to  you if i got through this.


Ramya
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Division help in python

2012-09-07 Thread Chris Angelico
On Fri, Sep 7, 2012 at 10:53 PM, Ramyasri Dodla  wrote:
> I am brand new to python. checking over basic stuff. I came across the
> problem while doing so. If any body aware of the problem, kindly respond me.
>
 5/10
> 0
 - 5/10
> -1
>
> The second case also should yield a 'zero' but it is giving a -1

You're clearly using Python 2, because in Python 3, the / operator
will return a float instead (so these would return 0.5 and -0.5
respectively). But it's helpful to mention what Python version you're
using when you ask for help :)

The reason for this is that / (or in Python 3, //) rounds toward
negative infinity, not toward zero. This allows the modulo operator
(%) to return a positive number, while still maintaining the normal
expectation that:

(x//y)*y + (x%y) == x

for any two integers x and y.

Hope that helps!

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to print something only if it exists?

2012-09-07 Thread Roy Smith
In article <9s4nh9-8dr@chris.zbmc.eu>, tinn...@isbd.co.uk wrote:

> I want to print a series of list elements some of which may not exist,
> e.g. I have a line:-
> 
>  print day, fld[1], balance, fld[2]
> 
> fld[2] doesn't always exist (fld is the result of a split) so the
> print fails when it isn't set.
> 
> I know I could simply use an if but ultimately there may be more
> elements of fld in the print and the print may well become more
> complex (most like will be formatted for example).  Thus it would be
> good if there was some way to say "print this if it exists".

One possible way is a trick I've used in the past.

fld = split(...) + ['']*10

this guarantees that fld has at least 10 elements.  If you want to 
guarantee that fld has *exactly* 10 elements, just take [0:10] of that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bitshifts and "And" vs Floor-division and Modular

2012-09-07 Thread Mark Lawrence

On 07/09/2012 02:08, Cameron Simpson wrote:

On 07Sep2012 01:30, Mark Lawrence  wrote:
| On 07/09/2012 01:01, jimbo1qaz wrote:
| > Is it faster to use bitshifts or floor division? And which is better, & or 
%?
| > All divisors and mods are power of 2, so are binary operations faster? And 
are they considered bad style?
|
| Why don't you use the timeit module and find out for yourself?

Because timeit doesn't output style advice?
Because timeit won't offer even a short single parapgraph description
of how python ints (even just in CPython) are implemented and how that
may affect performance in general?

To the OP: personally, I would suggest using % when I am thinking of
division and a bit shift when I am thinking of a bitshift, and only reach
for timeit when performance becomes an issue. Code for the algoritm,
and only optimise later.

Of course only a well run benchmark will measure the real world, but it
possible to address his other questions in a helpful fashion and address
the benchmark question in a less offputting tone. If you can't be
bothered, please don't. (Especially since these irritating posts from
you are usually in response to a post you feel could have used more
effort from the OP.)

Nobody answers all performance considerations or design choices with an
exhaustive timeit benchmark, and it is silly to suggest so. It is
helpful for people to have a mental model of the python internals
so they can make often-sensible choices from the start.

So try being helpful instead of slapping people down when they haven't
reached your private bar.

Cheers,



I'm sorry but I refuse point blank to spoon feed, fit bibs and change 
nappies.  I wouldn't do that on the tutor mailing list and I certainly 
wouldn't do it here.  If any OP is too bone idle to do some research and 
then pose a sensible question relating to what they want to achieve, 
what they've done to achieve it and what issues they've got then I 
intend responding in the same way.  Clearly your approach is different 
so we'll have to agree to disagree.


--
Cheers.

Mark Lawrence.

--
http://mail.python.org/mailman/listinfo/python-list


Defining features in a list

2012-09-07 Thread M Whitman
Good Morning,

I have been recently trying to define all of the features in a list but have 
been running into errors.  I would like to define the features similar to the 
following print statement.  Any advice would be appreciated.  I'm trying to 
transition my output from a text file to excel and if I can loop through my 
lists and define them that transition will be cleaner.

Many Thanks,

-Matt

#Author: MGW
#2012 
import os, datetime, sys, arcpy, xlrd
from arcpy import env
submission = "Rev.mdb"
env.workspace = "C:/temp/"+submission+"/Water"

#Get Submission totals
fclist = sorted(arcpy.ListFeatureClasses("*"))
for fc in fclist:
print fc+"="+str(arcpy.GetCount_management(fc).getOutput(0))

print "Complete"
raw_input("Press ENTER to close this window") 

Output Generated
WATER_Net_Junctions=312
WS_Hyd=484
WS_Mains=2752
WS_Node=4722
WS_Vlvs=1078
WS_WatLats=3661
WS_WatMtrs=3662
WTRPLANTS_points=0
WTRPUMPSTA_points=0
WTRTANKS=0
WTR_ARV=10
WTR_MISC=0
Complete
Press ENTER to close this window

#Get Submission totals
fclist = sorted(arcpy.ListFeatureClasses("*"))
for fc in fclist:
fc=str(arcpy.GetCount_management(fc).getOutput(0))
#TEST
print WS_Hyd
   

print "Complete"
raw_input("Press ENTER to close this window") 

Output Generated
Traceback (most recent call last):
  File "C:\Documents and Settings\mattheww\Desktop\Copy of QAQCexce_2.py", line 
14, in 
print WS_Hyd
NameError: name 'WS_Hyd' is not defined
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bitshifts and "And" vs Floor-division and Modular

2012-09-07 Thread Grant Edwards
On 2012-09-07, Steven D'Aprano  wrote:

> My *guess* is that you mean *bitwise* operators, compared to numeric 
> operators like * and // (integer division). The runtime cost is mostly 
> dominated by the object-oriented overhead -- Python is not C or assembly,
> and the integers are rich objects, not low-level bitfields, so the 
> difference between division and bitshifting is much less than you might 
> expect from assembly language.

I don't suppose there's much of a chance that the OP is running Python
on a CPU that doesn't have an integer divide instruction?  If that
_were_ the case, the difference would be more noticable, but would
still probably not worth worrying about unless a truely huge number of
operations were being done in a very tight loop with no intervening
I/O operations.

-- 
Grant Edwards   grant.b.edwardsYow! I have accepted
  at   Provolone into my life!
  gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Function for examine content of directory

2012-09-07 Thread Tigerstyle
kl. 16:56:29 UTC+2 torsdag 6. september 2012 skrev Tigerstyle følgende:
> Hi guys,
> 
> 
> 
> I'm trying to write a module containing a function to examine the contents of 
> the current working directory and print out a count of how many files have 
> each extension (".txt", ".doc", etc.)
> 
>  
> 
> This is the code so far:
> 
> --
> 
> import os
> 
> 
> 
> path = "v:\\workspace\\Python2_Homework03\\src\\"
> 
> dirs = os.listdir( path )
> 
> filenames = {"this.txt", "that.txt", 
> "the_other.txt","this.doc","that.doc","this.pdf","first.txt","that.pdf"}
> 
> extensions = []
> 
> for filename in filenames:
> 
> f = open(filename, "w")
> 
> f.write("Some text\n")
> 
> f.close()
> 
> name , ext = os.path.splitext(f.name)
> 
> extensions.append(ext)
> 
> 
> 
> # This would print all the files and directories
> 
> for file in dirs:
> 
> print(file)
> 
> 
> 
> for ext in extensions:
> 
> print("Count for %s: " %ext, extensions.count(ext))
> 
> 
> 
> --
> 
> 
> 
> When I'm trying to get the module to print how many files each extension has, 
> it prints the count of each ext multiple times for each extension type. Like 
> this:
> 
> 
> 
> this.pdf
> 
> the_other.txt
> 
> this.doc
> 
> that.txt
> 
> this.txt
> 
> that.pdf
> 
> first.txt
> 
> that.doc
> 
> Count for .pdf:  2
> 
> Count for .txt:  4
> 
> Count for .doc:  2
> 
> Count for .txt:  4
> 
> Count for .txt:  4
> 
> Count for .pdf:  2
> 
> Count for .txt:  4
> 
> Count for .doc:  2
> 
> 
> 
> Any help is appreciated.
> 
> 
> 
> T

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Function for examine content of directory

2012-09-07 Thread Tigerstyle
Ok I'm now totally stuck.

This is the code:

---
import os
from collections import Counter
 
path = ":c\\mypath\dir"
dirs = os.listdir( path )
filenames = {"this.txt", "that.txt", 
"the_other.txt","this.doc","that.doc","this.pdf","first.txt","that.pdf"}
extensions = []
for filename in filenames:
f = open(filename, "w")
f.write("Some text\n")
f.close()
name , ext = os.path.splitext(f.name)
extensions.append(ext)

# This would print all the files and directories
for file in dirs:
print(file)



for ext, count in Counter(extensions).items(): 
print("Count for %s: " % ext, count) 

---

I need to make this module into a function and write a separate module to 
verify by testing that the function gives correct results.

Help and pointers are much appreciated.

T


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Defining features in a list

2012-09-07 Thread Dave Angel
On 09/07/2012 09:42 AM, M Whitman wrote:
> Good Morning,
>
> I have been recently trying to define all of the features in a list but have 
> been running into errors.

How proficient are you in Python?  Could you possibly use terms which
make sense to someone who doesn't know this arcGIS program?  I'm just
making a wild guess that that's what you're importing with the arcpy
import.  When I do an internet search on arcpy, I see lots of tutorials,
training, etc.  I didn't find a mailing list, but there probably is one.

The term that needs translating is "feature.'

>   I would like to define the features similar to the following print 
> statement.  Any advice would be appreciated.  I'm trying to transition my 
> output from a text file to excel and if I can loop through my lists and 
> define them that transition will be cleaner.
>
> Many Thanks,
>
> -Matt
>
> #Author: MGW
> #2012 
> import os, datetime, sys, arcpy, xlrd
> from arcpy import env
> submission = "Rev.mdb"
> env.workspace = "C:/temp/"+submission+"/Water"
>
> #Get Submission totals
> fclist = sorted(arcpy.ListFeatureClasses("*"))
> for fc in fclist:
> print fc+"="+str(arcpy.GetCount_management(fc).getOutput(0))
>
> print "Complete"
> raw_input("Press ENTER to close this window") 
>
> Output Generated
> WATER_Net_Junctions=312
> WS_Hyd=484
> WS_Mains=2752
> WS_Node=4722
> WS_Vlvs=1078
> WS_WatLats=3661
> WS_WatMtrs=3662
> WTRPLANTS_points=0
> WTRPUMPSTA_points=0
> WTRTANKS=0
> WTR_ARV=10
> WTR_MISC=0
> Complete
> Press ENTER to close this window
>
> #Get Submission totals
> fclist = sorted(arcpy.ListFeatureClasses("*"))
> for fc in fclist:
> fc=str(arcpy.GetCount_management(fc).getOutput(0))
> #TEST
> print WS_Hyd
>   
There's no variable WS_Hyd, so what did you expect it to do?  Do you
want to be able to fetch the values by name that were printed above?  if
so, I'd suggest a dict, not a list.  Lists don't have names for each
element, just indices.


>  
> 
> print "Complete"
> raw_input("Press ENTER to close this window") 
>
> Output Generated
> Traceback (most recent call last):
>   File "C:\Documents and Settings\mattheww\Desktop\Copy of QAQCexce_2.py", 
> line 14, in 
> print WS_Hyd
> NameError: name 'WS_Hyd' is not defined

As a very rough start, perhaps you could try something like this. 
Remember i don't have the docs, so the only clue I've got is the stuff
you printed from the first loop.

table = {}

fclist = sorted(arcpy.ListFeatureClasses("*"))
for fc in fclist:
table[fc] = +str(arcpy.GetCount_management(fc).getOutput(0))

Now, if you want to print the value for WS_Hyd, it should be available as

print "value = ", table["WS_Hyd"]

If you're sufficiently advanced, i could suggest a class-based solution
where you'd access items by
 mytable.WS_Hyd

But if you're not yet familiar with class definition and attributes and
such, we'd better not go there.

-- 

DaveA

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Defining features in a list

2012-09-07 Thread M Whitman
Dave- By features I was refering to items in the list.  For background the 
arcpy module is used for geoprocessing of geographic information.  I'm using my 
script to get totals for features in a dataset that I receive on a regular 
basis- for example total number of hydrants, total number of hydrants with null 
or missing attributes, and total number of hydrants with outlining attributes.

I am experienced particularly with the arcpy module and I am trying deligently 
to become more experienced with Python in general.  My goal is to fetch values 
by name and then print output by name. print WS_Hyd and then see "484".   I 
have some experience with class definition but a dictionary might be the way to 
go.  I was understanding the response of the Arcpy module but hadn't understood 
why the list wasn't being defined in my previous loop statement.  I appreciate 
the response.  I will look into dict if you have a class definition suggestion 
I will run with that.  Thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Defining features in a list

2012-09-07 Thread Jean-Michel Pichavant

M Whitman wrote:

Good Morning,

I have been recently trying to define all of the features in a list but have 
been running into errors.  I would like to define the features similar to the 
following print statement.  Any advice would be appreciated.  I'm trying to 
transition my output from a text file to excel and if I can loop through my 
lists and define them that transition will be cleaner.

Many Thanks,

-Matt

#Author: MGW
#2012 
import os, datetime, sys, arcpy, xlrd

from arcpy import env
submission = "Rev.mdb"
env.workspace = "C:/temp/"+submission+"/Water"

#Get Submission totals
fclist = sorted(arcpy.ListFeatureClasses("*"))
for fc in fclist:
print fc+"="+str(arcpy.GetCount_management(fc).getOutput(0))

print "Complete"
raw_input("Press ENTER to close this window") 


Output Generated
WATER_Net_Junctions=312
WS_Hyd=484
WS_Mains=2752
WS_Node=4722
WS_Vlvs=1078
WS_WatLats=3661
WS_WatMtrs=3662
WTRPLANTS_points=0
WTRPUMPSTA_points=0
WTRTANKS=0
WTR_ARV=10
WTR_MISC=0
Complete
Press ENTER to close this window

#Get Submission totals
fclist = sorted(arcpy.ListFeatureClasses("*"))
for fc in fclist:
fc=str(arcpy.GetCount_management(fc).getOutput(0))
#TEST
print WS_Hyd
   

print "Complete"
raw_input("Press ENTER to close this window") 


Output Generated
Traceback (most recent call last):
  File "C:\Documents and Settings\mattheww\Desktop\Copy of QAQCexce_2.py", line 14, 
in 
print WS_Hyd
NameError: name 'WS_Hyd' is not defined
  
I'm not sure I've understood everything, is this something you're 
searching for:


fcDict = dict([(str(fc), 
str(arcpy.GetCount_management(fc).getOutput(0))) ) for fc in 
sorted(arcpy.ListFeatureClasses("*")) ])


print fcDict
print fcDict['WS_Hyd']

This is difficult to read because of the online statement, but it does 
basically the following pseudo code:


fcDict = dict([(feature.name, feature.value) for feature in featureList ])

Cheers,

JM

--
http://mail.python.org/mailman/listinfo/python-list


Re: Defining features in a list

2012-09-07 Thread Dave Angel
On 09/07/2012 11:21 AM, M Whitman wrote:
> Dave- By features I was refering to items in the list.  For background the 
> arcpy module is used for geoprocessing of geographic information.  I'm using 
> my script to get totals for features in a dataset that I receive on a regular 
> basis- for example total number of hydrants, total number of hydrants with 
> null or missing attributes, and total number of hydrants with outlining 
> attributes.
>
> I am experienced particularly with the arcpy module and I am trying 
> deligently to become more experienced with Python in general.  My goal is to 
> fetch values by name and then print output by name. print WS_Hyd and then see 
> "484".   I have some experience with class definition but a dictionary might 
> be the way to go.  I was understanding the response of the Arcpy module but 
> hadn't understood why the list wasn't being defined in my previous loop 
> statement.

There is a list fclist being defined, just before the loop.  But that
list contains the names of the "features" not the values.  So if you
wanted, you could make a second list containing the values, or you could
even make a list containing tuples with name & value.  But assuming
there's no particular ordering you care about, that's what a dictionary
is good at.

In either case that loop is not creating extra variables with names like
WS_Hyd.  Creating variables with arbitrary names from data can only be
done with code that's dangerous and prone to injection attacks.  You can
avoid the problem by putting them in some namespace, either a
dictionary, or a namedtuple, or a custom class.

>   I appreciate the response.  I will look into dict if you have a class 
> definition suggestion I will run with that.  Thanks

Anyway, once you have the dictionary, you can indeed work on the values
in it, in various ways.

table = {}

fclist = sorted(arcpy.ListFeatureClasses("*"))
for fc in fclist:
table[fc] = +str(arcpy.GetCount_management(fc).getOutput(0))



Now you can use your captured data to do further processing.  Simplest example 
printing.  Suppose order doesn't matter:

for key in table.iterkeys():
print key, "=", table[key]

You could also do this as:

for key, value in table.iteritems():
print key, "=", value

If you want them in the original order, you can use your fclist, which is a 
list of keys:

for key in fclist:
print key, "=", table[key]

And of course if you want any particular one, you can do

print table["WS_hyd"]

Note that in the last case, if you typed the literal key wrong, or if the arcpy 
removed or renamed one of the keys, you'd get an exception there.  To avoid 
that, you might do something like:

key = "WS_hyd"
if key in table:
print table[key]


-- 

DaveA

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Division help in python

2012-09-07 Thread Jean-Michel Pichavant

Ramyasri Dodla wrote:

Hi All,

I am brand new to python. checking over basic stuff. I came across the 
problem while doing so. If any body aware of the problem, kindly 
respond me.


>>> 5/10
0
>>> - 5/10
-1

The second case also should yield a 'zero' but it is giving a -1


Why should it yield 'zero' ?
The definition of the euclidean division : 
(http://en.wikipedia.org/wiki/Euclidean_division)


a = b*q +r with 0≤ r < |b|

With the constraint of r being a positive integer, the couple (q, r) is 
unique:


with a=-5, b=10

-5 = 10*-1 + 5 (q=-1, r=+5)

Note that for the strict Euclidean division, I mean the one allowing r 
to be negative, then


-5 = 10*0 - 5 (q=0, r=-5) is also valid, but I there's still no reason 
to state that it SHOULD be prefered over the other solution.


The uniqueness of the solution for the 1st definition is probably what 
makes python yield -1 instead of 0.


Cheers,

JM



--
http://mail.python.org/mailman/listinfo/python-list


Re: Bitshifts and "And" vs Floor-division and Modular

2012-09-07 Thread rusi
On Sep 7, 9:32 am, Paul Rubin  wrote:
> rusi  writes:
> > On an 8086/8088 a MUL (multiply) instruction was of the order of 100
> > clocks ...  On most modern processors (after the pentium) the
> > difference has mostly vanished.  I cant find a good data sheet to
> > quote though
>
> See http://www.agner.org/optimize/:

Hey Thanks! Seems like a nice resource!  How on earth does he come up
with the data though, when Intel does not publish it?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bitshifts and "And" vs Floor-division and Modular

2012-09-07 Thread Dave Angel
On 09/07/2012 12:59 PM, rusi wrote:
> On Sep 7, 9:32 am, Paul Rubin  wrote:
>> rusi  writes:
>>> On an 8086/8088 a MUL (multiply) instruction was of the order of 100
>>> clocks ...  On most modern processors (after the pentium) the
>>> difference has mostly vanished.  I cant find a good data sheet to
>>> quote though
>> See http://www.agner.org/optimize/:
> Hey Thanks! Seems like a nice resource!  How on earth does he come up
> with the data though, when Intel does not publish it?

As he says on the home page, he measured the data himself.  Unclear how
repeatable such data may be, either due to environment or to multiple
versions of the processor, and from two vendors.

-- 

DaveA

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Accessing dll

2012-09-07 Thread Helpful person
On Sep 7, 5:16 am, Chris Angelico  wrote:
> On Fri, Sep 7, 2012 at 1:44 AM, Helpful person  wrote:
> > FYI
>
> > My Python version is 2.5.4
>
> You may wish to upgrade, that's quite an old version. Unless
> something's binding you to version 2.x, I would strongly recommend
> migrating to 3.2 or 3.3.
>
> ChrisA

Upgrading is not possible due to the large number of programs using
the early version.
-- 
http://mail.python.org/mailman/listinfo/python-list


Reusable (local) Modules

2012-09-07 Thread Travis Griggs
I'm relatively new to Python (coming from strong C and Smalltalk backgrounds). 
I've written a couple of relatively small apps (one or two .py files). I'm 
using PyCharm (I love it).

I'm curious what the pythonic approach is to creating your own reusable 
modules. Any tutorials or high level explanations, or detailed, much 
appreciated. 

For example, I have a small module called valvenumbers.py. It's a family of 
functions that we use to do a variety of things with the serial numbers we 
attach to some of our products. Now I'm making a little desktop app using 
wxpython, and I want to use (import) that module. Using PyCharm, I have two 
separate projects in sibling directories. And there's another separate command 
line tool that wants to do the same. Currently, I just place a symlink to the 
valvenumbers.py, local to the directory of these apps. This seems like "the 
quickest thing that could possibly work", but I'm assuming there's a more 
pythonic way to approach this general problem.

TIA!

Travis Griggs
"Simplicity is the ultimate sophistication." -- Leonardo Da Vinci

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reusable (local) Modules

2012-09-07 Thread Dave Angel
On 09/07/2012 01:56 PM, Travis Griggs wrote:
> I'm relatively new to Python (coming from strong C and Smalltalk 
> backgrounds). I've written a couple of relatively small apps (one or two .py 
> files). I'm using PyCharm (I love it).
>
> I'm curious what the pythonic approach is to creating your own reusable 
> modules. Any tutorials or high level explanations, or detailed, much 
> appreciated. 
>
> For example, I have a small module called valvenumbers.py. It's a family of 
> functions that we use to do a variety of things with the serial numbers we 
> attach to some of our products. Now I'm making a little desktop app using 
> wxpython, and I want to use (import) that module. Using PyCharm, I have two 
> separate projects in sibling directories. And there's another separate 
> command line tool that wants to do the same. Currently, I just place a 
> symlink to the valvenumbers.py, local to the directory of these apps. This 
> seems like "the quickest thing that could possibly work", but I'm assuming 
> there's a more pythonic way to approach this general problem.
>
> TIA!
>
> Travis Griggs
> "Simplicity is the ultimate sophistication." -- Leonardo Da Vinci
>

import sys
print sys.path

This will show you your path for imports.  The actual directories change
by default with different python versions, but one of them will be
suitable for putting new modules to be imported.  Naturally, you don't
want to add to the place where the stdlib is placed, but some of those
are normal writable directories.

-- 

DaveA

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reusable (local) Modules

2012-09-07 Thread Dave Angel
On 09/07/2012 01:56 PM, Travis Griggs wrote:
> I'm relatively new to Python (coming from strong C and Smalltalk 
> backgrounds). I've written a couple of relatively small apps (one or two .py 
> files). I'm using PyCharm (I love it).
>
> I'm curious what the pythonic approach is to creating your own reusable 
> modules. Any tutorials or high level explanations, or detailed, much 
> appreciated. 
>
> For example, I have a small module called valvenumbers.py. It's a family of 
> functions that we use to do a variety of things with the serial numbers we 
> attach to some of our products. Now I'm making a little desktop app using 
> wxpython, and I want to use (import) that module. Using PyCharm, I have two 
> separate projects in sibling directories. And there's another separate 
> command line tool that wants to do the same. Currently, I just place a 
> symlink to the valvenumbers.py, local to the directory of these apps. This 
> seems like "the quickest thing that could possibly work", but I'm assuming 
> there's a more pythonic way to approach this general problem.
>
> TIA!
>
> Travis Griggs
> "Simplicity is the ultimate sophistication." -- Leonardo Da Vinci
>

import sys
print sys.path

This will show you your path for imports.  The actual directories change
by default with different python versions, but one of them will be
suitable for putting new modules to be imported.  Naturally, you don't
want to add to the place where the stdlib is placed, but some of those
are normal writable directories. There are also several ways to add your
own directories to that path, but maybe you don't need that complexity yet.

I'm sure others will be able to be more specific.

-- 

DaveA

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Division help in python

2012-09-07 Thread Serhiy Storchaka
On 07.09.12 15:53, Ramyasri Dodla wrote:
> I am brand new to python. checking over basic stuff. I came across the 
> problem while doing so. If any body aware of the problem, kindly respond me.
> 
>  >>> 5/10
> 0
>  >>> - 5/10
> -1
> 
> The second case also should yield a 'zero' but it is giving a -1

http://python-history.blogspot.com/2010/08/why-pythons-integer-division-floors.html


-- 
http://mail.python.org/mailman/listinfo/python-list


Using Raw Data in NLTK

2012-09-07 Thread subhabangalore
Dear Group,
I am trying to use NLTK and its statistical classifiers. The system is working 
fine but I am trying to use my own data, instead of things like,

from nltk.corpus import brown
from nltk.corpus import names

If any one can kindly guide me up.

Thanks in Advance,
Regards,
Subhabrata. 

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ctypes - python2.7.3 vs python3.2.3

2012-09-07 Thread John Gordon
In <9a74$503e88dd$546bb230$30...@cache80.multikabel.net> Jan Kuiken 
 writes:

> >> uint32_t myfunction (char ** _mydata)
> >> {
> >> char mydata[16];
> >
> >> strcpy(mydata, "Hello Dude!");
> >
> >> *_mydata = mydata;
> >
> >> return 0;
> >> }
> >
> > mydata is an auto variable, which goes out of scope when myfunction()
> > exits.  *_mydata ends up pointing to garbage.

> I'm not completely sure, but i think this can be solved by using:

>  static char mydata[16];

That will solve the immediate problem, however it makes myfunction()
non-reentrant.

> (Btw.: I don't know why you use char ** _mydata, i would use
> char * _mydata, but then again, i'm not very familiar with
> ctypes)

He uses char **_mydata because he wants myfunction()'s caller to see the
new value of _mydata, which it wouldn't if it were just char *_mydata.

-- 
John Gordon   A is for Amy, who fell down the stairs
gor...@panix.com  B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing strings from the back?

2012-09-07 Thread Oscar Benjamin
On 2012-09-07, Steven D'Aprano  wrote:
> 
>
> After further thought, and giving consideration to the arguments given by 
> people here, I'm now satisfied to say that for equal-length strings, 
> string equality is best described as O(N).
>
> 1) If the strings are equal, a == b will always compare all N 
>characters in each string.
>
> 2) If the strings are unequal, a == b will *at worst* compare
>all N characters.
>
> 3) Following usual practice in this field, worst case is the
>one which conventionally is meant when discussing Big Oh
>behaviour. See, for example, "Introduction To Algorithms" 
>by Cormen, Leiserson and Rivest.

Would you say, then, that dict insertion is O(N)?

>
> Also of some interest is the best case: O(1) for unequal strings (they 
> differ at the first character) and O(N) for equal strings.
>
> Also of interest is the case that has caused the majority of the 
> discussion, the average case. I am now satisfied that the average number 
> of comparisons for unequal strings is O(1). To be precise, it is bounded 
> below by 1 comparison (you always have to compare at least one pair of 
> characters) and bounded above by 2 comparisons.

I find this idea of separating into the comparison of equal strings versus the
comparison of unequal strings rather odd. If the strings you compare come from
a distribution where they are guaranteed to be equal (or unequal) then you can
just use the O(0) comparison method.

Since string comparison is only useful if the strings can be equal or unequal,
the average case depends on how often they are equal/unequal as well as the
average complexity of both. For random strings the frequency of equal strings
decreases very fast as N increases so that the comparison of random strings is
O(1).

>
> (I'm talking about the average here -- the actual number of comparisons 
> can range all the way up to N, but the average is <= 2.)
>
> If I've done the maths right, the exact value for the average is:
>
> ((M-1)*sum( (N-i)*M**i for i in range(0, N) ) + N)/(M**N)

I'm not sure where the extra N comes from ^ but otherwise good.

I would have written that as:

(1 - p) * sum(i * p**(i-1) for i in range(1, N+1))

where p is the probability of a match (1/M for M equally likely characters) or
in closed form:

 ⎛ N ⎞
 ⎝1 - p ⋅(1 + N ⋅(1 - p))⎠
 ─
   1 - p

>
> for random strings of length N taken from an alphabet of size M.
>
> For M = 2, that average approaches but never exceeds 2 as N increases; 
> for M = 3, the average approaches 1.5, for M = 4 it approaches 1.333... 
> and so forth.

It approaches 1 / (1 - p) or, if you prefer: M / (M - 1)

Oscar

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing strings from the back?

2012-09-07 Thread Oscar Benjamin
On 2012-09-07, Oscar Benjamin  wrote:
> On 2012-09-07, Steven D'Aprano  wrote:
>> 
>
> Since string comparison is only useful if the strings can be equal or unequal,
> the average case depends on how often they are equal/unequal as well as the
> average complexity of both. For random strings the frequency of equal strings
> decreases very fast as N increases so that the comparison of random strings is
> O(1).
>
>>
>> (I'm talking about the average here -- the actual number of comparisons 
>> can range all the way up to N, but the average is <= 2.)
>>
>> If I've done the maths right, the exact value for the average is:
>>
>> ((M-1)*sum( (N-i)*M**i for i in range(0, N) ) + N)/(M**N)
>
> I'm not sure where the extra N comes from ^ but otherwise good.

Ok, I see it's for the case where they're equal.

Oscar

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamically scheduling Cron Jobs for Python Scripts.

2012-09-07 Thread Michael Ströder
Miki Tebeka wrote:
>> I want to re run the script at that schedule time to send me a email.
>
> Calculate how much time until the meeting. And spawn the script that will
> sleep that amount of time and then send email.

And if the process gets interrupted in the meantime (e.g. because of reboot)?

Ciao, Michael.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using Raw Data in NLTK

2012-09-07 Thread Terry Reedy

On 9/7/2012 3:02 PM, subhabangal...@gmail.com wrote:

Dear Group,
I am trying to use NLTK and its statistical classifiers. The system is working 
fine but I am trying to use my own data, instead of things like,

from nltk.corpus import brown
from nltk.corpus import names

If any one can kindly guide me up.


from mypack import mydata

The important thing is that mydata have the proper format.
I would think that the nltk docs have instructions for and examples of 
using personal data


--
Terry Jan Reedy

--
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing strings from the back?

2012-09-07 Thread Dwight Hutto
With unequal strings/lists to match, it would seem that one would regex
through the larger string/list with the shorter string, and piece by piece
begin to match for partial percentage matches in relation to the longer
iterative item.

-- 
Best Regards,
David Hutto
*CEO:* *http://www.hitwebdevelopment.com*
-- 
http://mail.python.org/mailman/listinfo/python-list


how to run python2.6 module with absolute imports stand alone

2012-09-07 Thread Gelonida N

Hi,

many of my modules contain following section at the end


def main():
do_something()
if __name__ == '__main__':
main()

This allows me to run some basic example code
or some small test in a stand alone mode.


My new modules contain following line at the beginning:

from __future__ import absolute_import


I like this:
- It can reduce import name conflicts
- and second it allows 'relative' imports like
   from .othermodule import funcname
   from ..mod_one_level_higher import fdfsd


However If I try to run such a script from the command line it will now 
complain with


ValueError: Attempted relative import in non-package

Any tricks to work around this ???

The only idea, that I have is to have a script, that would take my 
modulename or path name as parameter, and try to import it and then call 
the main function of the imported module.



Not very elegant, but probably functional.

Thanks in advance for any other suggestions / ideas.

--
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing strings from the back?

2012-09-07 Thread Dwight Hutto
On Fri, Sep 7, 2012 at 5:59 PM, Dwight Hutto  wrote:

> With unequal strings/lists to match, it would seem that one would regex
> through the larger string/list with the shorter string, and piece by piece
> begin to match for partial percentage matches in relation to the longer
> iterative item.
>

While iterating through the larger list character/item, one at a time, or
arranging them in certain instances.

>
> --
> Best Regards,
> David Hutto
> *CEO:* *http://www.hitwebdevelopment.com*
>
>


-- 
Best Regards,
David Hutto
*CEO:* *http://www.hitwebdevelopment.com*
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to run python2.6 module with absolute imports stand alone

2012-09-07 Thread Mark Lawrence

On 07/09/2012 23:04, Gelonida N wrote:

Hi,

many of my modules contain following section at the end


def main():
 do_something()
if __name__ == '__main__':
 main()

This allows me to run some basic example code
or some small test in a stand alone mode.


My new modules contain following line at the beginning:

from __future__ import absolute_import


I like this:
- It can reduce import name conflicts
- and second it allows 'relative' imports like
from .othermodule import funcname
from ..mod_one_level_higher import fdfsd


However If I try to run such a script from the command line it will now
complain with

ValueError: Attempted relative import in non-package

Any tricks to work around this ???

The only idea, that I have is to have a script, that would take my
modulename or path name as parameter, and try to import it and then call
the main function of the imported module.


Not very elegant, but probably functional.

Thanks in advance for any other suggestions / ideas.



I hope this helps 
http://stackoverflow.com/questions/3616952/how-to-properly-use-relative-or-absolute-imports-in-python-modules


--
Cheers.

Mark Lawrence.

--
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing strings from the back?

2012-09-07 Thread Steven D'Aprano
On Fri, 07 Sep 2012 19:10:16 +, Oscar Benjamin wrote:

> On 2012-09-07, Steven D'Aprano 
> wrote:
>> 
>>
>> After further thought, and giving consideration to the arguments given
>> by people here, I'm now satisfied to say that for equal-length strings,
>> string equality is best described as O(N).
>>
>> 1) If the strings are equal, a == b will always compare all N
>>characters in each string.
>>
>> 2) If the strings are unequal, a == b will *at worst* compare
>>all N characters.
>>
>> 3) Following usual practice in this field, worst case is the
>>one which conventionally is meant when discussing Big Oh behaviour.
>>See, for example, "Introduction To Algorithms" by Cormen, Leiserson
>>and Rivest.
> 
> Would you say, then, that dict insertion is O(N)?

Pedantically, yes. 

But since we're allowed to state (or even imply *wink*) whatever 
assumptions we like, we're allowed to assume "in the absence of 
significant numbers of hash collisions" and come up with amortized O(1) 
for dict insertions and lookups.

(Provided, of course, that your computer has an infinite amount of 
unfragmented memory and the OS never starts paging your dict to disk. 
Another unstated assumption that gets glossed over when we talk about 
complexity analysis -- on real world computers, for big enough N, 
*everything* is O(2**N) or worse.)

Big Oh analysis, despite the formal mathematics used, is not an exact 
science. Essentially, it is a way of bringing some vague order to hand-
wavy estimates of complexity, and the apparent mathematical rigour is 
built on some awfully shaky foundations. But despite that, it actually is 
useful.

Coming back to strings... given that in any real-world application, you 
are likely to have some string comparisons on equal strings and some on 
unequal strings, and more importantly you don't know which are which 
ahead of time, which attitude is less likely to give you a nasty surprise 
when you run your code?

"I have many millions of 100K strings to compare against other 100K 
strings, and string comparisons are O(1) so that will be fast."

"I have many millions of 100K strings to compare against other 100K 
strings, and string comparisons are O(N) so that will be slow, better 
find another algorithm."


Remember too that "for small enough N, everything is O(1)". Getting hung 
up on Big Oh is just as much a mistake as ignoring it completely.


> I find this idea of separating into the comparison of equal strings
> versus the comparison of unequal strings rather odd. If the strings you
> compare come from a distribution where they are guaranteed to be equal
> (or unequal) then you can just use the O(0) comparison method.

If you know that they're (un)equal, you don't need to call == at all.

If you know that "most" strings will be unequal, then you might be 
justified in treating comparisons as O(1) "most of the time" and not 
stress about the occasional slow call. But of course most of the time you 
don't know this, which is why it is appropriate to treat string 
comparisons as O(N) rather than O(1), since that's the upper bound.


> Since string comparison is only useful if the strings can be equal or
> unequal, the average case depends on how often they are equal/unequal as
> well as the average complexity of both. For random strings the frequency
> of equal strings decreases very fast as N increases so that the
> comparison of random strings is O(1).

But that is not an upper bound, and Big Oh analysis is strictly defined 
in terms of upper bounds.



>> (I'm talking about the average here -- the actual number of comparisons
>> can range all the way up to N, but the average is <= 2.)
>>
>> If I've done the maths right, the exact value for the average is:
>>
>> ((M-1)*sum( (N-i)*M**i for i in range(0, N) ) + N)/(M**N)
> 
> I'm not sure where the extra N comes from ^ but otherwise good.

The extra N comes from the case where you compare string S with itself, 
which takes exactly N comparisons.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing strings from the back?

2012-09-07 Thread Dwight Hutto
Why don' you just time it,eit lops through incrementing thmax input/

-- 
Best Regards,
David Hutto
*CEO:* *http://www.hitwebdevelopment.com*
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python newbie here! No module named settings

2012-09-07 Thread Jason Friedman
>> I was trying to use Python wrapper for Google Charts API and was
>> tweaking the examples.
>> https://github.com/gak/pygooglechart/raw/master/examples/pie.py
>>
>> This is the script which I was trying.
>>
>> And the python interpreter gives the following error:
>> import settings
>> ImportError: No module named settings
>>
>> I installed Django as well before this (if its causing the problem,
>> dunno)

I searched Google for "django import settings" and found a few links
that might be helpful.
-- 
http://mail.python.org/mailman/listinfo/python-list