Re: [Tutor] namespaces

2010-05-30 Thread Evert Rol
  Hi Robert

> This code generates the message “UnboundLocalError: local variable 'doubles' 
> referenced before assignment” (line: if d[0] == d[1] and doubles == 2:)
>  
> http://pastebin.com/mYBaCfj1  
>  
> I think I have a fair picture of what it means but I would be very happy if 
> someone could explain the difference between the two variables h and doubles 
> in the code. Why is one accessible from the function but not the other? I 
> looked into rules for namespaces but I’m still confused. Below is another 
> sample of the code

You assign a value to doubles in the roll() function, making Python think 
doubles is a local variable (which hasn't been assigned anything when you first 
use it, throwing the exception).
If you assign some value to h after the first line in roll() (eg, h = 6), you'd 
get the same exception, but then for h.
So, if you assign a value to a variable inside a function() and you want that 
variable to be the global one (instead of the implicitly assumed local one), 
you'll have to explicitly tell Python that: "global doubles" (probably on the 
first line in the function).
Since you hadn't assigned any value to h inside roll(), only used it, Python 
assumes it's the global one.

See also the second answer to this question: 
http://stackoverflow.com/questions/423379/global-variables-in-python

Hope that helps,

  Evert


>  
> Cheers, Robert
>  
> from random import *
>  
> h = 6
> doubles = 0 # current number of consecutive doubles
>  
> def roll():
> d = [randint(1, h), randint(1, h)]
> if d[0] == d[1] and doubles == 2:
> doubles = 0
> return 0
> elif d[0] == d[1] and doubles < 2:
> doubles += 1
> return sum(d)
> else:
> return sum(d)
>  
> for n in range(10):
> d = roll()
> print d   
>  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] matmolplot

2010-06-01 Thread Evert Rol
Sorry, forgot to reply-to-all previously.


> Hi,
> 
> I am trying to make plot using following code:
> ---



> for i in range(len(l2)):
> plt.axvline(x=l1[i], ymin=0, ymax=l2[i], linewidth=2, color='r')

axvline uses the [0, 1] range for it coordinates, not the coordinates set by 
the y-axis (which are set by the data): 
http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.axvline 
(which states "With the default values of ymin = 0 and ymax = 1, this line will 
always span the vertical extent of the axes, regardless of the ylim 
settings...")

You don't readily notice it, since your data lies in roughly the same [0, 1] 
interval. If your data were in the [0, 10] interval, you would have immediately 
spotted it.

Why don't you use eg:
plt.bar(left=l1, height=l2)

(which also removes the extra for loop)


  Evert



> plt.axis([350, 650, 0.0, max(l2)])
> plt.grid(True)
> savefig(f2[0]+"-"+"uv.png",dpi=(600/8))
> plt.show()
> 
> 
> My problem is the output plot I am getting is not showing correct values in 
> the plot as are in the input file (MS.txt - attached). It looks like it is 
> scaled to lower value.


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


Re: [Tutor] re.sub() query

2010-06-20 Thread Evert Rol
> Is it possible to solve the below, w/o making a re object?
> 
 a
> 'Mary Had a Little Lamb'
 p=re.compile('l',re.I)
 re.sub(p,'-',a)
> 'Mary Had a -itt-e -amb'
> 
> I cannot figure how to se re.I w/o involving  p.

Would this work?
>>> re.sub('(?i)l', '-', a)

See http://docs.python.org/library/re.html#regular-expression-syntax , search 
for iLmsux, which provide flags inside the regex.

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


Re: [Tutor] Getting an object's attributes

2010-06-26 Thread Evert Rol
> I have an object to which I dynamically add attributes. My question is how I 
> can inspect and display them at run-time?
> 
> Class a():
>pass
> 
> Obj1 = a()
> 
> Obj1.name = "Bob"
> Obj1.age = 45

First off, a few suggestions:
- you probably mean 'class', not 'Class' (sorry, but it's just that correct 
actual code helps: copy-paste from the Python prompt when you can. If you have 
a text-editor in your mail program that capitalises things, be careful when 
pasting code).
- use capitalisation (or CamelCase) for class names, lowercase for instances: 
class A, obj1 = A(). This is the usual Python convention.
- I would use new-style classes, ie, inherit from object:
>>> class A(object):
...   pass
... 
>>> obj1 = A()



> dir(a) returns a tuple which contains name and age, but also other things 
> (includings methods, etc.) I could filter this tuple (checking for 
> callable(), etc.)  but I just wondered if there was an existing way of 
> getting just name and age.

Normally, you know which attributes you want to access, so you wouldn't have 
this problem. Better yet, you wrap things in a try-except clause and see if 
that works:
>>> try:
... obj1.name
... except AttributeError:
... print "not there"
... 
not there

 
But for this case, when using new-style classes, obj1.__dict__ can help you (or 
obj1.__dict__.keys() ). 
>>> obj1.name = "Bob"
>>> obj1.age = 45
>>> obj1.__dict__
{'age': 45, 'name': 'Bob'}

Or, perhaps somewhat silly: set(dir(obj1)) - set(dir(A)).
>>> set(dir(obj1)) - set(dir(A))
set(['age', 'name'])

but I wouldn't recommend that.

See eg http://docs.python.org/library/stdtypes.html#special-attributes


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


Re: [Tutor] Problems installing

2010-06-30 Thread Evert Rol
> I just downloaded Python 2.6.5 onto my windows vista laptop. I am attempting 
> to install "escript version 3: Solution of Partial Differential Equations 
> (PDE) using Finite Elements (FEM)." I downloaded the files and manually 
> placed them in their appropriately place on my computer according to the 
> ReadMe file. However, when I try to import escript, I get an error:
> 
> I know nothing about escript, but according to the install doc on 
> https://launchpad.net/escript-finley/, it requires python 2.5.4.  The 
> distribution appears to consist entirely of .pyc files, so I think you need 
> to install the version of python that it requires.

There is a source distribution that has the *.py files, but looking at the 
dependencies, that's not going to be easy to install.
Then again, the webpage claims the third party software includes Python. So 
your system picks up Python 2.6 (which is the default), but escript does 
actually include Python, presumably 2.5. So somehow, you'll need to setup your 
system that it picks up the correct Python. Or rather, find that Python in the 
escript installation (I have no idea how it's installed, so can't tell you 
where to look), and use that Python instead when import escript.

What files did you download? Since you said you manually installed them in the 
correct places; that could/should have included Python.

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


Re: [Tutor] puzzled by Python 3's print()

2010-07-01 Thread Evert Rol
 x = 2034
 x/2
> 1017.0
 print(x/2)
> 1e+15
> 
> I was expecting, in fact needing, 117 or 117.0
> 
> 1e+15 is unsatisfactory. Am I forced to use the decimal module?

Can't you use string formatting? Eg:
>>> print("{0:15.0f}".format(x/2))
1017


print uses __str__()/str(), which I assume was deemed unsatisfactory in Python 
2: it's supposed to show a 'simple, nice' representation of anything, while 
__repr__() (or the repr() function) shows a more exact representation (or 
rather, repr() shows an object that can be used to recreate a new identical 
object: float(repr(x/2)) gives back the correct float, while float(str(x/2)) 
wouldn't). 
So they've apparently changed __str__() to make things somewhat more readable. 
__repr__()/repr() is what you get with just using x/2 on the command line:

>>> x/2
1017.0
>>> repr(x/2)
1017.0


And you could actually use:

>>> print(repr(x/2))
1017.0


I would go for the format statement, though. But that may depend on your 
precise needs.

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


Re: [Tutor] Problems with subtraction!

2010-07-07 Thread Evert Rol
> The second number should be negative ( I WANT it to be negative). For example:
> 
> print  (0 - t[4])*(t[3] - t[5]) , (0 - t[5])*(t[2] - t[4])   gives : 
> 
> -30895 -935636
> 
> And in the python shell: 
> 
> >>> -30895 -935636
> -966531

No, because you have to *subtract* the second answer from the first ( according 
to your print statement: print  (0 - t[4])*(t[3] - t[5])  -  (0 - t[5])*(t[2] - 
t[4]) ). So:
>>> -30895 - -935636
904741


If you want it to be negative, check the order of your coordinates: maybe you 
need to interchange two variables between one set of parentheses. Or maybe you 
need to subtract absolute values instead (sorry, too lazy to do the math to 
find out what is correct).

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


Re: [Tutor] "expected an indented block" (see attached)

2010-07-22 Thread Evert Rol
> Attached is a file. When I run the program it is part of, I get an
> error that says:
> line 62: IndentationError: expected an indented block.

This function:

 def fromString(self, str):
  #creates a Craft object from the string
#end class Craft


Is completely empty (the comment lines are discarded). So Python expects any 
next piece of code to be inside this method (and thus indented).
If you want an empty function, use 'pass' instead.

(also consider using four spaces for indentation, which I've also found much 
clearer. Have a read through PEP 8; has a lot of interesting tidbits. 
And an editor with a good Python mode is very handy, because that would have 
almost automatically indented the next piece of code, 'class 
Battleship(Craft)', which would have indicated something went awry before that 
line).



> I can see nothing wrong with the indentation, though. This is part of
> my Battleship game, defining all the different ships and aircraft the
> user can have, as well as the special weapons methods for each ship.
> If anyone can spot the problem, it would be great. I know I only
> indent one space, instead of the normal four, but I use a screen
> reader and it is a lot easier and faster to do it this way. If a
> version of Python based on braces instead of indents were released, my
> world would be so much better!

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


Re: [Tutor] "expected an indented block" (see attached)

2010-07-22 Thread Evert Rol
>> (also consider using four spaces for indentation, which I've also found much 
>> clearer. Have a read through PEP 8; has a lot of interesting tidbits.
> 
> Did you read the rest of his post? He's using a screen reader for a
> reason; he can't *see* the code. visual means of structuring code like
> whitespace are meaningless to him at best, and annoying at worst. No
> wonder his code is littered with '#end def' comments. Python's
> significant indentation is horrible for the blind, at least until we
> create a more specialized/better screen reader.

Sorry, I had obviously missed that. Apologies. 


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


Re: [Tutor] nested list help

2010-07-27 Thread Evert Rol
> Suppose i have this nested list:
> 
> >>> x
> [['NM100', 3, 4, 5, 6, 7], ['NM100', 10, 11, 12, 13], ['NM200', 15, 16, 17]]
> >>> for i in x:
> ...   print i
> ... 
> ['NM100', 3, 4, 5, 6, 7]
> ['NM100', 10, 11, 12, 13]
> ['NM200', 15, 16, 17]
> >>> 
> 
> how do i obtain from the above the following nested list:
> 
> >>> z
> [['NM100', 3, 4, 5, 6, 7, 10, 11, 12, 13], ['NM200', 15, 16, 17]]

You're not saying exactly how you go from one list to the other (ie, what 
criterion you use to combine the inner lists).
You could remove combine the first two lists using extend(), whereby you pass 
all but the first element of the second inner list to extend(): 
list1.extend(list2[1:]). Or simply list1+list2[1:].
If you're not concerned about the order of the elements (though I guess you 
are), you could do things like list(set(list1+list2)).
On the other hand, if you want to combine lists based on their first element, 
consider using dictionaries and extend lists which have the same key. Depending 
on how you create the lists (eg, when reading columns from a file), you can 
actually do this during creationi.
Otherwise, a (double) for-loop and an if-statement would probably work and be 
relatively straightforward, but I guess that would be rather un-Pythonesque.


> >>> for i in z:
> ...   print i
> ... 
> ['NM100', 3, 4, 5, 6, 7, 10, 11, 12, 13]
> ['NM200', 15, 16, 17]
> >>> 


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


Re: [Tutor] subprocess output

2010-07-28 Thread Evert Rol
> #!/usr/bin/env python
> import subprocess
> import sys
> 
> dom = sys.argv[1]
> switch = sys.argv [2]
> answer = subprocess.call("whois " + dom, shell=True)
> 
> Execute the above (whatever.py -example.com -a1) prints the entire WHOIS
> output, but I just want it saved to the variable 'answer', nothing more.

create a subprocess.Popen object instead, and use communicate().
Use subprocess.PIPE for the stdout and stderr arguments (and use a list for the 
executable + arguments: ["whois", dom], leaving out the shell argument).
Read the library docs: see example 17.1.3.2.


> Changing 'shell=True' to 'shell=False' raises an exception and removing
> the 'shell=' altogether is troublesome as well.

shell=False is the default

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


Re: [Tutor] Order Of Operations Question

2010-07-28 Thread Evert Rol
Sorry, forgot to reply-to-all:


I don't know the book nor the exercise, but see my comments interspersed in the 
code, and a few general remarks at the bottom

> From a practice exercise in Building Skills In Python page 64 I'm
> working on How Much Does The Atmosphere Weigh? Part 1:
> To check it states that the answer should be app. 10**18kg However,
> and I've checked to make sure that the math I've layed out matches up
> with the texts, I get 5.07360705863e+20
> 
> In the code I have broken the order of operations down to more
> parenthetical, and tried outright, but see nothing obvious about how
> it's strung together. If anyone has had a similar experience with the
> problem given, or see anything blatantly obvious I've done wrong with
> the ordering of operations. I tried to include as much of the
> problem(formulas are just above variables they're used in) as comments
> as possible.
> 
> import math
> def atmosphereWeight():
>   pi = math.pi
>   """Air Pressure (at sea level) P0. This is the long-term average.
>   P0 = 1.01325 × 10**5"""
>   airPressCLevl = 1.01325*(10**5)
>   gravity = 9.82
>   """We can use g to get the kg of mass from the force of air
> pressure P0. Apply the acceleration of gravity
>   (in m/sec2) to the air pressure (in kg · m/sec2). This result is
> mass of the atmosphere in kilograms per
>   square meter (kg/m2).
>   Mm2 = P0 × g"""
>   masAtmoInKgPerSqM = airPressCLevl * gravity

Simply from looking at the units left and right of the equality sign, you'll 
need to *divide* by g, not multiply: [kg] = [kg m / s^2] / [m / s^2]


>   """Given the mass of air per square meter, we need to know how
> many square meters of surface to apply
>   this mass to. Radius of Earth R in meters, m. This is an average
> radius; our planet isn’t a perfect sphere.
>   R = 6.37 × 10"""
>   avgRadiusEarth = 6.37 * (10**6)
>   """The area of a Sphere.
>   A = 4πr2"""
>   areaSphere = 4 * pi * (avgRadiusEarth**2)
>   """Mass of atmosphere (in Kg) is the weight per square meter,
> times the number of square meters
>   Ma = P0 × g × A"""
>   masEarthAtmoInKgPerSqM = airPressCLevl * gravity * areaSphere

ditto here: divide by gravity, not multiply by it.


>   print(masEarthAtmoInKgPerSqM)
> 
> atmosphereWeight()


Few general remarks:
- the standard way of writing numbers with a power of ten in code is something 
like 1.01325e5. I guess this is also easier/quicker to execute (not that this 
code is time-critical, but in general)
- why do you assign masTmoInKgPerSqM, then later not use it when calculating 
masEarthAtmoInKgPerSqM?
- just use math.pi when calculating areaSphere, instead of "pi = math.pi" and 
then later using pi. For me, that's just as clear.
- no need to put parentheses around powers; they are evaluated before the 
multiplication (unless this is what you meant by "to more parenthetical"
- try indenting the comments as well; more readable

Probably not all of the above are necessary, if you wrote this for debugging 
your problem, but they're just some thoughts that occurred to me.

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


Re: [Tutor] A Django Beginner View Question

2010-07-29 Thread Evert Rol
Consider using the django-users Google group for typical Django questions 
(unless you figure they're really about Python). Will likely get you better or 
more answers.
Anyway:

> Hi
> 
> I am building my first Django site which has a lot of effectively 'static' 
> pages where I just want to make the meta data and text editable.

Sounds like you actually want a generic view. Search for the link on the front 
page of the Django docs. Generic views point your straight from urls.py to the 
template, bypassing the views.py.
For the second part, you can use the keyword "editable" and set it to False in 
de model below, for fields you don't want to be edited in the admin (but you'll 
then have to figure out yourself how to enter the other fields).


> The model is
> 
> models.py
> 
> class About(models.Model):
>page_title = models.CharField(max_length=900, help_text='Text at top of 
> browser window')
>meta_keywords = models.CharField(max_length=900, help_text='Keywords (for 
> SEO)')
>meta_description = models.CharField(max_length=160, help_text='Description 
> (for SEO)')
>logo_header = models.CharField(max_length=900, help_text='H1 Header (for 
> SEO)')
>header = models.CharField(max_length=60)
>body = models.TextField()
>last_updated = models.DateTimeField(default=datetime.datetime.now, 
> primary_key=True)
> 
>class Meta:
>get_latest_by = "last_updated"
>verbose_name_plural = "About Page"
> #managed = False
> 
> def __unicode__(self):
>return self.title
> 
> 
> I'm trying to understand how to either write a model that only allows a 
> single entry or write a view that will take either a single entry or the most 
> recent entry.

Not clear what you want to do: "a model that allows a single entry"? Is that a 
model which has one, and only one, entry in the database? That doesn't really 
make much sense. Better do that through your view, as below (again, consider a 
generic view).


> views.py
> 
> def about(request):
>   return render_to_response('about.html',
>   { 'About' : 
> About.objects.latest() })
> urls.py
> 
>(r'^about/$', 'harkproject.cms.views.about'),
> 
> Much appreciated
> Al Macmillan

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


Re: [Tutor] Simple Python Program

2010-07-31 Thread Evert Rol
> Can anyone tell me how to fix the errors I am getting if possible? I'm quite 
> new and so confused...

You're not telling us what the errors are. If you'd like us help to debug your 
program, best is to provide information about how you run it, and what output 
you're getting. Not just the program (sure, we can all copy-paste the program 
and run it, but we're not all going to do that). Just copy-paste the error 
message along with the rest of the email a next time.
Python is pretty verbose and clear with its error messages; once you learn to 
read the traceback (bottom-up), you can often figure out what's wrong: read the 
exact error message and line number, and try to understand why you get that 
message.

That said, I can see one glaring error when skimming through your code (unless 
I'm horribly misreading things):
 
>  import random
> def main():
> print
> 
> playerOne, playerTwo = inputNames(playerOne, PlayerTwo)
>  
> while endProgram == 'no':

You use endProgram to compare with 'no' here, but
> 
> endProgram == no

you only set the variable here.

This is programming 101 (not even Python specific): declare (& set) your 
variables before you use them (in comparisons, function calls, etc).

Also:
> playerOne = 'NO NAME'
> playerTwo = 'NO NAME'

are set here to 'NO NAME' (some default value), but *before* that, you assign 
real names. Since the default assignment is after the proper assignment, you 
end up with 'NO NAME' for both players (except that your program currently 
crashes at the while statement).

Finally:
> 
> also how do I display the winner under the displayInfo function?
 
If you want to do that, you'll have to feed the displayInfo() function the name 
of the winner as an argument.
What you do below in the second line, is assign the displayInfo function to 
winnerName. Instead, you'll have to call that function, with the winnerName as 
as argument (you're doing this correctly before, so it's somewhat odd you're 
doing it wrong here).

> winnerName = rollDice(p1number, p2number, playerOne, playerTwo, 
> winnerName)
> winnerName = displayInfo

All in all, I can see why you're "so confused". Do you understand what you're 
doing; specifically, do you understand the flow of the program? Or did you just 
copy-paste something and made a few edits, then gave it a try? 
Perhaps you should take a step back, start even a bit smaller (single function 
programs), read a few other tutorials, then come back to this program.
You're most welcome to ask questions here, but looking through your code, 
there's a few generic programming mistakes here that you should learn about 
first.

Good luck,

  Evert


> endProgram = raw_input('Do you want to end program? (Enter yes or 
> no): ')
> 
> def inputNames(playerOne, PlayerTwo):
> 
> p1name = raw_input("Enter your name.")
> p2name = raw_input("Enter your name.")
> return playerOne, playerTwo
> 
> def random(winnerName):
> 
> p1number = random.randint(1, 6)
> p2number = random.randint(1, 6)
> 
> if p1number > p2number:
> playerOne = winnerName
> elif p1number < p2number:
> playerTwo = winnerName
> else p1number == p2number:
> playerOne, playerTwo = winnerName
> 
> def displayInfo():
> 
> #how do I display winner?
> 
> main()
> 

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


Re: [Tutor] Help with Import Error problems

2010-08-01 Thread Evert Rol
> Hi. Good day. 
> 
> I am having an import error problem. Last week, I was following this site: 
> http://sites.google.com/site/spatialpython/processing-aster-with-python-numpy-and-gdal.
>  I was able to make the python script run on the terminal. But this week, it 
> was throwing some error. 
> 
> This was the traceback:
> 
> Traceback (most recent call last):
>   File "aster_convert.py", line 2, in 
> from osgeo import gdal
>   File "/usr/lib/python2.6/dist-packages/osgeo/__init__.py", line 21, in 
> 
> _gdal = swig_import_helper()
>   File "/usr/lib/python2.6/dist-packages/osgeo/__init__.py", line 17, in 
> swig_import_helper
> _mod = imp.load_module('_gdal', fp, pathname, description)
> ImportError: /usr/lib/libspatialite.so.2: undefined symbol: GEOSSimplify
> 
> I tried google-ing for the ImportError but the results dont make sense. It 
> was working last week. I might have installed something that "broke" it but I 
> dont know how to trace it back.
> 
> Could I ask for some pointers on how to fix this? 

I have absolutely no experience with the libraries you're using, but the error 
tells you that libspatialite is expected to have the symbol GEOSSimplify (could 
be a function or a class definition, for example), which isn't found.
The first Google hit for libspatialite results in 
http://www.gaia-gis.it/spatialite/how_to_build_libspatialite.html , which 
mentions two required dependencies: PROJ.4 and GEOS. Probably the latter 
provides GEOSSimplify.
So, you've either uninstalled the GEOS library, your LD_ LIBRARY_PATH settings 
settings aren't what they were a week ago, or you've reinstalled libspatialite, 
but this time with the no-geos option.

For a quick check, try the following from the command line:
$> ldd /usr/lib/libspatialite.so.2

and see if it has any missing dependencies. If there's any missing (you can 
also post the output here if you'd like), see if you can that dependency 
somewhere on your system (the 'locate' command can help, or just good-old 
'find'). If it's missing from libspatialite but you can find that library 
somewhere on your system (that would probably be the GEOS library then), it's 
your LD_LIBRARY_PATH that's likely different.

Also, what linux distro are you using? Maybe you've been using the package 
manager overzealously, causing some essential packages to be modified or 
removed?

And how did you install libspatialite; or for that matter, osgeo?


> 
> Thank you.
> 
> Roy
> 
> P.S. I dont know if this is the right list to post this. If it isnt, I'm 
> sorry for the inconvenience. Kindly direct me to the right one.  

If libspatialite or osgeo has a mailing list, you could (also) try that one. 
While this error shows up in Python, it's more likely a generic 
installation/system settings problems. Which are often tricky to find the 
correct mailing list for, actually, as long as it's not clear what's the 
underlying cause.


Good luck, and let us know what you find.

  Evert

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


Re: [Tutor] Help with Import Error problems

2010-08-01 Thread Evert Rol
> I got it back working. But it was with some stroke of luck. And I dont know 
> the explanation.
> 
> I installed the latest source of GEOS (as suggested by someone from the gdal 
> channel). Then i tried the script. It gave me a different import error. 
> 
> ImportError: libgeos-3.3.0.so: cannot open shared object file: No such file 
> or directory
> 
> I uninstalled the thing. And then tried the script again and it worked. :| I 
> answered some of your questions below. Again, thanks.

Sounds like a library mess-up. System thing, definitely not a Python thing. 
Installing the latest source was a bit of an odd suggestion, if you got things 
working earlier.
But it's good it's working now. Just be careful that it doesn't come back to 
bite you when you install more things.

Few other things below, after the break:




> For a quick check, try the following from the command line:
> $> ldd /usr/lib/libspatialite.so.2
> 
> The command line returns the following lines:
> 
>   linux-vdso.so.1 =>  (0x7fff6edff000)
>   libsqlite3.so.0 => /usr/lib/libsqlite3.so.0 (0x7f793015c000)
>   libgeos_c.so.1 => /usr/local/lib/libgeos_c.so.1 (0x7f792ff4f000)
>   libgeos-3.2.2.so => /usr/lib/libgeos-3.2.2.so (0x7f792fbe8000)
>   libproj.so.0 => /usr/lib/libproj.so.0 (0x7f792f9a6000)
>   libm.so.6 => /lib/libm.so.6 (0x7f792f723000)
>   libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0x7f792f40e000)
>   libpthread.so.0 => /lib/libpthread.so.0 (0x7f792f1f1000)
>   libdl.so.2 => /lib/libdl.so.2 (0x7f792efed000)
>   libc.so.6 => /lib/libc.so.6 (0x7f792ec69000)
>   libgeos.so.2 => /usr/local/lib/libgeos.so.2 (0x7f792e964000)
>   libgcc_s.so.1 => /lib/libgcc_s.so.1 (0x7f792e74d000)
>   /lib64/ld-linux-x86-64.so.2 (0x7f7930688000)
>  
> I dont know what to make of it.

It's the pointers to the libgeos libraries that are interesting.
Which shows that one libgeos lives in /usr/lib, while the other one can be 
found in /usr/local/lib. And libgeos_c also lives in /usr/local/lib.
So it still feels a bit messy, having similarly named libraries in two 
different system directories, and you may run into some compatibility issues 
later on, in just a few specific functions or classes. May, because I've never 
used this software. 
You should scan through /usr/local/lib for more libgeos* libraries. If you find 
libgeos-3.2.2.so there as well, then probably that should actually be the 
preferred one (although then libspatialite.so.2 should also be in 
/usr/local/lib). Anyway, don't change it if it's working.
See also below.

> and see if it has any missing dependencies. If there's any missing (you can 
> also post the output here if you'd like), see if you can that dependency 
> somewhere on your system (the 'locate' command can help, or just good-old 
> 'find'). If it's missing from libspatialite but you can find that library 
> somewhere on your system (that would probably be the GEOS library then), it's 
> your LD_LIBRARY_PATH that's likely different.
> 
> Also, what linux distro are you using? Maybe you've been using the package 
> manager overzealously, causing some essential packages to be modified or 
> removed?
> 
> 
> I'm on Ubuntu 10.04 (64 bit). I think it was from installing different 
> GIS-related software (not all of which could be installed from the package 
> manager).

So perhaps some stuff automatically installed in /usr/lib (that could be 
software installed through the package manager), and then you used the usual 
./configure; make; make install (or python setup.py install; or whatever), 
which most likely (hopefully, actually) would install things in /usr/local/lib. 
And somewhere along the way, a library got removed or replaced by a different 
version library, and things stopped working. 
What exactly happened is hard to tell, depending on how exactly you installed 
everything, and in which order.

I hope this keeps working for you. Probably the folks on the gdal channel or 
related mailing lists could otherwise help you; but perhaps then tell them you 
have the geos & related libraries spread across /usr/lib and /usr/local/lib.

Cheers,

  Evert

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


Re: [Tutor] sys.exit help

2010-08-01 Thread Evert Rol
> I was wondering how can I change sys.exit so if you use command line to run 
> the program. it prompts a message asking if the user wants to exit instead of 
> automatically just exiting?

Just write a wrapper exit() function around sys.exit that does that.
You don't want to change the sys.exit function to behave differently; it's 
purpose is simply to exit the program with a return value.



> import random
> import sys
> my_hp = 50
> mo_hp = 50
> menu1 = """
> Menu Selections: 
> 1 - Attack
> 2 - Defend
> 3 - Help
> 4 - Exit
> """
> print menu1
> while True:
> my_dmg = random.randrange(1, 20)
> mo_dmg = random.randrange(1, 20)
> 
> choice = input ("\nEnter your selection. ")
> choice = float(choice)
> print
> if choice == 1:
> mo_hp = mo_hp - my_dmg
> if mo_hp <= 0:
> print "Iris is at 0 Hit Points!\nYOU HAVE SLAIN IRIS!"
> sys.exit(0)
> elif mo_hp > 0:
> print 
> "-"
> print "Iris is at %s Hit Points\nYou did %s damage\n" % 
> (mo_hp, my_dmg)
> my_hp = my_hp - mo_dmg
> if my_hp <= 0:
> print "Your Hit Points are 0!\nYOU HAVE BEEN SLAIN BY Iris!"
> sys.exit(0)
> elif my_hp > 0:
> print name,"was attacked by Iris for %s damage!\nMy Hit 
> Points are %s" % (mo_dmg, my_hp)
> print 
> "-"
> else:
> print menu1
> 
> 
> elif choice == 2:
> mo_hp = mo_hp - my_dmg / 2
> if mo_hp <= 0:
> print "The Lich King is at 0 Hit Points!\nYOU HAVE SLAIN 
> IRIS!"
> sys.exit(0)
> elif mo_hp > 0:
> print 
> "-"
> print "The Lich King is at %s Hit Points\nYou did %s 
> damage\n" % (mo_hp, my_dmg)
> my_hp = my_hp - mo_dmg / 2
> if my_hp <= 0:
> print "Your Hit Points are 0!\nYOU HAVE BEEN SLAIN BY IRIS!"
> sys.exit(0)
> elif my_hp > 0:
> print name,"was attacked by the Iris for %s damage!\nMy Hit 
> Points are %s" % (mo_dmg, my_hp)
> print 
> "-"
> else:
> print menu1
> 
> elif choice == 3:
> print """
> -
> Attack = Attack for 100% of damage.
> Defending = Attack for 50% of damage and endure 50% of damage.
> -
> """
> elif choice == 4:
> sys.exit(0)
> ___
> 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] Menu not working properly

2010-08-02 Thread Evert Rol
> My problem is choice 3. Exit, if you select no or put an invalid answer... It 
> will run menu1... but then it runs
> name = raw_input ("Enter your character name. ")
> print "Your character name is:", name
> 
> How can i make it so it prints menu1 like normal... then asks you to enter 
> your selection again?
> instead of running the above code.

Put it in a loop with the necessary break statements. Something like:

while True:
  print menu1
  answer = raw_input()
  if ...:
...
break
  elif ...: 
...
  elif ...:
   answer = raw_input()
   if ...:
 sys.exit()
raw_input('character name')

Only the first option will break out of the loop to the 'character name' 
question; the other two options will continue to loop, apart from the point 
where you exit() the whole program.
If you need user input until the correct input has been given, that means 
you'll have to wrap things in a loop (generally a while loop that you break out 
of when you received correct input). 
You could factor out the actual code inside the while loop into a function, 
which can make the structure clearer.


Btw, 



> characterChoice = input ("Enter your choice. ")

You have input() here, while further down raw_input(). The latter is preferred 
in Python 2.x. I assume this is just a minor mistake.


  Evert


> print
> 
> if characterChoice == 1:
> print """
> 
> *Place Holder*
>   
> """
> 
> elif characterChoice == 2:
> print "Currently under construction.\nPlease choose again."
> print menu1
> elif characterChoice == 3:
> endProgram = raw_input ("Do you want to end program? yes or no ")
> if endProgram == "yes":
> sys.exit(0)
> elif endProgram == "no":
> print menu1
> else:
> print "\nInvalid Command:\nSelect from the menu again.\n"
> print menu1
> 
> print
> name = raw_input ("Enter your character name. ")
> print "Your character name is:", name
> ___
> 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] Menu not working properly

2010-08-02 Thread Evert Rol
> Hello Evert Rol,
>   Thank you for the menu help, I have completed it with great 
> success... There is 1 more problem I am currently having, and when I fix it 
> my program will be completed. If you are interested in helping me with this 
> last stretch, I will be greatly appreciative.
> 
>   If you respond with a yes. I will go ahead and send my code over 
> and list the problem I am currently having.

Jason, it makes more sense to send this to the full tutor list, not just to me: 
there are more people who can and will help you. Unless I've missed a response 
to a previous post of yours where people disrecommended your postings, but that 
shouldn't happen to quickly.
Although in general, it's better to try and solve the problem yourself, and ask 
the tutor list if you're really stuck, either with an error or a concept. And 
the 'try and solve yourself' step can take one or more days and a lot of 
Googling, but in the end you learn a lot from it.
So, depending on your current problem, see if you want to try yourself first, 
or that you feel you need the input from the list.
(Code can be included with the mail if short; use something like 
http://python.pastebin.com/ if lengthly code.)

Good luck,

  Evert





> 
>          -Thank You
> 
> On Mon, Aug 2, 2010 at 3:35 AM, Evert Rol  wrote:
> > My problem is choice 3. Exit, if you select no or put an invalid answer... 
> > It will run menu1... but then it runs
> > name = raw_input ("Enter your character name. ")
> > print "Your character name is:", name
> >
> > How can i make it so it prints menu1 like normal... then asks you to enter 
> > your selection again?
> > instead of running the above code.
> 
> Put it in a loop with the necessary break statements. Something like:
> 
> while True:
>  print menu1
>  answer = raw_input()
>  if ...:
>...
>break
>  elif ...:
>...
>  elif ...:
>   answer = raw_input()
>   if ...:
> sys.exit()
> raw_input('character name')
> 
> Only the first option will break out of the loop to the 'character name' 
> question; the other two options will continue to loop, apart from the point 
> where you exit() the whole program.
> If you need user input until the correct input has been given, that means 
> you'll have to wrap things in a loop (generally a while loop that you break 
> out of when you received correct input).
> You could factor out the actual code inside the while loop into a function, 
> which can make the structure clearer.
> 
> 
> Btw,
> 
> 
> 
> > characterChoice = input ("Enter your choice. ")
> 
> You have input() here, while further down raw_input(). The latter is 
> preferred in Python 2.x. I assume this is just a minor mistake.
> 
> 
>  Evert
> 
> 
> > print
> >
> > if characterChoice == 1:
> > print """
> >
> > *Place Holder*
> >
> > """
> >
> > elif characterChoice == 2:
> > print "Currently under construction.\nPlease choose again."
> > print menu1
> > elif characterChoice == 3:
> > endProgram = raw_input ("Do you want to end program? yes or no ")
> > if endProgram == "yes":
> > sys.exit(0)
> > elif endProgram == "no":
> > print menu1
> > else:
> > print "\nInvalid Command:\nSelect from the menu again.\n"
> > print menu1
> >
> > print
> > name = raw_input ("Enter your character name. ")
> > print "Your character name is:", name
> > ___
> > 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] sys.exit help

2010-08-02 Thread Evert Rol
(replying to the full list; hope that was intended.)

>>> I was wondering how can I change sys.exit so if you use command line to run 
>>> the program. it prompts a message asking if the user wants to exit instead 
>>> of automatically just exiting?
>> 
>> Just write a wrapper exit() function around sys.exit that does that.
> 
> In a post 2 minutes after yours, Steven D'Aprano says, "write your own
> quit() function that
> asks the user and then calls sys.exit if they say yes."
> 
> Is that an example of what you meant by a wrapper? I've never been
> sure I understood the term, "wrapper".

Yes. A "wrapper function" would be a function that "wraps itself around" 
something else, most of the time around another function. It's often used to 
expand original functionality of a function, or to make life easier it you need 
to always set some variables before calling the original function.
In Python, you could almost call it a decorator, although in this case that 
wouldn't be a good idea. And wrapper function (as far as I'm aware) is a more 
general term.

For fun I just Googled for "wrapper function" (always useful). First hit leads 
to wikipedia: http://en.wikipedia.org/wiki/Wrapper_function (though it's a 
short wiki entry, and I'm not sure how much extra it would clarify).

  Evert

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


Re: [Tutor] global exception handling?

2010-08-02 Thread Evert Rol
> A week or two back I asked this list about how to deal with SQLite database 
> errors like 'database is locked'.  Since then I figured out one way to 
> reproduce that error (*see p.s. below if anyone is interested).  I can also 
> then catch the error with a try/except block and prevent it from causing 
> problems.
> 
> But, the issue is, I have many places where I write to the database and would 
> have to embed each of these in a try/except block.  I can do that, but 
> wondered if there is a "global" way to catch this 'database is locked' error? 
>  I found someone asking this sort of question online but it doesn't appear to 
> be answered:
> http://bytes.com/topic/python/answers/799486-how-do-i-prevent-exceptions-stopping-execution-global-exception-handler

I'm not sure why you would like to do that: your code assumes the database 
interaction works fine, and based on that just continues it's normal flow. If 
the database is locked, you'll need to do something to prevent your code 
crashing further down, which is what you put in the except OperationalError: 
block. I would assume that the error handling depends on where you are in the 
code.
If you can always perform the same type of error handling, just create a 
convenience function (possibly with the SQL statement as argument) that calls 
the database and returns the results, and put the database call inside the try: 
except: clause. Then you need to do this only once.

A global way to catch the database-locked exception is just to put the try: 
except OperationalError: around your complete code. Exceptions propagate all 
the way to the function where your program started, and if you catch it there, 
you will catch every OperationalError exception from anywhere in the code. Of 
course, your program then always exits anyway, because you can't return to the 
point where the the exception was thrown (or maybe you can, but not that I'm 
aware of. I wouldn't recommend it though).


> Thanks,
> Che
> 
> p.s. *I use the nice program SQLite Database Browser and if I edit a field in 
> the database my Python app is accessing, click "Apply changes", but I do 
> *not* save the changes (that is, I do not click the disk icon), when I go to 
> write to that database from my Python app, I get a 'database is locked' error.

Sounds like somewhat odd behaviour to me: "apply changes" for me means "apply & 
commit", ie, it includes the save operation. Might just be me.
I guess "Apply changes" opens the database connection, but then "save" performs 
the actual commit to the database, and in the meantime the database is locked.

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


Re: [Tutor] access class through indexing?

2010-08-04 Thread Evert Rol
> Hi all,
> Further to my questions about overriding builtin methods earlier, how
> would I make a class able to be accessed and changed using index
> notation? For example, take the following:
> deck=CardPile(52) #creates a new deck of cards
> print(len(deck)) #prints 52, thanks to my __len__ function
> for c in deck: print c #also works thanks to __iter__
> print(deck[4]) #fails with a list index out of range error
> How would I get the last one working? I tried __getattr__(self, i),
> but it did not work. I want to be able to get an arbitrary item from
> the "pile" of cards (which can be a deck, a hand, whatever), and/or
> set an element. A "pile" is just a list of Card objects, so I would
> only need to use sequence indexing, not mapping functions.

If you want most or all of the things that lists implement, and you feel in 
general that CardPile is really an advanced/augmented list, just let CardPile 
inherit from list: class CardPile(list).
I would think that should work for what you want.

  Evert


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


Re: [Tutor] access class through indexing?

2010-08-04 Thread Evert Rol
>>> Further to my questions about overriding builtin methods earlier, how
>>> would I make a class able to be accessed and changed using index
>>> notation? For example, take the following:
>>> deck=CardPile(52) #creates a new deck of cards
>>> print(len(deck)) #prints 52, thanks to my __len__ function
>>> for c in deck: print c #also works thanks to __iter__
>>> print(deck[4]) #fails with a list index out of range error
>>> How would I get the last one working? I tried __getattr__(self, i),
>>> but it did not work. I want to be able to get an arbitrary item from
>>> the "pile" of cards (which can be a deck, a hand, whatever), and/or
>>> set an element. A "pile" is just a list of Card objects, so I would
>>> only need to use sequence indexing, not mapping functions.
>>> 
>> 
>> Implement __getitem__(self, key) (See
>> http://docs.python.org/reference/datamodel.html#emulating-container-types )
>> 
>> If you want to support slicing (access like deck[0:10]), you'll need to
>> handle getting a slice object as the key in addition to accepting an integer
>> key.
>> 
>> If a pile is really "just" a list of cards, you may want to look into
>> inheriting from list instead of re-implementing all of the functionality on
>> your own.
> I tried this first, by typing
> class Pile(list):
> Doing this does not seem to work, though, since creating a pile of
> size 52 results in a list of size 0, unless I include the __len__
> function. I thought putting (list) in my class definition would
> automatically give me the functions of a list as well as anything I
> wanted to implement, but that does not seem to be the case.

That depends how you create the Pile of 52 cards: list(52) also doesn't 
generate 52 (random) items.
If you override __init__ to accept an integer that generates the cards for you, 
this should work.
Something like:

class Pile(list):
def __init__(self, *args, **kwargs):
if len(args) == 1 and isinstance(args[0], (int, long)):
args = ([Card(i) for i in xrange(args[0])],)
super(Pile, self).__init__(*args, **kwargs)

allows things like Pile(52), Pile([card1, card2, card3]), Pile(12)[0:3] etc.

Cheers,

  Evert

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


Re: [Tutor] access class through indexing?

2010-08-04 Thread Evert Rol

On 4 Aug 2010, at 23:28 , Alex Hall wrote:

> On 8/4/10, Evert Rol  wrote:
>>>>> Further to my questions about overriding builtin methods earlier, how
>>>>> would I make a class able to be accessed and changed using index
>>>>> notation? For example, take the following:
>>>>> deck=CardPile(52) #creates a new deck of cards
>>>>> print(len(deck)) #prints 52, thanks to my __len__ function
>>>>> for c in deck: print c #also works thanks to __iter__
>>>>> print(deck[4]) #fails with a list index out of range error
>>>>> How would I get the last one working? I tried __getattr__(self, i),
>>>>> but it did not work. I want to be able to get an arbitrary item from
>>>>> the "pile" of cards (which can be a deck, a hand, whatever), and/or
>>>>> set an element. A "pile" is just a list of Card objects, so I would
>>>>> only need to use sequence indexing, not mapping functions.
>>>>> 
>>>> 
>>>> Implement __getitem__(self, key) (See
>>>> http://docs.python.org/reference/datamodel.html#emulating-container-types
>>>> )
>>>> 
>>>> If you want to support slicing (access like deck[0:10]), you'll need to
>>>> handle getting a slice object as the key in addition to accepting an
>>>> integer
>>>> key.
>>>> 
>>>> If a pile is really "just" a list of cards, you may want to look into
>>>> inheriting from list instead of re-implementing all of the functionality
>>>> on
>>>> your own.
>>> I tried this first, by typing
>>> class Pile(list):
>>> Doing this does not seem to work, though, since creating a pile of
>>> size 52 results in a list of size 0, unless I include the __len__
>>> function. I thought putting (list) in my class definition would
>>> automatically give me the functions of a list as well as anything I
>>> wanted to implement, but that does not seem to be the case.
>> 
>> That depends how you create the Pile of 52 cards: list(52) also doesn't
>> generate 52 (random) items.
>> If you override __init__ to accept an integer that generates the cards for
>> you, this should work.
> Here is my init, not half as pretty as yours, but it should work.
> Maybe this will explain the problem.
> 
> def __init__(self, size, cards=None, fill=False):
>  #creates a pile of cards. If "fill"==true, it will auto-fill the
> pile starting from the Ace of Clubs up through the King of Spades,
> stopping if it exceeds the size arg.
>  #if the cards arg is not null, it will populate the pile with the
> cards in the list.
>  self=[]

You declare self to be a list here (while somewhere before the def __init__, 
you'll have class Pile(list), meaning every self will be a Pile object. While 
self is an arbitrarily chosen name, it is assigned by the interpreter when 
calling the methods (I hope I'm saying that correctly). So when __init__(self, 
...) is called, self is a Pile object, then you turn self into a list object, 
loosing its meaning. Don't reassign self (but you can do 'print self[:size]'. 
Then again, you probably don't need that inside your class.


Try using your __init__, then at the end of the __init__ method, print 
type(self). That should be something like . Now do the same with the 
init below that uses super. You should get something like .


>  if fill: #auto-fill, useful to generate a new, unshuffled deck
>   for i in range(1, 14):
>for j in range(1, 5):
> self.append(Card(i, j))
>#end for
>   #end for
>   self=self[:size] #keep only the amount specified
>  elif cards is not None: #fill the pile with the cards
>   for c in cards:
>self.append(c)
>   #end for
>  #end if
> #end def __init__
> 
> 
>> Something like:
>> 
>> class Pile(list):
>>def __init__(self, *args, **kwargs):
>>if len(args) == 1 and isinstance(args[0], (int, long)):
>>args = ([Card(i) for i in xrange(args[0])],)
>>super(Pile, self).__init__(*args, **kwargs)
> Why call super here, if it is already my own __init__?


It's just Good Practice to always call super, propagating any remaining 
arguments to the base class __init__ (hence the *args & **kwargs).
Google for "Python super" and read a few of those hits. At first, it may make 
little sense, because there's a lot that can be said about it, but after a 
while, it'll become clearer.


>> allows things like Pile(52), Pile([card1, card2, card3]), Pile(12)[0:3] etc.
> Again, my init 

Re: [Tutor] os.urandom()

2010-08-07 Thread Evert Rol
> 
> 
> using Vista, Python 3.1:
> 
 import os
 os.urandom(6)
> b'\xd1\xfc\xb0\x14\xeaL'
> 
> So what is this output? What in ascii? What in hex?  Do those
> questions even make sense?

It returns just what it says in the docs: "a string of [6] random bytes"

You can convert the bytes to characters using eg chr():
>>> [a for a in map(chr, os.urandom(6))]
['Ó', 'ó', 'P', 'Ü', 'Ó', 'C']

Not all converted bytes will be printable characters, so some may appear with 
the \x still prepended (eg, control characters).

Does that help? What actually do you wish to achieve in the first place?


> I've tried 2 things to get at it:
 import binascii
 binascii.b2a_qp(b'\xd1\xfc\xb0\x14\xeaL')
> b'=D1=FC=B0=14=EAL'
 binascii.b2a_hex(b'\xd1\xfc\xb0\x14\xeaL')
> b'd1fcb014ea4c'
> 
> Help, please.
> 
> Dick Moores
> 
> 
> 
> 
> 
 import binascii
 binascii.b2a_qp(b'\x05\x8aU\x92\xf3R')
> b'=05=8AU=92=F3R'
 binascii.b2a_hex(b'\x05\x8aU\x92\xf3R')
> b'058a5592f352'
> ___
> 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] Need help understanding output...

2010-08-11 Thread Evert Rol
> I'm learning Python and I'm currently facing an issue with a small script I'm 
> writing.
> 
> I need to generate a list of 30 numbers randomly chosen from 1, 2, 3, 4, 5 & 
> 6. However, I cannot have more than 2 numbers which are the same next to each 
> other. I came up with the following (Please ignore the fact that I'm trying 
> to avoid an IndexError in a stupid way :)):

Ok, we'll ignore that (for now ;-D).



> However, I wanted to look deeper in the above script and I created the 
> following:
> 
> import random
> iteraties = 5
> cijferreeks = 6
> aantal_cijfers = iteraties * cijferreeks
> reeks = []
> while len(reeks) <= 1:
>  nummer = random.randrange(1, cijferreeks + 1, 1)
>  print 'Nummer: ', nummer
>  print 'Reeks: ', reeks
>  reeks.append(nummer)
>  print '\n'
> 
> while len(reeks) <= aantal_cijfers:
>  nummer = random.randrange(1, cijferreeks + 1, 1)
>  print 'Nummer: ',  nummer
>  print 'Voorlaatste vd reeks (-2): ', reeks[-2]
>  print 'Laatste vd reeks (-1): ', reeks[-1]
>  print 'Reeks: ', reeks
>  if nummer != reeks[-1] and nummer != reeks[-2]:
>reeks.append(nummer)
>  else:
>print 'Nummer: ', nummer, 'is gelijk aan vorige 2 nummers: ', reeks[-1], 
> '&', reeks[-2], '!'
>  print '\n'
> print reeks
> 
> When I run that, I can see there's something wrong with my if statement, it 
> triggers the else condition even when the 2 previous numbers in my list are 
> not the same...  I'm not sure what is happening here...

For an 'and' in a condition, only one part of the condition needs to be False 
for the condition to fail and skip to the else clause.
Eg, with nummer=1, reeks[-1]=1 and reeks[-2]=2, it finds that 1 != 1 is False, 
and immediately skips to the else part. Ditto if nummer=2 and same reeks: first 
part is then True, but second part False, hence skip to else.
I leave it up to you to find the correct if statement. (Hint: it's phrased in 
your third sentence at the top.)


Btw, tip: always code in English. It just makes things easier for yourself when 
using other code examples, for example. But I just find generally good practice.

Cheers,

  Evert

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


Re: [Tutor] string conversion according to the terminal

2010-08-12 Thread Evert Rol
> Hey- suppose we have a file name-"my file number"
> if we want to execute it into the terminal it would be like - my\ file\ number
> 
> so wondering is there any one in the python that change the enter string into 
> the terminal string one-
> like if user enter the file name with path- "my file number". i want to 
> automatically convert it into "my\ file\ number"
> Plz help me out in this.

>>> a = "my file number"
>>> a.replace(' ', '\\ ')
'my\\ file\\ number'
>>> print a.replace(' ', '\\ ')
my\ file\ number

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


Re: [Tutor] string conversion according to the terminal

2010-08-12 Thread Evert Rol
> a = "my file number"
> a.replace(' ', '\\ ')
>> 'my\\ file\\ number'
> 
> What if a has more than 1 space between words? Then I think this would
> be a safer way.
> 
 print "\\ ".join("my  file  number".split())
> my\ file\ number

If those spaces are in the actual filename, you'll want to keep them, hence 
you'll need to escape those extra spaces as well.

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


Re: [Tutor] string conversion according to the terminal

2010-08-12 Thread Evert Rol
> Ok. I appreciate ur response and its gud somewhat... But we dont have only 
> space=" " . this '\' rules also applies to '(' ')' and all that stuff also... 
> so i was looking for the builtin function that fully converts it... Is there 
> any one??

This may depend on your system, but generally, putting the complete filename 
between quotes ("some filename with ()") also works well; no need for escapes 
(unless your filename contains quotes itself).
Otherwise, you put the a.replace in a simple for loop that iterates through all 
special characters that need to be replaced.
Or you could look into regular expressions: re.sub can help.

Lastly, depending on your exact needs, Python may already take care of this 
anyway. Eg:
>>> import glob
>>> files = glob.glob("special*")
>>> files
['special name']
>>> f = open(files[0])
>>> f.read()
'data\n'

So even though there's no escape for the space character in 'special name', 
Python's open is smart enough to take care of the spaces and open the file 
correctly anyway.


> > a = "my file number"
> > a.replace(' ', '\\ ')
> >> 'my\\ file\\ number'
> >
> > What if a has more than 1 space between words? Then I think this would
> > be a safer way.
> >
>  print "\\ ".join("my  file  number".split())
> > my\ file\ number
> 
> If those spaces are in the actual filename, you'll want to keep them, hence 
> you'll need to escape those extra spaces as well.

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


Re: [Tutor] is it possible to call a setter property during class instantiation?

2010-08-12 Thread Evert Rol
> Does anyone know if it's possible to call a property setter inside of a 
> class's init method?  Below is a code sample of what I'm trying to do. 

Just a quick guess:


> class Question(object);

replace the semi-colon with a colon (I assume it's just a typo, since you don't 
get an error for this).

> 
> def __init__(self, value):
> self.text(value)

self.text = value  # is the way to do this, if you're using it as a 
property.


> 
> @property
> def text(self):
> return self._text
> 
> @text.setter
> def text(self, value):
> if not isinstance(value, str):
> raise TypeError
> self._text = value
> 
> 
> Here's an explanation of what I'm trying to accomplish:
> 
> I have a class with an init method that is getting bloated with 
> error-checking guard clauses. I was hoping to "hide" some of these guard 
> clauses by using the @property decorator and its associated setter method. 
> I'd like to use the Question.text property to set the value (or raise an 
> error) upon instantiation of a Question object. I figured this would clean up 
> my init method and move the error-checking code closer to the relevant class 
> attribute. I've tried numerous variations on the above init method, but all 
> without success.
> 
> 
> In the current version, when I try:
> 
> >>> q = Question("Hello world?") 
> 
> I get the following error:
> 
> AttributeError: 'Question' object has no attribute '_text'
> 
> I was hoping text property would create self._text for me on instantiation, 
> but apparently no dice. I'm also getting errors when I do the below 
> variations:
> 
> ### variation 1 
> def __init__(self, value):
> self._text = ''
> self.text(value)
> 
> ### variation 2 
> def __init__(self, value):
> self._text = None
> self.text(value)
> 
> Can anyone point out what I'm doing wrong? I suspect I'm misunderstanding 
> properties and/or the finer points of object instantiation. Any help would be 
> greatly appreciated! 

Again, see the correction above: use 'self.text = value'. Don't use self._text, 
nor call self.text()

> 
> Thanks!
> Serdar

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


Re: [Tutor] Using Django with TortoiseSVN (overwriting files)

2010-08-16 Thread Evert Rol
> We have a project at work where myself and a co-developer are setting up 
> Django. Our version control software of choice is TortoiseSVN.
> 
> When doing a project update from SVN, it pulls the server version to the 
> local project. When checking code in, it overwrites the server version of the 
> code as expected. 
> 
> I wish to find out whether Django would work happily this way, as it requires 
> one to use the django-admin.py tool to create projects and apps. Would 
> overwriting these files/ directories with server versions compromise their 
> integrity in a Django setup?

That's not a Python question, more a Django question or a system-admin 
question. You'd be better off using the correct mailing list for that.

That said, you should be fine, providing you re-sync the databases every time 
you 'svn up', to keep your model schema's in the database in sync (you can use 
fixtures to sync data in the database). Also the settings files may differ on 
the server or the local machines; it's best to keep those out of SVN, or have a 
little if-else clause in settings.py that takes care server-dependent settings.
Otherwise, all your code can (and should) be machine/server agnostic, and thus 
easily transportable.

  Evert


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


Re: [Tutor] reading from 2 file output to 1

2010-08-17 Thread Evert Rol
> I am trying to read from 2 CSV files, where first 4 ([0,1,2,3])
> columns are read from 'file1' and 3 columns ([1,2,3]) from 'file2' and
> write them into a 3rd file 'file3', 7 columns string. The data is
> Numeric values both, +ve and -ve.
> 
> this is how i was trying.
> 
> **
> import sys,os, fileinput
> 
> 
> file11 = raw_input('Enter PR1 File name :')
> fp1 = open(file11,'r')
> 
> file12 = raw_input('Enter PR3 File Name :')
> fp2 = open(file12,'r')
> 
> 
> while 1:
>fp1 = fp1.readline()
>  for line in fp1:

This is too much: Looks like you've gathered input from example scripts, and 
combined them all in the above three lines.
Instead of explaining what's going wrong (sorry; ask again if you really want 
to know), here's what you could do instead:

while 1:
  line = fp1.readline()  # read a line and move file pointer to the next line
  line2 = ...
  

and probably wrap that in a try-except block to catch the EOF error when 
there's nothing more to read.
Better is, however,

for line in fp1:  # iterating through a file is iterating through its separate 
lines.
  line2 = ...
  

Even better, assuming you're Python >=2.6 (for Python 2.5, use the following at 
the top of your file: from __future__ import with_statement):

file11 = raw_input('Enter PR1 File name :')
with open(file11) as fp1:
  for line in fp1:
line2 = ...


The with clause, in combination with the open(file1) statement (note: mode 'r' 
is the default), will neatly close the file afterwards, even if you get an 
error in the for loop (ie, the with statement takes care of some 
try-except-finally clauses previously used).

  
As for whether there are better ways of 'doing it': there are CSV Python 
modules out there that could help you (I've never used those), and personally I 
would use a combination of *nix tools like awk & paste for just this. But 
that's not an option on a Python mailing list ;-).

Hope that helps,

  Evert


> line2 = line.split(",")
> col1 = line2[0]
> col2 = line2[1]
> col3 = line2[2]
> col4 = line2[3]
> print col1
> print col2
> FL1 = '%s,%s,%s,%s' % (col1,col2,col3,col4)
> print FL1
> 
> while 1:
>fp2 = fp2.readline()
>   for line1 in fp2:
>  line3 = line1.split(",")
>  col5 = line3[1]
>  col6 = line3[2]
>  col7 = line3[3]
> 
>  FL2 = '%s,%s,%s,' % (col5,col6,col7)
>  print FL2
> 
> file3=raw_input('Enter PR2 OUTPUT File Name :')
> fp3 = open(file3,'w')
> 
> print col1,col2,col3,col4 + ',' + col5,col6,col7
> 
> str3 = '%s,%s,%s,%s,%s,%s,%s\n' % (col1,col2,col3,col4,col5,col6,col7)
> fp3.write(str3)
> 
> **
> 
> I am getting the following error :
> 
> Traceback (most recent call last):
>  File "mer5Pr2.py", line 16, in 
>col2 = line2[1]
> IndexError: list index out of range
> 
> *
> 
> There is data in the file at 'col2'. So what am i missing / doing wrong ?
> 
> And is there better / optimized way of doing it?
> 
> Thanks
> 
> Nitin
> ___
> 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 confusing NameError

2010-08-18 Thread Evert Rol
> This is my first mail to this list so firstly thank you for reading and 
> apologies in advance for any noob mistakes i may have inadvertantly made:). 
> Ive only started learning python as my first programming language and its all 
> going well so far, working my way through a couple of books one of which is 
> programming python: for absolute beginners by Michael Dawson
>  
> In one of the code samples he supplies while doing loops ( namely if and else 
> loops) im getting a NameError i dont understand and cannot find any help 
> anywhere about it. here is the code he supplied and the error im getting
>  
> # Password
> # Demonstrates the if statement
>  
> print("Welcome to System Security Inc.")
> print("-- where security is our middle name\n")
>  
> password = input("Enter your password: ")
>  
> if password == "secret":
> print("Access Granted")
>  
> input("\n\nPress the enter key to exit.")
>  
>  
> and the traceback error im getting
>  
> Traceback (most recent call last):
>   File "G:\Programming\Python\programming python\chapter3\password.py", line 
> 7,
> in 
> password = input("Enter your password: ")
>   File "", line 1, in 
> NameError: name 'secret' is not defined


  Hi Shane,

Normally, a NameError would indicate a variable that's not defined. Here it's a 
it more tricky. You're probably using Python 2.x, while the code is for Python 
3.x. There are several changes between Python versions 2 and 3 that make the 
two languages different (or rather, the interpreters handle some code 
differently). One difference how the function 'input()' is handled, and that 
difference is big enough for your code to crash. 
I would hope that the book somewhere in the beginning mentions the code is for 
Python 3 and not for Python 2. The best solution for you is to try and install 
Python 3 and use that to proceed through the code in the book.

  Evert

NB: if-else are not actually loops, but rather form a conditional statement. 
You can, then, use such a if-else construction to break out of a loop, which 
probably will be shown in some later code. Just to be pedantic ;-).


> I know this is probably very simple but for some reason i cannot get my head 
> around it.
>  
> thank you for any help in advance
>  
> shane
> ___
> 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] Need help understanding output...

2010-08-18 Thread Evert Rol

On 18 Aug 2010, at 13:21 , Laurens Vets wrote:

> On 8/12/2010 1:26 AM, Steven D'Aprano wrote:
>> On Thu, 12 Aug 2010 07:04:15 am Laurens Vets wrote:
>> 
>>> I need to generate a list of 30 numbers randomly chosen from 1, 2, 3,
>>> 4, 5&  6. However, I cannot have more than 2 numbers which are the
>>> same next to each other. I came up with the following (Please ignore
>>> the fact that I'm trying to avoid an IndexError in a stupid way :)):
>> 
>> I can't possible do that! :)
>> 
>>> import random
>>> reeks = []
>>> while len(reeks)<= 1:
>>>number = random.randrange(1, 7, 1)
>>>reeks.append(number)
>>> 
>>> while len(reeks)<= 29:
>>>nummer = random.randrange(1, 7, 1)
>>>if nummer != reeks[-1] and nummer != reeks[-2]:
>>>  reeks.append(nummer)
>>> print reeks
>> 
>> This is probably a simpler way:
>> 
>> import random
>> reeks = []
>> for i in range(30):
>> temp = [random.randint(1, 6)]
>> while reeks[-2:-1] == reeks[-1:] == temp:
>> # print "Triplet found:", reeks, temp
>> temp = [random.randint(1, 6)]
>> reeks.extend(temp)
>> 
>> print reeks
> 
> 
> 
> Thank you all for your help! I've added another condition to this program, 
> namely, in a range of 60, each 'random' number can only occur 10 times. I 
> came up with the following:
> 
> import random
> series = []
> for i in range(60):
>  temp = [random.randint(1, 6)]
>  while series[-2:-1] == series[-1:] == temp:
>temp = [random.randint(1, 6)]
>  while series.count(temp[0]) >= 10:
>temp = [random.randint(1, 6)]
>  series.extend(temp)
> print series
> 
> However, this also generates gems such as:
> 
> [4, 4, 3, 6, 3, 2, 6, 3, 4, 3, 4, 1, 4, 2, 4, 3, 4, 4, 6, 2, 1, 5, 5, 6, 5, 
> 6, 5, 6, 3, 3, 1, 6, 6, 4, 1, 5, 2, 6, 6, 4, 2, 5, 3, 1, 5, 5, 2, 1, _2_, 
> _2_, _2_, 3, 3, 2, 1, 5, 1, 1, 5, 1]
> 
> [1, 4, 3, 1, 5, 3, 5, 1, 5, 6, 5, 3, 2, 6, 1, 4, 1, 5, 5, 2, 6, 2, 4, 1, 3, 
> 1, 2, 1, 1, 3, 1, 6, 6, 3, 2, 3, 6, 4, 5, 6, 5, 6, 3, 6, 2, 4, 5, 3, 3, 4, 6, 
> _4_, _4_, _4_, 5, 4, _2_, _2_, _2_, _2_]
> 
> I thought this needed to become the following:
> 
> import random
> series = []
> for i in range(60):
>  temp = [random.randint(1, 6)]
>  print "Temp", i, ":", temp
>  while series[-2:-1] == series[-1:] == series:
>if series.count(temp[0]) >= 10:
>  temp = [random.randint(1, 6)]
>  series.extend(temp)
> print series
> 
> But this just hangs whenever the while clause matches. I'm not sure what I'm 
> doing wrong here. I do know the random.shuffle() function, but I can't put my 
> conditions in there.


I assume the '== series:' is a typo, and should be '== temp'. Otherwise I don't 
see how this matches, unless series = [] (which means the while clause always 
matches, right at the start. Perhaps that actually is what you're seeing?). 
That's probably the disadvantage of using a list to avoid an IndexError (sorry 
Steven; I would have just caught the IndexError, or have an 'if i < 2: 
continue' statement in there.)

As suggestion for avoiding occurrences of > 10 times: use a dict, where the 
random numbers become the keys and you add +1 every time to d[temp]. Checking 
if d[temp] > 10 is then very easy.


Cheers,

  Evert



> 
> Any push in the right direction would be greatly appreciated :)
> ___
> 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] flow problem with a exercise

2010-08-21 Thread Evert Rol
>  In [39]: t = 3
> 
> In [40]: round((t-32)/1.8)
> Out[40]: -16.0
> 
> In [41]: t = 3.0
> 
> In [42]: round((t-32)/1.8)
> Out[42]: -16.0
> 
> Works fine for me.
>  
> Correct,
> But I see one wierd thing.
>  
> round ((42-32)/1.8) gives a output -16.0 but (42-32)/1.8) gives also -16.0
> I was expectting that round will give 16 as output because round (32.0) is 
> the same as round (32.0, 0) so there will be 0 decimals.
> And I see one decimal.

The rounding doesn't influence how it's printed.
>From help(round):

"""
round(...)
round(number[, ndigits]) -> floating point number

Round a number to a given precision in decimal digits (default 0 digits).
This always returns a floating point number.  Precision may be negative.
"""

It *rounds* the number to ndigits, not prints. It always returns a floating 
point number though (not an integer).
Since floats are normally represented with at least one trailing digit after 
the decimal dot, you see a zero.
Eg,
>>> float(1)
1.0

If you want to get rid of the trailing .0, convert it to an integer:
>>> int(round(1.1))
1

Also consider:
>>> round(1.15, 0)
1.0
>>> round(1.15, 1)
1.2
>>> round(1.15, 2)
1.1499


(Note again how the last rounded 1.15 is represented. It's just a 
representation though, and showing the imprecision you intrinsicaly get when 
dealing with floating point numbers.)

If you really want different behaviour when printing (or using) floating point 
numbers, perhaps have a look at the decimal module: 
http://docs.python.org/library/decimal.html


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


Re: [Tutor] check the terminal keyword

2010-08-21 Thread Evert Rol
> i m making a app in which i launch application using os.system("input from 
> user"). I want to check whether the input entered by the user matches with 
> the exact keyword in terminal or not.
> like i want to launch vlc so user should provide me input as " vlc" in order 
> to launch the app just like he did from terminal. I want to make a check on 
> the input spell so that if he type "wlc" it shows an error to it. I have an 
> little idea abt sys.agrv but don't know how to use it... Plz help me guys.

Check the return value from os.system. If it's not 0, there was an error, 
likely caused by incorrect input.
Better yet, catch the error message you get back from the command line, and act 
on that (eg, show it to the user).

Eg, 
>>> r = os.system("hello")
sh: hello: command not found
>>> print r
32512

And have a look at the subprocess module, which I think is now the de facto 
module to run external processes. 

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


Re: [Tutor] prime test problem

2010-08-21 Thread Evert Rol
> Hello, 
>  
> I know.
> I have read them all I believe but I can't see how I can convert the algebra 
> to a working programm.

And if you just search Google for "Python prime number algorithm"? Perhaps it's 
cheating, so you'll have to try and fully understand the code first before you 
run it (be sure to read comments if there are any, eg the activatestate 
recipes; can have tons of useful extra info & links).
Generally, try to start with a program yourself, and then see where you get 
stuck. You could then post your stuck algorithm to the list and ask for advice; 
your current question is a bit too general, and thus harder to answer.

  Evert


>  
> Roelof
> 
>  
> Date: Sat, 21 Aug 2010 19:15:03 +0530
> Subject: Re: [Tutor] prime test problem
> From: nitin@gmail.com
> To: rwob...@hotmail.com
> CC: tutor@python.org
> 
> For this problem u will get lots of solutions on the net.
> e.g wilson's theorem , sieve of eranthoses etc.
> 
> --nitin
> 
> On Sat, Aug 21, 2010 at 7:05 PM, Roelof Wobben  wrote:
> Hello, 
>  
> I have to make a programm which can test if a number is a prime.
> I know a prime is a number which can only be diveded by 1 and itself.
>  
> One way is was thinking about is to make a loop which try if % has output 0.
> But that don't work.
>  
> Can someone give me a hint what's the best approach is.
>  
> Roelof
>  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] prime test problem

2010-08-21 Thread Evert Rol
> Hello,
>  
> I tried it with this simple programm 
>  
> def is_prime(n):
> x=2 
> while x <= int(n**0.5)+1:
> if n % x == 0: 
> return False

If your while condition is True, you get into the loop. 
Inside the loop, however, you never change anything that could change the 
condition (ie, neither x nor n get changed).
So the while condition stays the same, ie, True, and you loop indefinitely.


> x=x+1;

Ah, but here you actually change something so that the while condition could 
become False. Sadly, this statement is outside the loop (hint hint).


> 
> return True
>   
> x=is_prime(7)
> if x==True:
> print 7, "is een prime getal"
> else :
> print 7, "is geen prime getal"
>  
>  
> But this one gets in a indefinitive loop.

Try to mentally follow the logic of the loop. 
Or use print statements and some small, easily checkable, numbers (prime and 
non-prime) to see what happens. 
Print statements (functions, if you're on Python >= 3) are a simple, but at 
times extremely quick and useful way to debug scripts.

Ah yes, and either use "is een priemgetal" or "is a prime number", not a mix of 
both (sorry, couldn't help myself ;-).


  Evert



>  
> Roelof
> 
>  
> > From: st...@pearwood.info
> > To: tutor@python.org
> > Date: Sun, 22 Aug 2010 02:49:26 +1000
> > Subject: Re: [Tutor] prime test problem
> > 
> > On Sun, 22 Aug 2010 12:41:03 am Roelof Wobben wrote:
> > > Hello,
> > >
> > > I know.
> > > I have read them all I believe 
> > 
> > You've read all 64 million pages that Google finds? Wow, you must be a 
> > fast reader! Well done!
> > 
> > > but I can't see how I can convert the 
> > > algebra to a working programm.
> > 
> > Have you *tried*?
> > 
> > Perhaps you should try something a little bit less ambitious. Write a 
> > program to test whether a number is divisible by 3. Then write a 
> > program to test whether a number is divisible by 3 or 5. Then write a 
> > third program to test whether a number is divisible by 3, 5 or 7. 
> > 
> > Then generalise that third program.
> > 
> > Off you go. Come back when you have some code. Even if it isn't working 
> > code, at least try something.
> > 
> > 
> > 
> > -- 
> > Steven D'Aprano
> > ___
> > 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] FW: find() problem

2010-08-24 Thread Evert Rol
> > > def find(strng, ch, start, step=1):
> > > index = start
> > The problem lies here, if you do a print on index, it never gets past
> > the first index of the number, so
> > your while loop below goes into an infinite loop.
> > 
> > For example:
> > find('starfruit','t',0) <- First time will return 1
> > find('starfruit','t',1) <- Still returns 1. Infinite loop
> > 
> > > while 0 <= index < len(strng):
> > > if strng[index] == ch:
> > > return index
> > > index += step
> > > return -1
> > >
> > > fruit=""
> > > letter=""
> > > fruit= raw_input("Enter a sort of fruit: ")
> > > letter = raw_input("Enter the character which must be counted: ")
> > > start=0
> > > aantal=0
> > > while 0 <=start < len(fruit):
> > > x=find (fruit,letter, start)
> > > aantal +=1
> > > start=x
> > > print "De letter", letter , "komt", aantal , "maal voor in het woord", 
> > > fruit
> > >
> > 
> > HTH,
> > Tino
> 
> Hello, 
>  
> Your right. index get never past 1 
> But in my opinion when something is found then x will be the place where the 
> character is be found.
> After that the counter is increased and start gets the value of x.
> So start should change.
>  
> Now finding out why this is not happening.

You're including the previous found index; so it will just find the character 
at that same index again. You need to start the next search one index further 
down the word.


>  
> But thanks for the help.
>  
> Roelof
>  
> ___
> 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] FW: find() problem

2010-08-24 Thread Evert Rol
> > > > > def find(strng, ch, start, step=1):
> > > > > index = start
> > > > The problem lies here, if you do a print on index, it never gets past
> > > > the first index of the number, so
> > > > your while loop below goes into an infinite loop.
> > > > 
> > > > For example:
> > > > find('starfruit','t',0) <- First time will return 1
> > > > find('starfruit','t',1) <- Still returns 1. Infinite loop
> > > > 
> > > > > while 0 <= index < len(strng):
> > > > > if strng[index] == ch:
> > > > > return index
> > > > > index += step
> > > > > return -1

Why are you returning -1 here? 
-1 is a valid list index. 
And with your last change, it makes your main condition valid.


> > > > >
> > > > > fruit=""
> > > > > letter=""
> > > > > fruit= raw_input("Enter a sort of fruit: ")
> > > > > letter = raw_input("Enter the character which must be counted: ")
> > > > > start=0
> > > > > aantal=0
> > > > > while 0 <=start < len(fruit):
> > > > > x=find (fruit,letter, start)
> > > > > aantal +=1
> > > > > start=x
> > > > > print "De letter", letter , "komt", aantal , "maal voor in het 
> > > > > woord", fruit
> > > > >
> > > > 
> > > > HTH,
> > > > Tino
> > > 
> > > Hello, 
> > > 
> > > Your right. index get never past 1 
> > > But in my opinion when something is found then x will be the place where 
> > > the character is be found.
> > > After that the counter is increased and start gets the value of x.
> > > So start should change.
> > > 
> > > Now finding out why this is not happening.
> > 
> > You're including the previous found index; so it will just find the 
> > character at that same index again. You need to start the next search one 
> > index further down the word.
> 
>  
> Hello Evert.
>  
> Stupid mistake.
> I change start=x to start=x+1 
> But still it's not working properly.
>  
> I can see that on this example.
>  
> Fruit : banaan
> letter : a
>  
> That a is being found at 2,4,5 which is correct but the programm don't end.
> So there's another error somewhere,
>  
> Roelof
>  
> > 
> > 
> > > 
> > > But thanks for the help.
> > > 
> > > Roelof
> > > 
> > > ___
> > > 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] FW: find() problem

2010-08-24 Thread Evert Rol
> I found it.

Good.
Few generic comments nonetheless, just for the fun of it ;-).

> This one does the trick :
>  
> def find(strng, ch, start, step=1):
> index=start
> while 0 <= index < len(strng):
> if strng[index] == ch:
>   return index 
> index += step
> return -2

You can actually use 'return index'. When you reach the end of the function, 
index == len(strng), which would be invalid in your main while condition, and 
the +1 would still keep it that way.
But read on if you want to keep the return -1 from the book.

> 
> fruit=""
> letter=""
> fruit= raw_input("Enter a sort of fruit: ")
> letter = raw_input("Enter the character which must be counted: ")
> index=1
> aantal=0
> while 0 <=index < len(fruit):
> x=find (fruit,letter, index)

You can check for x == -1 here (if you have the old find() from the book), and 
then break out of the loop. Provided the book has already dealt with the break 
statement. If you use break, your while condition can simply be 'while True:'

> index=x+1
> if x<>-2 :

Don't use <>, but != instead. 
If you ever use Python 3, it doesn't work anymore: 
http://docs.python.org/release/3.0.1/whatsnew/3.0.html#removed-syntax


> aantal=aantal+1
> print "De letter", letter , "komt", aantal , "maal voor in het woord", fruit
>  
> Roelof
> 
> > 
> > > > > > > def find(strng, ch, start, step=1):
> > > > > > > index = start
> > > > > > The problem lies here, if you do a print on index, it never gets 
> > > > > > past
> > > > > > the first index of the number, so
> > > > > > your while loop below goes into an infinite loop.
> > > > > > 
> > > > > > For example:
> > > > > > find('starfruit','t',0) <- First time will return 1
> > > > > > find('starfruit','t',1) <- Still returns 1. Infinite loop
> > > > > > 
> > > > > > > while 0 <= index < len(strng):
> > > > > > > if strng[index] == ch:
> > > > > > > return index
> > > > > > > index += step
> > > > > > > return -1
> > 
> > Why are you returning -1 here? 
> > -1 is a valid list index. 
> > And with your last change, it makes your main condition valid.
> > 
> > 
> > > > > > >
> > > > > > > fruit=""
> > > > > > > letter=""
> > > > > > > fruit= raw_input("Enter a sort of fruit: ")
> > > > > > > letter = raw_input("Enter the character which must be counted: ")
> > > > > > > start=0
> > > > > > > aantal=0
> > > > > > > while 0 <=start < len(fruit):
> > > > > > > x=find (fruit,letter, start)
> > > > > > > aantal +=1
> > > > > > > start=x
> > > > > > > print "De letter", letter , "komt", aantal , "maal voor in het 
> > > > > > > woord", fruit
> > > > > > >
> > > > > > 
> > > > > > HTH,
> > > > > > Tino
> > > > > 
> > > > > Hello, 
> > > > > 
> > > > > Your right. index get never past 1 
> > > > > But in my opinion when something is found then x will be the place 
> > > > > where the character is be found.
> > > > > After that the counter is increased and start gets the value of x.
> > > > > So start should change.
> > > > > 
> > > > > Now finding out why this is not happening.
> > > > 
> > > > You're including the previous found index; so it will just find the 
> > > > character at that same index again. You need to start the next search 
> > > > one index further down the word.
> > > 
> > > 
> > > Hello Evert.
> > > 
> > > Stupid mistake.
> > > I change start=x to start=x+1 
> > > But still it's not working properly.
> > > 
> > > I can see that on this example.
> > > 
> > > Fruit : banaan
> > > letter : a
> > > 
> > > That a is being found at 2,4,5 which is correct but the programm don't 
> > > end.
> > > So there's another error somewhere,
> > > 
> > > Roelof
> > > 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] FW: find() problem

2010-08-24 Thread Evert Rol
>>> I found it.
>> 
>> Good.
>> Few generic comments nonetheless, just for the fun of it ;-).
>> 
>>> This one does the trick :
>>> 
>>> def find(strng, ch, start, step=1):
>>> index=start
>>> while 0 <= index < len(strng):
>>> if strng[index] == ch:
>>> return index 
>>> index += step
>>> return -2
>> 
>> You can actually use 'return index'. When you reach the end of the function, 
>> index == len(strng), which would be invalid in your main while condition, 
>> and the +1 would still keep it that way.
>> But read on if you want to keep the return -1 from the book.
> 
> 
> Hello Evert, 
> 
> I don't get this.
> If you reach the end of the function , index==len(string) , then this loops 
> end. 
> index does then have the value of the last found lettter. So why +1 would it 
> keep it that way.

In your function, you keep adding step to index. If you won't find a match for 
a letter anymore, index reaches len(strng) and thus you break out of the while 
loop. Thus you continue to the return statement, and you return index (which 
equals len(strng) now).
Remember that len(strng) is the length of the string, but because Python's 
indices are zero-based, that does *not* equal the index of the last element: 
fruit[len(fruit)] will give an IndexError. So index does not have the value of 
the last found letter (actually, it never has, because it is an index, not a 
letter). 
In your main while loop, now, index == len(fruit), thus the condition fails. If 
you add one, you would get '0 <= len(fruit)+1 < len(fruit)', (index substituted 
with "len(fruit)"), which just as easily fails.

But if you don't get, better not use it; that generally leads to bugs.


> 
>> 
>>> 
>>> fruit=""
>>> letter=""
>>> fruit= raw_input("Enter a sort of fruit: ")
>>> letter = raw_input("Enter the character which must be counted: ")
>>> index=1
>>> aantal=0
>>> while 0 <=index < len(fruit):
>>> x=find (fruit,letter, index)
>> 
>> You can check for x == -1 here (if you have the old find() from the book), 
>> and then break out of the loop. Provided the book has already dealt with the 
>> break statement. If you use break, your while condition can simply be 'while 
>> True:'
>> 
>>> index=x+1
>>> if x<>-2 :
> 
> I don't thought about that but it is also a possibility.
> 
>> 
>> Don't use <>, but != instead. 
>> If you ever use Python 3, it doesn't work anymore: 
>> http://docs.python.org/release/3.0.1/whatsnew/3.0.html#removed-syntax
> 
> 
> Oke,  Point taken.
> 
> 



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


Re: [Tutor] can this be done easerly

2010-08-30 Thread Evert Rol
> For a exerise I made this one :"
>  
> import string
> def extract_words(s):
> """
>   >>> extract_words('Now is the time!  "Now", is the time? Yes, now.')
>   ['now', 'is', 'the', 'time', 'now', 'is', 'the', 'time', 'yes', 'now']
>   >>> extract_words('she tried to curtsey as she spoke--fancy')
>   ['she', 'tried', 'to', 'curtsey', 'as', 'she', 'spoke', 'fancy']
> """
> word= ""
> s=string.lower(s)
> for char in s :
> if ord(char) >=65 and ord(char) <= 122 or ord(char)==32 or 
> ord(char)==45:
>   word= word + char 
> word=string.split(word, "--")
> word=string.join(word, " ")
> word=word.replace ("  ", " ")
> word=string.split(word, " ")
> return word
> 
> if __name__ == '__main__':
> import doctest
> doctest.testmod()
>  
> But now I wonder if this can be done more easerly ?

Using regular expressions could work, depending on your view of regular 
expressions being 'easy':

import re
re.split('\W+', s.lower()) 

will do most of what you want (though you'll end up with the occasional empty 
string.

  Evert

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


Re: [Tutor] nested functions

2010-09-04 Thread Evert Rol
> hello,
> i have to plug two functions b() and c() inside another one a();
> i wonder if the code defining b and c must be in the same text file of
> a or it is possible to import b and c somehow, hence giving the code a
> neater appearance

Definitely!
Read through http://docs.python.org/tutorial/modules.html, that should 
definitely get you started.

Basically, with b & c defined in file1.py (choose your own appropriate name), 
from file2.py you can do:

import file1

def a(...):
file1.b()
file1.c()

or (bit shorter, but can be less clear):

from file1 import b, c

def a(...):
b()
c()



  Evert

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


Re: [Tutor] for loop results into list

2010-09-05 Thread Evert Rol
> Hello all,
> 
> I'm having a little problem figuring out how to accomplish this simple task. 
> I'd like to take a list of 6 numbers and add every permutation of those 
> numbers in groups of four. For example for 1, 2, 3, 4, 5, 6 add 1 + 1 + 1 +1 
> then 1 + 1 + 1 +2 etc. until reaching 6 + 6 + 6 + 6. Using a for loop, that 
> was the easy part, now I'd like to take the results and count the number of 
> times each number occurs.
> My problem occurs when I try to create a list from the results of the for 
> loop, it puts each individual number into its own list. I've looked 
> everywhere for the solution to this and can find nothing to help.
> 
> Any suggestions would be much appreciated

If you had some code, that would be very helpful. Now it's a bit of guesswork 
what exactly you have (code tends to be clearer than a full paragraph or two of 
text).
At least, I currently don't understand what your problem is (or what your 
for-loop involves).
Eg, are you looping and calling a function recursively, do you have four nested 
loops (or nested list comprehensions)? Or some other convenient loop to step 
through all combinations?

Anway, if you have a recent Python version (2.7 or 3.1), the itertools module 
provides a handy utiity: 
http://docs.python.org/py3k/library/itertools.html#itertools.combinations_with_replacement
Eg,

>>> map(sum, combinations_with_replacement(range(1,7), 4))
[4, 5, 6, 7, 8, 9, 6, 7, 8, 9, 10, 8, 9, 10, 11, 10, 11, 12, 12, 13, 14, 7, 8, 
9, 10, 11, 9, 10, 11, 12, 11, 12, 13, 13, 14, 15, 10, 11, 12, 13, 12, 13, 14, 
14, 15, 16, 13, 14, 15, 15, 16, 17, 16, 17, 18, 19, 8, 9, 10, 11, 12, 10, 11, 
12, 13, 12, 13, 14, 14, 15, 16, 11, 12, 13, 14, 13, 14, 15, 15, 16, 17, 14, 15, 
16, 16, 17, 18, 17, 18, 19, 20, 12, 13, 14, 15, 14, 15, 16, 16, 17, 18, 15, 16, 
17, 17, 18, 19, 18, 19, 20, 21, 16, 17, 18, 18, 19, 20, 19, 20, 21, 22, 20, 21, 
22, 23, 24]

seems to do what you want.

But, I'd still say to adopt your own code first, and when you've learned from 
that, just use the one-liner above. You're most welcome to ask your question, 
best done in combination with code, actual output and expected output. Then we 
can point you in the right direction.

Cheers,

  Evert

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


Re: [Tutor] for loop results into list

2010-09-05 Thread Evert Rol
>>> I'm having a little problem figuring out how to accomplish this simple 
>>> task. I'd like to take a list of 6 numbers and add every permutation of 
>>> those numbers in groups of four. For example for 1, 2, 3, 4, 5, 6 add 1 + 1 
>>> + 1 +1 then 1 + 1 + 1 +2 etc. until reaching 6 + 6 + 6 + 6. Using a for 
>>> loop, that was the easy part, now I'd like to take the results and count 
>>> the number of times each number occurs.
>>> My problem occurs when I try to create a list from the results of the for 
>>> loop, it puts each individual number into its own list. I've looked 
>>> everywhere for the solution to this and can find nothing to help.
>>> 
>>> Any suggestions would be much appreciated
>> If you had some code, that would be very helpful. Now it's a bit of 
>> guesswork what exactly you have (code tends to be clearer than a full 
>> paragraph or two of text).
>> At least, I currently don't understand what your problem is (or what your 
>> for-loop involves).
>> Eg, are you looping and calling a function recursively, do you have four 
>> nested loops (or nested list comprehensions)? Or some other convenient loop 
>> to step through all combinations?
>> 
>> Anway, if you have a recent Python version (2.7 or 3.1), the itertools 
>> module provides a handy utiity: 
>> http://docs.python.org/py3k/library/itertools.html#itertools.combinations_with_replacement
>> Eg,
>> 
> map(sum, combinations_with_replacement(range(1,7), 4))
>> [4, 5, 6, 7, 8, 9, 6, 7, 8, 9, 10, 8, 9, 10, 11, 10, 11, 12, 12, 13, 14, 7, 
>> 8, 9, 10, 11, 9, 10, 11, 12, 11, 12, 13, 13, 14, 15, 10, 11, 12, 13, 12, 13, 
>> 14, 14, 15, 16, 13, 14, 15, 15, 16, 17, 16, 17, 18, 19, 8, 9, 10, 11, 12, 
>> 10, 11, 12, 13, 12, 13, 14, 14, 15, 16, 11, 12, 13, 14, 13, 14, 15, 15, 16, 
>> 17, 14, 15, 16, 16, 17, 18, 17, 18, 19, 20, 12, 13, 14, 15, 14, 15, 16, 16, 
>> 17, 18, 15, 16, 17, 17, 18, 19, 18, 19, 20, 21, 16, 17, 18, 18, 19, 20, 19, 
>> 20, 21, 22, 20, 21, 22, 23, 24]
>> 
>> seems to do what you want.
>> 
>> But, I'd still say to adopt your own code first, and when you've learned 
>> from that, just use the one-liner above. You're most welcome to ask your 
>> question, best done in combination with code, actual output and expected 
>> output. Then we can point you in the right direction.
>> 
>> Cheers,
>> 
>>   Evert
>> 
> Thanks Evert, here is the code.
> 
> 
> fourdsix = [1, 2, 3, 4, 5, 6]
> for i in fourdsix:
>for j in fourdsix:
>for k in fourdsix:
>for l in fourdsix:
>fourdsix_result = [i, j, k, l]
>attribs = sum(fourdsix_result) - min(fourdsix_result)
>print attribs
> 
> This gives me the proper results,

I'm not sure I understand that, because now you have a subtraction here; not 
sure what that does.

> now it's just a matter of getting it into a list so I can further work with 
> the data.
> I've tried the following
> attrib_list = [attribs]
> 
> and
> attrib_list = []
> attrib_list.append(attribs)
> print attrib_list

This one should work, unless you've put it incorrectly inside the code. But 
otherwise, it will create the list you're looking for.
So then it's a matter of stepping through the numbers inside the list and 
counting their occurrences.
In fact, that could be done straight inside the quadruple nested for loops. One 
way I can think of, is using a dictionary, where the sum of the four-element 
list is the key, and the value increases by one each time. Eg:

try:
   counter[attribs] += 1
except KeyError:
   counter[attribs] = 1

or with dict.setdefault:

counter2[attribs] = counter2.setdefault(attribs, 0) + 1


(oh, and sorry: I missed the part where you wanted to count the number of times 
the sum appears in your initial email.)

> but these both only create a list of the last number.
> 
> I'm sure there is a pre-existing module that will do all of this for me but 
> I'm trying to learn by doing.

Definitely. 
It's often fun to be surprised later by the amount of utilities available in 
the Python standard library, that would have solved a problem in a one-liner 
(also a bit frustrating, but not too much).

Cheers,

  Evert

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


Re: [Tutor] for loop results into list

2010-09-05 Thread Evert Rol
> 
> I'm having a little problem figuring out how to accomplish this simple 
> task. I'd like to take a list of 6 numbers and add every permutation of 
> those numbers in groups of four. For example for 1, 2, 3, 4, 5, 6 add 1 + 
> 1 + 1 +1 then 1 + 1 + 1 +2 etc. until reaching 6 + 6 + 6 + 6. Using a for 
> loop, that was the easy part, now I'd like to take the results and count 
> the number of times each number occurs.
> My problem occurs when I try to create a list from the results of the for 
> loop, it puts each individual number into its own list. I've looked 
> everywhere for the solution to this and can find nothing to help.



>  here is the code.
>>> 
>>> 
>>> fourdsix = [1, 2, 3, 4, 5, 6]
>>> for i in fourdsix:
>>>for j in fourdsix:
>>>for k in fourdsix:
>>>for l in fourdsix:
>>>fourdsix_result = [i, j, k, l]
>>>attribs = sum(fourdsix_result) - min(fourdsix_result)
>>>print attribs
>>> 
>>> This gives me the proper results,
>> I'm not sure I understand that, because now you have a subtraction here; not 
>> sure what that does.
> 
> It removes the lowest number in the group of 4. It's intended to replicate 
> rolling four six sided dice, eliminating the lowest number and adding the 
> remaining 3 dice roll results. I didn't mention it cause I felt it wasn't 
> germane to the problem and it might needlessly complicate the situation.



>>> attrib_list = []
>>> attrib_list.append(attribs)
>>> print attrib_list
>> This one should work, unless you've put it incorrectly inside the code. But 
>> otherwise, it will create the list you're looking for.
>> So then it's a matter of stepping through the numbers inside the list and 
>> counting their occurrences.
> 
> I've tried this in every place in the code, outside the loop, inside at each 
> step of the loop and none of them get me what I want. Andre's suggestion that 
> I put the empty list before the loop helped but it's still giving me multiple 
> lists.

Can you send what you currently have? Sounds like you still have the first 
statement at some incorrect place in your code.


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


Re: [Tutor] for loop results into list

2010-09-05 Thread Evert Rol

On 5 Sep 2010, at 22:31 , Micheal Beatty wrote:

> On 09/05/2010 03:16 PM, Evert Rol wrote:
>>>>>>> I'm having a little problem figuring out how to accomplish this simple 
>>>>>>> task. I'd like to take a list of 6 numbers and add every permutation of 
>>>>>>> those numbers in groups of four. For example for 1, 2, 3, 4, 5, 6 add 1 
>>>>>>> + 1 + 1 +1 then 1 + 1 + 1 +2 etc. until reaching 6 + 6 + 6 + 6. Using a 
>>>>>>> for loop, that was the easy part, now I'd like to take the results and 
>>>>>>> count the number of times each number occurs.
>>>>>>> My problem occurs when I try to create a list from the results of the 
>>>>>>> for loop, it puts each individual number into its own list. I've looked 
>>>>>>> everywhere for the solution to this and can find nothing to help.
>> 
>> 
>>>>>>>  here is the code.
>>>>> 
>>>>> fourdsix = [1, 2, 3, 4, 5, 6]
>>>>> for i in fourdsix:
>>>>>for j in fourdsix:
>>>>>for k in fourdsix:
>>>>>for l in fourdsix:
>>>>>fourdsix_result = [i, j, k, l]
>>>>>attribs = sum(fourdsix_result) - min(fourdsix_result)
>>>>>print attribs
>>>>> 
>>>>> This gives me the proper results,
>>>> I'm not sure I understand that, because now you have a subtraction here; 
>>>> not sure what that does.
>>> It removes the lowest number in the group of 4. It's intended to replicate 
>>> rolling four six sided dice, eliminating the lowest number and adding the 
>>> remaining 3 dice roll results. I didn't mention it cause I felt it wasn't 
>>> germane to the problem and it might needlessly complicate the situation.
>> 
>> 
>>>>> attrib_list = []
>>>>> attrib_list.append(attribs)
>>>>> print attrib_list
>>>> This one should work, unless you've put it incorrectly inside the code. 
>>>> But otherwise, it will create the list you're looking for.
>>>> So then it's a matter of stepping through the numbers inside the list and 
>>>> counting their occurrences.
>>> I've tried this in every place in the code, outside the loop, inside at 
>>> each step of the loop and none of them get me what I want. Andre's 
>>> suggestion that I put the empty list before the loop helped but it's still 
>>> giving me multiple lists.
>> Can you send what you currently have? Sounds like you still have the first 
>> statement at some incorrect place in your code.
>> 
>> 
> Here is what I have.
> 
> # Program to determine frequency of each possible 4d6 die roll
> 
> attrib_list = []
> fourdsix = [1, 2, 3, 4, 5, 6] #list of possible 1d6 die roll  results
> for i in fourdsix:
>for j in fourdsix:
>for k in fourdsix:
>for l in fourdsix:
>fourdsix_result = [i, j, k, l] # creating list from loop 
> results
>attribs = sum(fourdsix_result) - min(fourdsix_result)
>attrib_list.append(attribs)
>print attrib_list
> 
> 
> This gets me multiple lists running through the loop.

Have you tried printing attrib_list at the very end of your code, *outside* all 
the nested loops?


I also noticed a mistake in a previous answer:

>>> map(sum, combinations_with_replacement(range(1,7), 4))

doesn't really work, because it produces eg [1, 1, 1, 2], but skips [2, 1, 1, 
1], [1, 2, 1, 1] & [1, 1, 2, 1].

itertools.product does produce all of these combinations (and the docs even say 
"Equivalent to nested for-loops in a generator expression." for product()). 
Of course, when you want to throw away the lowest number, it becomes something 
like:

>>> map(lambda x: sum(x)-min(x), itertools.product(range(1,7), repeat=4))
(list with 1296 elements)

Just for future reference.


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


Re: [Tutor] Python command calls the wrong version!

2010-09-07 Thread Evert Rol
> Dear Python Tutors,
> 
> I am new to Python, having perviously used IDL for all my scripts. I was 
> hoping to use Python and so I have just downloaded and installed  version 2.6 
> using the mac installer. That all went fine.
> 
> I then opened up X11, all fine.
> 
> Then I typed in >python
> 
> and got this message
> 
> python: execv: 
> /Applications/scisoft/i386/Packages/Python-2.5.4/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python:
>  No such file or directory
> 
> W!!! why is my python command trying to call a version which does not 
> exist? I appear to have broken Python? I am sire this is a really easy thing 
> to fix but I do not know enough about hows these programmes work to figure it 
> out for myself.

Most likely your path has been screwed up by the installation of scisoft. From 
the fact that it now can't find this Python 2.5, it appears you've later 
removed scisoft, but never changed your path back (check your .bashrc (or 
.cshrc, depending on your shell).
Also check your PATH:
$> echo $PATH
and perhaps even
$> which python

to see what you get back. If that points to some awkwardly located python, 
there's your problem.


Btw, if you trying to replace IDL with Python (I assume RSI IDL), you may be 
better off using macports, because you'll want various Python libraries & 
modules on your Mac (eg numpy, scipy, matplotlib). And, in fact, you don't 
really need X11, although that may depend on the GUI toolkit you're using 
(TKinter works without, pygtk needs X11 & GTK, the latter also available 
through macports); you can use start Python from the Terminal.


  Evert

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


Re: [Tutor] sort problem

2010-09-08 Thread Evert Rol
> I have this :
>  
> def sort_sequence(seq):
> """
>   >>> sort_sequence([3, 4, 6, 7, 8, 2])
>   [2, 3, 4, 6, 7, 8]
>   >>> sort_sequence((3, 4, 6, 7, 8, 2))
>   (2, 3, 4, 6, 7, 8)
>   >>> sort_sequence("nothappy")
>   'ahnoppty'
> """
>if type(seq) == type([]):
> seq.sort()
> elif type(seq)== type(()):
> seq = tuple(sorted(seq))
> else:
> seq2 = list(seq)
> seq2.sort()
> print seq2
> seq.join(seq2)
> return seq
>  
> The problem is that if I want to sort the characters in a string, the list 
> exist of the sorted characters but as soon as I convert them to a string I 
> get the old string.

Carefully read the documentation for str.join: 
http://docs.python.org/library/stdtypes.html#str.join

How does it work, what does it return, etc. Then fix the corresponding line in 
your code.
As a hint: str.join does work quite different than list.sort; I assume you're 
confusing their syntaxes.

Good luck,

  Evert


>  
> What went wrong ?
>  
> Roelof
>  
> ___
> 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] slicing a string

2010-09-08 Thread Evert Rol
>> But remember that you can make it simpler if you simply don't specify
>> the start and end points:
>> 
> 'hello'[::-1]
>> 'olleh'
>> 
> 
> While I know that idiom works, I haven't really found an explanation
> as to *why* it works that way.
> 
> For a string S:
> * Using  range, you need range(len(S),-1,-1) to give you the indexes
> for the string in reverse.
> * For slices, if you dont specify the start and end indices, they are
> supposed to be filled in by 0 and len(S) respectively.
>  - So S[::-1] means, S[0:len(S):-1] , so why dont we start with index
> 0 here, and then go to -1 (last char) and then into an infinite loop?

I guess because Python "is smart", and works the way you want/expect it to.
Read 
http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange
 , note 5 (about one "page" down), which explicitly says "If i or j are omitted 
or None, they become “end” values (which end depends on the sign of k)", where 
the important bit for this discussion is actually between parentheses.

And to quote part of the Zen of Python:
"
Special cases aren't special enough to break the rules.
Although practicality beats purity.
"

Reversing the automatic end values is very practical when the step index < 0.


>  - Especially, when S[0:len(S):1] works that way?
> 
> - Sandip
> ___
> 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] Exception Handling and Stack traces

2010-09-10 Thread Evert Rol
> I can't work out how to suppress stacktrace printing when exceptions
> are thrown.
> 
> I want the thrown exception to pass a message on the console, just
> like Java does when I catch an exception and print e.getMessage().
> 
> I tried some of the examples of controlling traceback through the
> traceback module.
> 
> I have to admit, this is one of the cases where I wonder why it has to
> be made so bloody complicated.  The other day, I read an article by
> Guido in which he was proposing to remove 'map' and 'filter' from the
> language because he though the developer shouldn't have to think too
> much about using them.  But the exception handling is so non-intuitive
> that the time saved from not having to think about using 'map' is
> spent instead on trying to figure out how to promote a message to the
> commandline when a method fails.
> 
> It seems that exceptions automatically are thrown up, so even if I put
> a 'try/except' clause in a method; when that method fails, the
> exception will still be thrown up to the top of the call chain.  So,
> there seems to be no reason whatever to catch an exception in any
> method except the top caller (i.e., 'main').  
> 
> Example:
> 
> def getData(auth) :
>   # create opener with auth headers here
>   try :
>   data = opener.open(url)
>   except urllib2.URLError("Badly formed URL") :
>   formatted_lines = traceback.format_exc().splitlines()
>   print formatted_lines[0]
>   print formatted_lines[-1]
>   sys.exit(1)
>   return data

This is a bit of a guess, but as far as I know, you can catch exceptions like 
that. 
Try:

try:
data = opener.open(url)
except urllib2.URLError as msg:
print msg
sys.exit(1)

If you're using an older version of Python, you'll need:

try:
data = opener.open(url)
except urllib2.URLError, msg:
print msg
sys.exit(1)

In your example, you are *creating* an exception (but doing nothing with it; I 
have no idea what happens if you have a line like "except ". Perhaps it tries to compare one on one with that instance, but if 
it compares by id, that will not work).
In this way, you're not catching the exception. So, it will be pass your except 
clause, and just do what it always does: print the whole exception's traceback. 
Which is probably what you're seeing.


  Evert



> 
> This method is called by another method, printOutput(), which
> processes the return data (XML from web service).
> 
> That method is called in main:
> 
> [printOutput(w) for w in weeks]
> 
> All I want to see is that if the exception is thrown in getData(), the
> message is printed to stdout and the script exits.  Instead, I get the
> stacktrace printed back down from main, I don't get the exception
> handled in getData (i.e., the error message and exit).
> 
> Now, I'm sure somebody is going to explain to me why it's so
> unreasonable to think that I ought to be able to get an error message
> from e.getMessage() and a stacktrace from e.printStacktrace() and that
> I ought to be able to choose between the two.  Because, it seems that
> python is determined that I should have a stacktrace whether I want
> one or not.
> 
> Sorry, I'm more than a little annoyed because even the example of
> using the traceback module from the python docs does not provide the
> handling that it is supposed to; and I really think this level of
> complexity for handling exceptions cleanly is just unwarranted.  I
> need to be able to give this script to someone who will want to be
> able to read the error output without having to be a Python programmer
> experienced in reading stack traces.  e.g. a "Badly formed URL"
> message that tells them they set up the parameters for connecting to
> the web service incorrectly.
> 
> Hopefully, you can get past the rant and help me solve this problem.
> 
> Thanks.
> 
> mp
> 
> -- 
> Michael Powe  mich...@trollope.orgNaugatuck CT USA
> 
> "The secret to strong security: less reliance on secrets."
> -- Whitfield Diffie
> ___
> 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] Exception Handling and Stack traces

2010-09-10 Thread Evert Rol
>>> I can't work out how to suppress stacktrace printing when exceptions
>>> are thrown.
>> 
>> [snip rant]
>> 
>> It might have been a good idea to read a tutorial like
>> 
>> http://docs.python.org/tutorial/errors.html#handling-exceptions
> 
>> or ask before you got annoyed enough to write that rant ;)
> 
> Hello,
> 
> Thanks for the reply.  Stupid me, I just read a half dozen articles on
> the web about python exception handling, including some at
> docs.python.  At no point is the 'as' clause discussed as being
> required.

Because 'as' didn't use to be there. That is more recent.

The real difference is between using an 'instance' and a class in the except 
clause. You used the former, you need the latter.


> Note that in section 8.3 of that article, the statement is made that
> if the exception matches the the exception type in the following
> format, the statements within the except clause are executed.
> 
> except URLError :
>  # do something
> 
> That in fact, seems to me to be incorrect.  It is not my experience
> (e.g., print statements are not executed in the example I gave and the
> sys.exit() is not called).

Have you tried this? In your example, you have 

except urllib2.URLError("Badly formed URL") :

which is quite a different thing; and I'm quite sure it's like that in the docs.
If you have tried the above ("except URLError"), I'm curious about an example.

Cheers,

  Evert



> 
> I'll follow up on your suggestions.  I appreciate the help.
> 
> Thanks.
> 
> mp
> 
>> To catch an exception you have to put the class into the except clause, not 
>> an instance. Basic example, using 2.6 syntax:
>> 
>> WRONG:
>> 
> try:
>> ... 1/0
>> ... except ZeroDivisionError("whatever"):
>> ... print "caught"
>> ...
>> Traceback (most recent call last):
>>  File "", line 2, in 
>> ZeroDivisionError: integer division or modulo by zero
>> 
>> CORRECT:
>> 
> try:
>> ... 1/0
>> ... except ZeroDivisionError as e:
>> ... print "caught", e
>> ...
>> caught integer division or modulo by zero
>> 
>> Peter

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


Re: [Tutor] Trapping HTTP Authentication Failure

2010-09-10 Thread Evert Rol
> My script to call a web service authenticates.  

Sorry, but where is the (full) script? I missed an attachment or (preferably) 
a link.


> I would like to be
> able to trap an exception if the authentication fails.  The script
> loops over a list of dates and I don't want it to retry for every
> element in the list.  This could take a long time and be very annoying
> when, after the long wait, a stacktrace spews out of the last attempt.
> The assumption is that if it fails, it is not a transient network or
> some other issue but that the credentials themselves are faulty.
> 
> Now, the authentication header is sent with the initial request, so it
> does not look to me like the standard process of request, get a 401
> and then re-request with credentials is relevant.  However, clearly
> the opener issues a number of retries after the initial failure.
> 
> But, I don't see a mechanism in urllib2 for taking notice of a failure
> and acting on it.
> 
> Can somebody point me toward a solution?
> 
> Thanks.
> 
> mp

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


Re: [Tutor] smtp connection problem --- socket error 10061

2010-09-10 Thread Evert Rol
> I could not connect with gmail smtp server in Vista 32( worked ok in XP 32). 
> Both vista and xp have same anti-virus software.
> 
 smtplib.SMTP("smtp.gmail.com",587)
> 
> Traceback (most recent call last):
>  File "", line 1, in 
>smtplib.SMTP("smtp.gmail.com",587)
>  File "C:\Program Files\Python25\lib\smtplib.py", line 244, in __init__
>(code, msg) = self.connect(host, port)
>  File "C:\Program Files\Python25\lib\smtplib.py", line 310, in connect
>raise socket.error, msg
> error: (10061, 'Connection refused')
> 
> I am using IPV4 for my vista wireless connection. No improvement with 
> firewall disabled.
> 
> Any one has this problem? any solution?

Do things work when you use SSL or TLS (through SMTP_SSL or using starttls, 
respectively)? Perhaps Vista is more strict in checking for this when 
connecting through a secure port (465 for SSL, 587 for TLS).

It's just a very simple guess, because I have no access to any Windows system.


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


Re: [Tutor] Trapping HTTP Authentication Failure

2010-09-11 Thread Evert Rol
>>> My script to call a web service authenticates.  
> 
>> Sorry, but where is the (full) script? I missed an attachment or 
>> (preferably) a link.
> 
> Hello,
> 
> Sorry, the verb of the sentence is "authenticates," as in, "My script
> ... authenticates."

Sorry, misread that.
Although code does help :-). 
I assume the rest of the code is just the loop around the items you want to 
fetch, calling getData each time with a new URL.


> But I can show the authentication portion.
> 
> 8<-- start >8
> 
> # Creates an authentication object with the credentials for a given URL
> def createPasswordManager(headers) :
>passwordManager = urllib2.HTTPPasswordMgrWithDefaultRealm()
>passwordManager.add_password(None,overview_url,headers[0],headers[1])
>return passwordManager
> 
> # Creates an authentication handler for the authentication object created 
> above
> def createAuthenticationHandler(passwordManager) :
>authenticationHandler = urllib2.HTTPBasicAuthHandler(passwordManager)
>return authenticationHandler
> 
> # Creates an opener that sets the credentials in the Request
> def createOpener(authHandler) :
>return urllib2.build_opener(authHandler)
> 
> 
> # Retrieves the data
> def getData(authHeaders) :
>opener = 
> createOpener(createAuthenticationHandler(createPasswordManager(authHeaders)))
>data = opener.open(overview_url)
>return data
> 8<--- end >8
> 
> So, to restate the question, how can I trap an exception in the cases
> in which authentication fails? 
> 
> Right now, the whole script is complete and working (thanks for your
> help with my other exception-handling question).  Except for the case
> of bad credentials.  The use case is that the user misspells a
> username or password or puts in a wrong account information.  Then, I
> don't want them to sit for 10 minutes while the script makes 30 data
> connections, retries and fails each time.

I'm not sure what you're exactly doing here, or what you're getting, but I did 
get curious and dug around urllib2.py. Apparently, there is a hardcoded 5 
retries before the authentication really fails. So any stack trace would be the 
normal stack trace times 5. Not the 30 you mentioned, but annoying enough 
anyway (I don't see how it would fail for every element in the loop though. 
Once it raises an exception, the program basically ends).
I don't know why it's hard-coded that way, and not just an option with a 
default of 5, but that's currently how it is (maybe someone else on this list 
knows?).
If that's what you're finding, perhaps the quickest way is to subclass 
urllib2.HTTPBasicAuthHandler, and override the http_error_auth_reqed method 
(essentially keeping it exactly the same apart from the hard-coded 5).

Otherwise, I'm afraid I still don't know what's the problem you're having.

  Evert

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


Re: [Tutor] Trapping HTTP Authentication Failure

2010-09-11 Thread Evert Rol


>> I'm not sure what you're exactly doing here, or what you're getting,
>> but I did get curious and dug around urllib2.py. Apparently, there is
>> a hardcoded 5 retries before the authentication really fails. So any
>> stack trace would be the normal stack trace times 5. Not the 30 you
>> mentioned, but annoying enough anyway (I don't see how it would fail
>> for every element in the loop though. Once it raises an exception,
>> the program basically ends).
> 
> It never throws an exception.  Or, if it does, something about the way
> I'm calling suppresses it.  IOW, I can put in a bogus credential and
> start the script and sit here for 5 minutes and see nothing.  Then ^C
> and I get a huge stacktrace that shows the repeated calls.  After the
> timeout on one element in the list, it goes to the next element, times
> out, goes to the next.

Ok, now I had to try and recreate something myself. So my processData is:

def processData(f):
   global overview_url
   overview_url = baseurl + f
   getData(authHeaders)

(f being a filename, out of a list of many). Other code same as yours.

It definitely throws a 401 exception after 5 retries. No time-outs, no long 
waits. In fact, a time-out would to me indicate another problem (it still 
should throw an exception, though). So, unless you're catching the exception in 
processData somehow, I don't see where things could go wrong. 
I assume you have no problem with correct credentials or simply using a 
webbrowser?



>> I don't know why it's hard-coded that way, and not just an option
>> with a default of 5, but that's currently how it is (maybe someone
>> else on this list knows?).
> 
> I don't know, but even if I could set it to 1, I'm not helped unless
> there's a way for me to make it throw an exception and exit the loop. 
> 
>> If that's what you're finding, perhaps the quickest way is to
>> subclass urllib2.HTTPBasicAuthHandler, and override the
>> http_error_auth_reqed method (essentially keeping it exactly the
>> same apart from the hard-coded 5).
> 
> Now there's a challenge!  ;-)

It'd be straightforward, but not solve your current problem, I'm afraid.

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


Re: [Tutor] tree problem

2010-09-12 Thread Evert Rol
> Write a program named litter.py that creates an empty file named trash.txt in 
> each subdirectory of a directory tree given the root of the tree as an 
> argument (or the current directory as a default). 
> 
> So I change the example to this :
> 
> def traverse(path, s='.\n', f=0, d=0):
> path2file = os.path.join(path) *** pathfile contains the path 
> if os.path.isdir(path2file):  if pathfile is a dir.
> d += 1 * the is one more directory
> if getdirlist(path2file): ** if the outcome of getdirlist is the same as 
> the current directory
> s, f, d = traverse(path2file, '| ' + s, f, d) do this module again
> else:
> f += 1 ** else f (number of files increases with 1 
> return s, f, d ** return s , numbers of files and the number of 
> directories.

That can't be a valid program: no indentation, comments not preceded by a 
comment mark (#), and getdirlist is nowhere defined afaics. While probably 
anyone can understand what's the real code of the above snippet, it doesn't 
help putting non-valid code like this in your email. If you can directly 
copy-paste code (plain text), that is almost always better.


> When I try to make it run I get this message :
> 
> File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 31, in traverse
> s, f, d = traverse(path2file, '| ' + s, f, d)
> File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 31, in traverse
> s, f, d = traverse(path2file, '| ' + s, f, d)
> File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 31, in traverse
> s, f, d = traverse(path2file, '| ' + s, f, d)
> File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 28, in traverse
> if os.path.isdir(path2file):
> File "C:\Python27\lib\genericpath.py", line 44, in isdir
> return stat.S_ISDIR(st.st_mode)
> File "C:\Python27\lib\stat.py", line 41, in S_ISDIR
> return S_IFMT(mode) == S_IFDIR
> RuntimeError: maximum recursion depth exceeded
> 
> I can't see why this happens.
> I know I have to fish but I can't see what's wrong here.
> So I hope someone can learn how to fish here.

Fishing is debugging. You could use the logging module for that, but assuming 
you're not familiar with that, litter your program with print statements, and 
print out the value of the various variables at certain points in your program 
(it helps putting a short string in the print statement as well, so you know 
which print statement print where. Eg, print '1:', s, f, d; and then a few 
lines below, print '2:', s, f, d).
Having done that (you will get a lot of output), try to follow the logic of the 
program and see why things happen the way they do. In this case, why you keep 
spiraling in and never break out of your recursion. Then, step by step, you can 
try and change or add statements so you actually find a way to break out the 
recursion.

  Evert

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


Re: [Tutor] What's the best way to ask forgiveness here?

2010-09-13 Thread Evert Rol
> I've been coding Python long enough that 'asking forgiveness instead of 
> permission' is my first instinct, but the resulting code is sometimes clumsy, 
> and I wonder if someone can suggest something I'm missing, or at least 
> validate what's going on here in some way. 
> 
> What I'm trying to do is write a file to a directory. However, the directory 
> may not exist the first time I try to write a file there, so I'm going to 
> first try to write the file, and if I get an exception, create the directory 
> (er, *try* to), and *then* write the file there.

That would work.
Though I would just try to create the error directory first. If that fails, I 
check the error message/code in the except clause: if it indicates the 
directory already exists, I pass the exception, otherwise reraise it.
Then I continue with creating the file within the directory I now am certain of 
exists.
Note 1: certain is only half: some other process could remove the directory in 
the split second between my code creating it and my code creating the file. If 
you think that could happen, you'll need to look at the other ways to do this.
Note 2: the directory can exist, but not have write access to your process. So 
between the try-except for creating a directory and the try-except for creating 
a file, you may put in a try-except for chmod. Of course, if you're not the 
owner, both the chmod and file creation will fail (I'm assuming some *nix 
platform here, btw).

> Here's my first shot at the code: 
> 
> try:  
> self.save_file(picfile_fullpath, picdata)
> except IOError as err:
> # directory doesn't exist. Try to create it.

Careful: you're not checking the actually error given by the exception. There 
may be more than one reason that the file can't be created (examples: the 
permissions mentioned above, or some file creation limit in a directory).


> try:  
> os.makedirs(picfile_fullpath)
> except OSError as oserr:
> logging.error("Can't create file path: %s (%s)" % 
> (picfile_fullpath, oserr))
> else: 
> # Created dir, now write file.
> try:  
> self.save_file(picfile_fullpath, picdata)
> except IOError as err:
> logging.error("Bailing. Couldn't save file %s (%s)" % 
> (picfile_fullpath, err)) 
> return False
> 
> Doesn't this seem less readable than the 'ask permission' equivalent? I think 
> it does, but in this case asking permission for every single operation when 
> the dir will only need to be created a single time (and then may be written 
> to several hundred times) is pretty wasteful.

One of the things I once read (but I forgot where) on this issue, is the usual 
"it depends". It depends whether you except that often, the directory doesn't 
exist and the file can't directly be created. In that case, if may be quicker 
to ask permission first (simple if-statement). If you expect that in general, 
you can immediately create the file within the directory (so an exception is 
unlikely to occur), then use a try-except clause.
But don't take my word for it; I'd be curious what others on this list say 
about this.


> 
> I suppose I could set some sentinel variable and check for it in a while 
> loop, but then I need some other scaffolding code to make sure I don't 
> infinitely loop trying to create the directory, and probably some other stuff 
> I'm forgetting, so it strikes me as being just as messy. 
> 
> Is there a clean sort of pattern to apply in instances like this? 

I guess not, though readability of code is an important thing to consider. In 
this case, I don't find the correctly unreadable, but at some point, these 
things do tend to get out of hand and you're better off coding it differently 
(perhaps even using functions).


  Evert

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


Re: [Tutor] re.findall parentheses problem

2010-09-14 Thread Evert Rol
> I have a regex that matches dates in various formats.  I've tested the regex 
> in a reliable testbed, and it seems to match what I want (dates in formats 
> like "1 Jan 2010" and "January 1, 2010" and also "January 2008").  It's just 
> that using re.findall with it is giving me weird output.  I'm using Python 
> 2.6.5 here, and I've put in line breaks for clarity's sake:
> 
> >>> import re
> 
> >>> date_regex = 
> >>> re.compile(r"([0-3]?[0-9])?((\s*)|(\t*))((Jan\.?u?a?r?y?)|(Feb\.?r?u?a?r?y?)|(Mar\.?c?h?)|(Apr\.?i?l?)|(May)|(Jun[e.]?)|(Jul[y.]?)|(Aug\.?u?s?t?)|(Sep[t.]?\.?e?m?b?e?r?)|(Oct\.?o?b?e?r?)|(Nov\.?e?m?b?e?r?)|(Dec\.?e?m?b?e?r?))((\s*)|(\t*))(2?0?[0-3]?[0-9]\,?)?((\s*)|(\t*))(2?0?[01][0-9])")

This will also match '1 Janry 2010'. 
Not sure if it should?


two examples

> >>> test_output = re.findall(date_regex, "The date was January 1, 2008.  But 
> >>> it was not January 2, 2008.")
> 
> >>> print test_output
> [('', ' ', ' ', '', 'January', 'January', '', '', '', '', '', '', '', '', '', 
> '', '', ' ', ' ', '', '1,', ' ', ' ', '', '2008'), ('', ' ', ' ', '', 
> 'January', 'January', '', '', '', '', '', '', '', '', '', '', '', ' ', ' ', 
> '', '2,', ' ', ' ', '', '2008')]
> 
> A friend says: " I think that the problem is that every time that you have a 
> parenthesis you get an output. Maybe there is a way to suppress this."
> 
> My friend's explanation speaks to the empties, but maybe not to the two 
> Januaries.  Either way, what I want is for re.finall, or some other re method 
> that perhaps I haven't properly explored, to return the matches and just the 
> matches.   
> 
> I've read the documentation, googled various permutations etc, and I can't 
> figure it out.  Any help much appreciated.

The docs say: " If one or more groups are present in the pattern, return a list 
of groups". So your friend is right.

In fact, your last example shows exactly this: it shows a list of two tuples. 
The tuples contain individual group matches, the two list elements are your two 
date matches.
You could solve this by grouping the entire regex (so r"(([0-3  [0-9]))" ; 
I would even use a named group), and then picking out the first tuple element 
of each list element:
[(' January 1, 2008', '', ' ', ' ', '', 'January', 'January', '', '', '', '', 
'', '', '', '', '', '', '', ' ', ' ', '', '1,', ' ', ' ', '', '2008'), (' 
January 2, 2008', '', ' ', ' ', '', 'January', 'January', '', '', '', '', '', 
'', '', '', '', '', '', ' ', ' ', '', '2,', ' ', ' ', '', '2008')]


Hth,

  Evert

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


Re: [Tutor] what happened to the cards module

2010-09-15 Thread Evert Rol
> I downloaded Python 2.6.6 for windows but I can't access the "Cards" module 
> for playing card games.
> 
> Did it get renamed? If so, how can I find it?

I don't think there's a Cards module in the standard library. At least, I've 
never seen it, nor can I find any mention about it on the python documentation 
page.

Probably this is a module you installed yourself later on, and is now only 
accessible for your previous Python version? You would have to reinstall it for 
Python 2.6.
How did you previously use Cards? What Python version.

Btw, I don't know what your upgrade path is, but can't you go to Python 2.7 
directly?

  Evert

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


Re: [Tutor] selecting elements from dictionary

2010-09-15 Thread Evert Rol
> using:
> 
> for key, value in xdic.items():
> if 1 in value and 2 in value or 3 in value:
> print key
> 
> 
> also print keys that have values such as [1,2,3]. 
> 
> In cases where there is [1,2,3] and [1,2] also reported. 
> 
> How can I extract those keys that have values only [1,2] and [1,3] 
> exclusively.  

If you know that elements in a list are unique (so only appear once), you may 
want to look at using sets.

  Evert


> >>> xdic = {75796988: [1, 2, 3], 75797478: [1, 2, 3], 75797887:[1,2], 
> >>> 75797987:[3,1]}
> >>> for key, value in xdic.items():
> ... if 1 in value and 2 in value or 3 in value:
> ... print key
> ...
> 75797987
> 75796988
> 75797478
> 75797887
> 
> 
> Here all 4 keys appear. Instead I want to get only 75797887:[1,2] and 
> 75797987:[3,1]
> how can I force this. 
> 
> thanks again. 
> 
> 
> 
> 
> 
> From: Steven D'Aprano 
> To: tutor@python.org
> Sent: Wed, September 15, 2010 7:27:05 AM
> Subject: Re: [Tutor] selecting elements from dictionary
> 
> On Wed, 15 Sep 2010 12:10:59 pm Hs Hs wrote:
> 
> > I want to print only those items that have [1,2] and [1,3]  in any
> > order, such as [1,2] or [2,1], [3,1] or [1,3]
> >
> > >>> for item in xdic.keys():
> >
> > ...if [1,2] in xdic[item]:
> > ...print item
> >
> > I get a wrong answer, 
> 
> That's because you ask the wrong question.
> 
> [1,2] in xdic[item] doesn't check to see if 1 is in the list, then if 2 
> is in the list. It looks to see if one of the items is *exactly* [1,2].
> 
> >>> [1,2] in [1,2,3,4]
> False
> >>> [1,2] in [1,2,3,4, [1,2]]
> True
> 
> 
> > I know the values are there. How can I print 
> > only those item that have [1,2] and [1,3]
> 
> for key, value in xdic.items():
> if 1 in value and 2 in value or 3 in value:
> print key
> 
> 
> 
> 
> -- 
> Steven D'Aprano
> ___
> 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] what happened to the cards module

2010-09-15 Thread Evert Rol
> Hi Evert:
> 
> I've been looking for a card playing framework for a long time. When I saw 
> "import Cards" and that he was shuffling, dealing cards, etc, I immediately 
> downloaded Python. Could this be available in Pygames?

It depends where you "him" shuffling & dealing cards. 
Pygames doesn't exist, pygame does, but probably doesn't have what you're 
looking for.

I do remember a set of questions on this list with a Cards example, but that 
was just some home-written code.

You'll need to check the context of where you saw this, and if it's useful and 
usable to you.
And I certainly don't know what you mean by a card playing framework: do you 
mean (library) code, which language, what "card game"?

  Evert



> Thanks.
> 
> John Soares
> jsoa...@safe-mail.net
> 
>  Original Message 
> From: Evert Rol 
> To: jsoa...@safe-mail.net
> Cc: tutor@python.org
> Subject: Re: [Tutor] what happened to the cards module
> Date: Wed, 15 Sep 2010 10:40:34 +0200
> 
>> I downloaded Python 2.6.6 for windows but I can't access the "Cards" module 
>> for playing card games.
>> 
>> Did it get renamed? If so, how can I find it?
> 
> I don't think there's a Cards module in the standard library. At least, I've 
> never seen it, nor can I find any mention about it on the python 
> documentation page.
> 
> Probably this is a module you installed yourself later on, and is now only 
> accessible for your previous Python version? You would have to reinstall it 
> for Python 2.6.
> How did you previously use Cards? What Python version.
> 
> Btw, I don't know what your upgrade path is, but can't you go to Python 2.7 
> directly?
> 
>  Evert

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


Re: [Tutor] quick speed question

2010-09-16 Thread Evert Rol
> Hello Tutors,
> 
> I was just wondering if you have a dictionary key is it faster to do:
> 
> if dict['key'] == 'foo':
>...
> 
> or is this faster:
> 
> if 'foo' in dict['key']:
>...
> 
> Or is there any difference and I'm chasing ghosts?

The latter: they are not the same:

>>> d = {'key': 'food'}
>>> d['key'] == 'foo'
False
>>> 'foo' in d['key']
True


Btw, generally don't use a reserved Python word for a variable, such as dict in 
this case (I know it's an example, but it's still unsafe practice).

Cheers,

  Evert

> 
> Thanks,
> 
> T
> -- 
> C.T. Matsumoto
> Claes de Vrieselaan 60a III
> 3021 JR Rotterdam
> The Netherlands
> 
> tel.: +31 (0)6 41 45 08 54
> ___
> 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] Function behavior

2010-09-16 Thread Evert Rol
> I am unclear on the behavior of using a function.  Below is a short code I 
> wrote to print an amount out after inputting the number of match.
> 
> # TEST Function.py
> 
> def change(amount):
>if match == 1:
>amount = 0
>if match == 2:
>amount = 0
>if match == 3:
>amount = 3
> 
> match = raw_input("How many matches?: ")
> change(match)
> print amount
> 
> ERROR Message:
> 
> How many matches?: 2
> Traceback (most recent call last):
>  File "/home/ken/Python262/TEST Function.py", line 13, in 
>print amount
> NameError: name 'amount' is not defined

Variables are only local to the their direct surroundings: in this case, amount 
is only local to the 'change' function, not outside it.

You might want to read through 
http://docs.python.org/tutorial/controlflow.html#defining-functions first.


  Evert


> How do I print out the amount of 0 if I input 2?
> 
> Should it be def change(match) instead of def change(amount)?
> 
> Perhaps, change(amount) instead of change(match)?
> 
> Perhaps, I need to add return somewhere?
> 
> Thanking you all in advance for your assistance.
> 
> Ken
> ___
> 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] robots question

2010-09-16 Thread Evert Rol
> As a exercise from this book ( Thinking like a computer scientist ) I have to 
> make this programm on this 
> page(http://openbookproject.net/thinkcs/python/english2e/ch12.html)
> Exercise 11 
> 
> #
> # robots.py
> #
> from gasp import *

Argh!
Is that really in the book? 
Bad book, bad.

You can just "import gasp" and type "gasp." a few times.

Lot of code


> def play_game(robots):
> begin_graphics(SCREEN_WIDTH, SCREEN_HEIGHT)
> player = place_player()
> robot = place_robots(4)
> junk = [place_robot(GRID_WIDTH/2, GRID_HEIGHT/2, junk="true" )]
> defeated = False
> 
> while not defeated:
> quit =  move_player(player)
> if quit:
> break
> move_robots(robot, player)
> defeated = check_collisions(robot, player, junk)
> 
> if defeated:
> remove_from_screen(player['shape'])
> for thing in robots + junk:
> remove_from_screen(thing['shape'])
> Text("They got you!", (240, 240), size=32)
> sleep(3)
> 
> end_graphics()
> 
> 
> 
> if __name__ == '__main__':
> play_game(2)
> 
> But now Im getting this error message :
> 
> Traceback (most recent call last):
>   File "/root/workspace/test2/src/test.py", line 120, in 
> play_game(2)
>   File "/root/workspace/test2/src/test.py", line 106, in play_game
> defeated = check_collisions(robot, player, junk)
>   File "/root/workspace/test2/src/test.py", line 73, in check_collisions
> for thing in robots + junk:
> TypeError: can only concatenate list (not "dict") to list
> 
> I understand that robots is a dict and junk is a list.
> 
> Is that right ?

I think robots is not even a dict, but I may be wrong here.
Check your variable *names* inside play_game, and your use of '2' and '4'. 
Aren't you mixing up 'robot' and 'robots'?
Have you tried putting print statements inside the code? Also 'print 
type()' can be variable.
Try more debugging when you get an exception.


> And why does the book say that when this message is appearing. 

A quick glance at those webpages doesn't show any place where the book gives 
this code. This seems to be code you added.


  Evert

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


Re: [Tutor] Bus Error with matplotlib

2010-09-17 Thread Evert Rol
> Hi, I have been trying to install matplotlib for python on my mac which is 
> running snow leopard. The installation appeared to go well until I tried the 
> following
> 
>> python
 import matplotlib
 import matplotlib.pyplot
> Bus error
>> 
> 
> It is very annoying, I have posted the error message below but I am not sure 
> why it is crashing at this point! 

This is really not a tutor question; you'd be better off checking on the 
matplotlib user group.

However:
- what version of matplotlib are you installing? 1.0 I assume?
- how are you installing matplotlib? Mac OS X binary (which one; there seem to 
be multiple options) or differently?
- have you tried installing from source? If you're not used to that, it can be 
a harsh exercise, but can at times result in working results

Btw, you're OS X version seems to run a bit behind: 10.6.4 is current. I don't 
expect it to let matplotlib work, but one never knows.

  Evert

> 
> Many thanks for your help,
> 
> Quinton
> 
> OS Version:  Mac OS X 10.6.3 (10D575)
> Report Version:  6
> 
> Interval Since Last Report:  3106 sec
> Crashes Since Last Report:   21
> Per-App Crashes Since Last Report:   16
> Anonymous UUID:  3FCCD611-0550-49F2-B5F4-43CD7E093033
> 
> Exception Type:  EXC_BAD_ACCESS (SIGBUS)
> Exception Codes: KERN_PROTECTION_FAILURE at 0x
> Crashed Thread:  0  Dispatch queue: com.apple.main-thread
> 
> Thread 0 Crashed:  Dispatch queue: com.apple.main-thread
> 0   ???   00 0 + 0
> 1   org.python.python 0x0009da39 _PyImport_LoadDynamicModule 
> + 204
> 2   org.python.python 0x0009c09f _PyImport_FindModule + 823
> 3   org.python.python 0x0009c88f PyImport_ReloadModule + 1392
> 4   org.python.python 0x0009cce7 PyImport_ReloadModule + 2504
> 5   org.python.python 0x0009d2cb PyImport_ImportModuleLevel + 
> 1221
> 6   org.python.python 0x0008578f _PyBuiltin_Init + 14665
> 7   org.python.python 0xc6e0 PyObject_Call + 101
> 8   org.python.python 0x0008678a 
> PyEval_CallObjectWithKeywords + 171
> 9   org.python.python 0x0008a758 PyEval_EvalFrameEx + 13261
> 10  org.python.python 0x0008cf74 PyEval_EvalCodeEx + 1720
> 11  org.python.python 0x0008d019 PyEval_EvalCode + 87
> 12  org.python.python 0x0009a542 PyImport_ExecCodeModuleEx + 
> 240
> 13  org.python.python 0x0009af3a PyImport_AppendInittab + 1164
> 14  org.python.python 0x0009c88f PyImport_ReloadModule + 1392
> 15  org.python.python 0x0009cce7 PyImport_ReloadModule + 2504
> 16  org.python.python 0x0009d295 PyImport_ImportModuleLevel + 
> 1167
> 17  org.python.python 0x0008578f _PyBuiltin_Init + 14665
> 18  org.python.python 0xc6e0 PyObject_Call + 101
> 19  org.python.python 0x0008678a 
> PyEval_CallObjectWithKeywords + 171
> 20  org.python.python 0x0008a758 PyEval_EvalFrameEx + 13261
> 21  org.python.python 0x0008cf74 PyEval_EvalCodeEx + 1720
> 22  org.python.python 0x0008d019 PyEval_EvalCode + 87
> 23  org.python.python 0x0009a542 PyImport_ExecCodeModuleEx + 
> 240
> 24  org.python.python 0x0009af3a PyImport_AppendInittab + 1164
> 25  org.python.python 0x0009c88f PyImport_ReloadModule + 1392
> 26  org.python.python 0x0009cce7 PyImport_ReloadModule + 2504
> 27  org.python.python 0x0009d295 PyImport_ImportModuleLevel + 
> 1167
> 28  org.python.python 0x0008578f _PyBuiltin_Init + 14665
> 29  org.python.python 0xc6e0 PyObject_Call + 101
> 30  org.python.python 0x0008678a 
> PyEval_CallObjectWithKeywords + 171
> 31  org.python.python 0x0008a758 PyEval_EvalFrameEx + 13261
> 32  org.python.python 0x0008cf74 PyEval_EvalCodeEx + 1720
> 33  org.python.python 0x0008d019 PyEval_EvalCode + 87
> 34  org.python.python 0x0009a542 PyImport_ExecCodeModuleEx + 
> 240
> 35  org.python.python 0x0009af3a PyImport_AppendInittab + 1164
> 36  org.python.python 0x0009c88f PyImport_ReloadModule + 1392
> 37  org.python.python 0x0009cce7 PyImport_ReloadModule + 2504
> 38  org.python.python 0x0009d2cb PyImport_ImportModuleLevel + 
> 1221
> 39  org.python.python 0x0008578f _PyBuiltin_Init + 14665
> 40  org.python.python 0xc6e0 PyObject_Call + 101
> 41  org.python.python 0x0008678a 
> PyEval_CallObjectWithKeywords + 171
> 42  org.python.python 0x0008a758 PyEval_EvalFrameEx + 13261
> 43  org.python.python 0x0008cf74 PyEval_EvalCodeEx + 1720
> 4

Re: [Tutor] trouble with a small Tkinter example

2010-09-21 Thread Evert Rol
> I'm having trouble with this small example program:
> 
> http://en.literateprograms.org/Bresenham%27s_line_algorithm_%28Python%29
> 
> When I run it, I only get a blank grey window. I'm running Python 2.6 under 
> Windows XP.
> 
> If there's a problem with the code, I can't see it... it seems like it should 
> work. Can anyone else try this and see if it works for them?

It appears that Tkinter (or probably the underling tcl/tk) is smart: if you 
create a line with the same start and end points, it won't draw a line.
Try it: create_line(10, 100, 10, 100, fill='red') won't work.


> If I stick this line in before the loop, it does draw a red line, so I know 
> my copy of Python/Tkinter is working:
> canvas.create_line(10, 100, 5, 50 , fill='red')


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


Re: [Tutor] input and raw input

2010-09-25 Thread Evert Rol
> any one have an idea about how we can input many number in the one time and 
> change it to list.
> for example:
>  
> a=input("Enter the number of your class in the school:") # the number can 
> be enter as: 12,13,14 or 12 13 14 with a space in between.
>  
> now how I can put these numbers into list like b=[12,13,14] with len( a ) =3

A string has a method split(); that may help you.
In your case, where you want either a space or a comma as a separator, it 
depends whether both can be used at the same time. If not, you can check for 
the occurrence of one or the other separator and run split() with the correct 
separator. If both can occur in the same line, you may want to use the regex 
module instead: re.split()

hth,

  Evert

 
> I tried with that but it's working only for a numbers less than 10 ex. 1,2,3 
> or 1 2 3 but it's not when I go for numbers higher than 10 like in example 
> above.
>  
> a=raw_input("Enter the number of your class in the school:")
> m=[]
>  for I range (len( a)):
> if a[I]==',':
> pass
> elif a[I]==' ':
> pass
> else:
> m.append(a[I])
> m=map(float,m)
> print m;print len( m )
> >> [1,2,3]
> >> 3
>  
> looking forward to seeing your help,
> regards,
> Ahmed
>  
>  
>  
> ___
> 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] Tutor Digest, Vol 79, Issue 134

2010-09-25 Thread Evert Rol
> I started seting up django. the only issue I am having is that all 
> instructions seem to assume that I am on linux.Don't suppose there are any 
> good instructions for those on a windows based system.

Firstly: please don't reply to an unrelated message, but start a new one (with 
a proper subject line). Especially a reply to a digest message contains a lot 
of unrelated info.
Secondly: there is a Django mailing list, which may be more helpful than a 
generic Python tutoring list.

That said: what's wrong with the Django installation notes: I see mentions of 
Windows there, not just Linux; does that not work? 
http://docs.djangoproject.com/en/1.2/topics/install/
Googling 'django windows install' also works. Eg, http://www.instantdjango.com/

Cheers,

  Evert

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


Re: [Tutor] input and raw input

2010-09-25 Thread Evert Rol
> > any one have an idea about how we can input many number in the one time and 
> > change it to list.
> > for example:
> >
> > a=input("Enter the number of your class in the school:") # the number 
> > can be enter as: 12,13,14 or 12 13 14 with a space in between.
> >
> > now how I can put these numbers into list like b=[12,13,14] with len( a ) =3
> 
> A string has a method split(); that may help you.
> In your case, where you want either a space or a comma as a separator, it 
> depends whether both can be used at the same time. If not, you can check for 
> the occurrence of one or the other separator and run split() with the correct 
> separator. If both can occur in the same line, you may want to use the regex 
> module instead: re.split()
> 
> No need for the 're' module. Even in the case where both can be used 
> together, you can still just use string methods: 
> 
> >>> s
> '12, 13 14'
> >>> s.replace(',', '').split(' ')
> ['12', '13', '14']

Good point.
To be finicky, you'll probably want to replace ',' by ' ' and let split work on 
whitespace instead of a single space. In case of tabs or a 12,13,14 input.


> > I tried with that but it's working only for a numbers less than 10 ex. 
> > 1,2,3 or 1 2 3 but it's not when I go for numbers higher than 10 like in 
> > example above.
> >
> > a=raw_input("Enter the number of your class in the school:")
> > m=[]
> >  for I range (len( a)):
> > if a[I]==',':
> > pass
> > elif a[I]==' ':
> > pass
> > else:
> > m.append(a[I])
> > m=map(float,m)
> > print m;print len( m )
> > >> [1,2,3]
> > >> 3
> >
> > looking forward to seeing your help,
> > regards,
> > Ahmed
> >
> >
> >
> > ___
> > 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
> 
> 
> 
> -- 
> Brian K. Jones
> My Blog  http://www.protocolostomy.com
> Follow me  http://twitter.com/bkjones

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


Re: [Tutor] dynamic arrays?

2010-09-27 Thread Evert Rol
> One thing I have never much liked about Python is its need for
> specifically sized arrays and lack of a dynamic, array-like data
> structure. For example, the following fails with a "list assignment
> index out of range" error:
> 
> a=[]
> i=0
> for l in open("file.txt", "r"):
>  a[i]=l
>   i+=1

Hmm, what's wrong with append()?

a = []
for l in open("file.txt"):
  a.append(l)

Can't answer on the why, ie, why use append instead of a[i]. 
Then again, if you want that option, use a dictionary (probably bad idea here, 
but it works):

a = {}
i = 0
for l in open("file.txt"):
  a[i] = l
  i += 1

Cheers,

  Evert


> Is there something in Python I am missing that would let the above
> work? I am hoping that my annoyance at the apparent lack of such a
> thing is unfounded. BTW, I know why the above throws that exception.
> TIA.

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


Re: [Tutor] function with multiple checks

2010-09-27 Thread Evert Rol
> I've got a small function that I'm using to check whether a password is of a 
> certain length and contains mixed case, numbers and punctuation.
> 
> Originally I was using multiple "if re.search" for the patterns but it looked 
> terrible so I've read up on list comprehensions and it's slightly improved. I 
> just can't escape the feeling that there's a more elegant way to do this that 
> I'm missing.
> 
> I've been looking through all the python stuff that I thought might be 
> relevant (lambda, map, filter, set, frozenset, etc) but nothing has come 
> together. Just wondering if anyone has suggested reading material for 
> alternate ways they'd handle this code.

set does seem to have what you want: isdisjoint() could do the trick.
Eg:

if set(punctuation).isdisjoint(password) or 
set(digits).isdisjoint(password) or set(ascii_uppercase).isdisjoint(password) 
or set(ascii_lowercase).isdisjoint(password):
 return False
return True


You could even confuse yourself and put it all on one line:

  return not any(set(chars).isdisjoint(password) for chars in [punctuation, 
digits, ascii_uppercase, ascii_lowercase])

but I wouldn't recomended it. I guess this can even shortened further.
(note: the 'not' operator is needed, because isdisjoint returns True for what 
you probably prefer as False.)


  Evert


> CODE:
> 
> from string import ascii_lowercase, ascii_uppercase, digits, punctuation
> 
> 
> def complex_password(password):
>"""Checks password for sufficient complexity."""
>if len(password) < 12:
>return False
>if len([c for c in password if c in punctuation]) == 0:
>return False
>if len([c for c in password if c in digits]) == 0:
>return False
>if len([c for c in password if c in ascii_uppercase]) == 0:
>return False
>if len([c for c in password if c in ascii_lowercase]) == 0:
>return False
>return True
> ___
> 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] unittest testing order...

2010-09-27 Thread Evert Rol
>> List,
>> 
>> When using the unittest module, tests are run in alphanumeric order.
>> What's the suggested way of specifying a test order? 
> 
> There isn't one. It shouldn't matter what order the tests run, no test 
> should *rely* on another test. 
> 
> (Although of course, if one test fails, any tests which assume the 
> missing functionality will also fail.)

Steven is right that unittests should be independent. 

I did once, however, come across an option to order the tests. Scanning through 
the unittest docs, I found "sortTestMethodsUsing":

"Function to be used to compare method names when sorting them in 
getTestCaseNames() and all the loadTestsFrom*() methods. The default value is 
the built-in cmp() function; the attribute can also be set to None to disable 
the sort."

Perhaps that does what you want. But I would indeed not recommend it.

  Evert

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


Re: [Tutor] pyMVPA and OSError

2010-09-28 Thread Evert Rol
  Hi,

> I am very much new to python, and thus I am likely to feel stupid about 
> asking. But I need to get past this to continue with my work.
> I need pyMVPA module to run some analysis on fMRI data, but as a start I want 
> to at first play around with the sample data provided on pyMVPA website. I 
> have downloaded Python2.6, my operating system is Mac Leopard (i get a 
> depracation warning when I try to >>> import mvpa,

What depracation warning?


> which is not the problem, however, when I attempt to use the following line
> >>> import mvpa.suite as mvpa

I wouldn't do that; just seems prone to lead to confusion. Perhaps:
  >>> import mvpa.suite as mvpas
or
  >>> from mvpa import suite


> which i assume to mean the same thing,

It normally doesn't mean the same thing. mvpa and mvpa.suite would normally be 
quite different things. But perhaps this is how the package is setup; that 
would be in the manual.


More after the traceback.


> I dont get deprecation warning, but I do get a bunch of errors as follows:
> >>> import mvpa.suite as mvpa
> 
> Traceback (most recent call last):
>  File "", line 1, in 
>import mvpa.suite as mvpa
>  File 
> "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/suite.py",
>  line 38, in 
>from mvpa.algorithms.cvtranserror import *
>  File 
> "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/algorithms/cvtranserror.py",
>  line 15, in 
>from mvpa.measures.base import DatasetMeasure
>  File 
> "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/measures/base.py",
>  line 31, in 
>from mvpa.clfs.stats import autoNullDist
>  File 
> "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/clfs/stats.py",
>  line 772, in 
>if externals.exists('pylab'):
>  File 
> "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/base/externals.py",
>  line 432, in exists
>exec _KNOWN[dep]
>  File "", line 1, in 
>  File 
> "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/base/externals.py",
>  line 249, in __check_pylab
>import pylab as P
>  File 
> "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pylab.py",
>  line 1, in 
>from matplotlib.pylab import *
>  File 
> "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/pylab.py",
>  line 206, in 
>from matplotlib import mpl  # pulls in most modules
>  File 
> "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/mpl.py",
>  line 2, in 
>from matplotlib import axis
>  File 
> "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/axis.py",
>  line 10, in 
>import matplotlib.font_manager as font_manager
>  File 
> "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/font_manager.py",
>  line 1297, in 
>_rebuild()
>  File 
> "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/font_manager.py",
>  line 1288, in _rebuild
>fontManager = FontManager()
>  File 
> "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/font_manager.py",
>  line 980, in __init__
>self.ttffiles = findSystemFonts(paths) + findSystemFonts()
>  File 
> "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/font_manager.py",
>  line 337, in findSystemFonts
>for f in get_fontconfig_fonts(fontext):
>  File 
> "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/font_manager.py",
>  line 298, in get_fontconfig_fonts
>pipe = subprocess.Popen(['fc-list', '', 'file'], stdout=subprocess.PIPE)


At first read, it looks like mvpa is checking for external dependencies, 
including checking for fonts to be used by matplotlib (or actually, matplotlib 
does this).
Matplotlib then tries to run an external process called 'fc-list', which 
presumably list the font-config fonts.
It looks like your system does not have this installed.

Since this is all installed through matplotlib, that would mean that somewhere 
there is a dependency check missing. 
For a start, you could try and reinstall matplotlib yourself, hoping this 
solves it. But I won't guarantee that.

Since this all done through macports, I wonder what your python is: did you 
install that through matplotlib as well, or are you using a different (system) 
python?
You mention you downloaded Python 2.6, which would suggest you're not using 
macports python, which may cause these errors as well.
In addition, if you are on Snow Leopard (not plain Leopard), you should have 
Python 2.6 as the system python, which would

Re: [Tutor] function error

2010-09-28 Thread Evert Rol
>> It seems that ur turtle.position doesn't return a list because of this when
>> indexing is done on that u get this kind of error.
>> --nitin
> 
> it seemed to me that kind of error but then i found that it was a
> list, as expected:
> 
> $  type(turtle.position())
> $ 
> $ abs(turtle.position()[0])
>   13.858469413370102
> 
> that's why i'm going crazy ...

Perhaps if you provide the full traceback from the error (assuming you're still 
getting this error); tracebacks generally show the offending code as well. It 
may be something that's simply overlooked but shows in the traceback.



>> On Tue, Sep 28, 2010 at 3:39 PM, Alan Gauld 
>> wrote:
>>> 
>>> "roberto"  wrote
>>> 
 i have the following error when i call this function:
  20 def outOfBounds():
 ---> 21 if abs(turtle.position()[0]) >
 turtle.window_height()/2 or abs(turtle.position()[1]) >
 turtle.window_width()/2:
22 return "true"
23 else:
 
 TypeError: 'function' object is unsubscriptable
 
 but i can't really figure out where is the problem with this function
 'unsubscriptable';
>>> 
>>> This means you are trying to use [] on a function.
>>> eg you might be doing turtle.position[1] instead of turtle.position()[1]
>>> 
>>> I can't see it in your code sample but I'd check carefully that your
>>> parens() all balance correctly and are in the right place...
>>> 
>>> 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
>> 
>> 
> 
> 
> 
> -- 
> roberto
> ___
> 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] Problems install Python

2010-09-29 Thread Evert Rol
> I had just download PeGreSQL, unzip and installed it, but I have a problem 
> such as:
> 
> phuong...@ubuntu:~/PyGreSQL-4.0$ python setup.py build
> sh: pg_config: not found
> Traceback (most recent call last):
>   File "setup.py", line 94, in 
> pg_include_dir = pg_config('includedir')
>   File "setup.py", line 56, in pg_config
> raise Exception("pg_config tool is not available.")
> Exception: pg_config tool is not available.
> 
> I do not know this errors. Could you help me, please? I can not install it 
> right now.

Have you installed Postgresql? You probaby need the development package for 
that.
Pygresql depends on Postgresql, and if you install from source as here, you 
probably need the Postgresql development stuff.

But since you're on Ubuntu, can't you just install Pygresql through a package 
manager? That would take care of everything.


  Evert

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


Re: [Tutor] function error

2010-09-29 Thread Evert Rol
>> Perhaps if you provide the full traceback from the error (assuming you're 
>> still getting this >error); tracebacks generally show the offending code as 
>> well. It may be something that's >simply overlooked but shows in the 
>> traceback.
>> 
>> 
> 
> here it is:
> 
> TypeError Traceback (most recent call last)
> 
> ~/randomMove2.py in ()
> > 1
>  2
>  3
>  4
>  5
> 
> ~/randomMove2.py in randomMove2(d1, d2, a1, a2)
>  6  while 1:
>  7  turtle.left(random.uniform(a1,a2))
> > 8  checkForward.checkForward(random.uniform(d1,d2))
>  9  if forward_failed == 'true':
> 10  turtle.right(180)
> 
> ~/checkForward.py in checkForward(distance)
>  8
>  9 turtle.forward(distance)
> ---> 10 forward_failed = outOfBounds()
> 11 turtle.setx(old_position[0]); turtle.sety(old_position[1])
> 12 turtle._pen.down()
> 
> ~/checkForward.py in out_of_bounds()
> 19
> 20 def outOfBounds():
> ---> 21 if (abs(turtle.position()[0]) >
> turtle.window_height()/2) or (abs(turtle.position()[1]) >
> turtle.window_width()/2):
> 22 return "true"
> 23 else:
> 
> TypeError: 'function' object is unsubscriptable


The only thing that strikes me as a bit odd, is that the last bit if given as 
'~/checkForward.py in out_of_bounds()', while the actual function seems to be 
called outOfBounds(). I don't know this traceback (ie, I can't tell what Python 
environment/editor you're using), but that could suggest the byte-compiled code 
you are running doesn't match with the actual current code. 
So you may have changed the function name in the meantime, *as well as* fixed a 
parenthesis in the process. But perhaps you haven't then recompiled your 
current code, and for some reason your Python executable hasn't picked up the 
most recent source code and recompiled that for you. 
If this is the case, it may be dependent on your development environment that 
does this (somewhat incorrectly, assuming you have at least saved the source 
file), but as I mentioned, I have no idea what you're using.

Then again, this is still a guess. But it's the only thing I can see that 
stands out.

Cheers,

  Evert

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


Re: [Tutor] inheritance problem

2010-09-30 Thread Evert Rol
  Hi Roelof,

> Im following this page : 
> http://openbookproject.net/thinkcs/python/english2e/ch17.html

I just checked this, and it appears you've copied this example fine.



> class Deck:
>def __init__(self):
>self.cards = []
>for suit in range(4):
>for rank in range(1, 14):
>self.cards.append(Card(suit, rank))
> 
>def deal(self, hands, num_cards=999):
>num_hands = len(hands)
>for i in range(num_cards):
>if self.is_empty(): break   # break if out of cards
>card = self.pop()   # take the top card
>hand = hands[i % num_hands] # whose turn is next?
>hand.add(card)  # add the card to the hand



> game = CardGame()
> hand = OldMaidHand("frank")
> deck = Deck()
> game.deck.deal([hand], 13)
> OldMaidHand.print_hands() 
> 
> But now Im getting this error message:
> 
> Traceback (most recent call last):
>  File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 126, in 
> 
>game.deck.deal([hand], 13)
>  File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 24, in deal
>card = self.pop()   # take the top card
> AttributeError: Deck instance has no attribute 'pop'
> 
> What went wrong here.

The error message tells you exactly what is wrong: there is no 'pop' attribute. 
Or in this case, rather there is no pop() method for the class Deck.
You're calling it as self.pop() within Deck, hence Deck should provide a pop 
method (the self refers to any instance of Deck that you're currently using). 
But pop() is nowhere defined...

Now, the commentary in the exercise says "a card is removed from the deck using 
the list method pop", which would suggest self is of type(list). Since self is 
also of type(Deck), Deck should inherit from list: class Deck(list).
Thus, in my view, the example is broken, and simply not well tested. Hence I 
said you copied it fine, and nothing went wrong there.

Seen the rest of the example, I actually suspect that inheriting from standard 
Python types is not yet discussed here, and will be done later. So inheriting 
from list is one option, but may not be right in the context of this exercise. 
Writing your own pop() method for Deck is another option.

And, since this is an openbookproject, I would expect that means you can edit 
it yourself. That doesn't appear to be directly the case, but you could at 
least notify the authors (bottom of page) and let them know that you think this 
example is broken (feel free to refer them to this thread in the mailing list). 
Unless of course, there was some example done before this chapter that provided 
a pop() method.

  Evert

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


Re: [Tutor] Networking

2010-10-02 Thread Evert Rol
> Dear Tutors,
> I have attached my 2 programs for networking. It uses socket and 
> SocketServer, but it just simplifies it even more. The problem is it won't 
> work. The Client raises the error, (with trace back)
> Traceback (most recent call last):
>   File "G:\My Dropbox\My Dropbox\Chris\Not done\client.py", line 34, in 
> 
> print client.recv()
>   File "G:\My Dropbox\My Dropbox\Chris\Not done\client.py", line 16, in recv
> return self.__sock.recv(1024)
> error: [Errno 10053] An established connection was aborted by the software in 
> your host machine
> The server seems to get an error of some sort, but also seems to catch and 
> print it. It prints
> 
> Exception happened during processing of request from ('127.0.0.1', 1424)
> Traceback (most recent call last):
>   File "C:\Python26\lib\SocketServer.py", line 281, in _handle_request_noblock
> self.process_request(request, client_address)
>   File "C:\Python26\lib\SocketServer.py", line 307, in process_request
> self.finish_request(request, client_address)
>   File "C:\Python26\lib\SocketServer.py", line 320, in finish_request
> self.RequestHandlerClass(request, client_address, self)
> TypeError: 'NoneType' object is not callable
> 
> I look at both of the documentations of socket and SocketServer, but I 
> couldn't firgue it out. I don't know much about networking. Please Help

I don't know much about networking, less so about it on Windows; also, I've 
only scanned quickly through the server script, but I notice your 
create_handler() function doesn't return anything. I guess it needs to return 
the Handler class.
The example in the Python docs doesn't use a factory function, but instead 
directly puts the class as the second argument to TCPServer. 
So the second argument needs to be a class, but since your create_handler() 
function returns nothing, you presumably get this NoneType exception.

  Evert

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


Re: [Tutor] specifying precision with scientific notation

2010-10-05 Thread Evert Rol
> I want to print scientific numbers with a specified number of decimal places. 
>  However, I want the number printed to be dynamically determined by the data. 
>  Example:
> 
>> a = 0.00762921383941
>> ea = 0.000830132912068
>> a / ea
> 9.190352205653852
> 
> By default, I will print the uncertainty ("ea") with two significant digits.  
> In this example, the central value is about 10 times larger than the 
> uncertainty, so I want to print it with 3 significant figures.

Note that 'specified number of decimal places' != 'number of significant 
digits'. But it's fairly obvious you mean significant digits here.
But that aside, perhaps Python's decimal module can help you to ease things: 
http://docs.python.org/library/decimal.html


>  So I want to do something like
> 
>> p = int(("%.1e" % (a / ea)).split('e')[-1]) # grab the power in the 
>> scientific notation (is there a better way?)
>> if p >= 0:
>>  print('%.' + str(int(2+p)) +'e +- %.1e' % (a, ea))
>> else:
>   print('%.2e +- %.1e' % (a, ea))
> 
> (desired output): 7.63e-03 +- 8.3e-04

Personally, I would print this as 7.63e-03 +- 0.83e-03, which shows the 
precision a bit better. But that's just a matter of aesthetics, and would make 
things even more complicated (then again, since you are printing numbers and 
formatting them, you are concerned about aesthetics).

But if the decimal module can't make it easier for you, I don't really think 
there's an easy way of doing this. 
Though you may want to make things slightly more convenient by creating your 
own Float class (inheriting from float), or even a Value class that has a 
number and an error. Then override the the __str__ method and you should be 
done for any number you print, while all the other operations can work as float 
(for the first class at least), or similar to float (second class).

Cheers,

  Evert



> but this fails.  And I haven't figured out how to get this to work.  Seems 
> like it should be simple.
> 
> Any help?
> 
> 
> Thanks,
> 
> Andre

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


Re: [Tutor] pymssql and encoding

2010-10-07 Thread Evert Rol
> >>> print customerName
> ImmobiliŠre (whatever)
> >>> customerName
> 'Immobili\x8are (whatever)'
> 
> There should be a small E with a grave accent (è) instead of the capital S 
> with a caron (Š) I'm getting.
> 
> I've tried applying various encodings, but to no avail:
> 


> When executed from MS SQL Server's Management Studio, the same query returns 
> "Immobilière (whatever)", with an 'è', as it should.
> 
> The field in question is of type nvarchar, with collation 
> SQL_Latin1_General_CP850_CI_AS.

Well, you're SQL server seems to use CP850, which is (almost) the first 
encoding I tried:

>>> name= 'Immobili\x8are'
>>> name
'Immobili\x8are'
>>> print name.decode('cp850')
Immobilière
>>> 

Seems to work for me.

  Evert

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


Re: [Tutor] wrap methods for logging purposes

2010-10-07 Thread Evert Rol
> I used a the recipe (http://aspn.activestate.com/ASPN/Coo.../Recipe/198078)  
> used to wrap methods for logging purposes. logging classes. But it does seem 
> to work well with classes inherit form other classes -  i get recursion 
> errors!
> 
> Here is an example of the classes .. 
> 
> class Base(MetaClass):
> 
> class BFrame(BaseFrame):
> def __init__(self, pathname=''):
> Base.__init__(self, pathname = pathname)
> 
> When i instatiate BiasFrame()

Sorry, but I can't see how this code example above can work;
- there is no definition of class Base. There's not even 'pass' statement!
- Where is MetaClass's definition?
- you instantiate BiasFrame, but that's not defined.
- BFrame inherits from BaseFrame, which I don't see defined inherit.
- I definitely would advise against calling Base.__init__ if you inherit BFrame 
from BaseFrame: BaseFrame.__init__ makes more sense.
  But rather, use super instead. In Python 2:
super(Base, self).__init__(pathname=pathname)


  Evert


> 
> below is the  OUTPUT
> 
> logmethod  __init__ () {}
> logmethod  __init__ () {'pathname': ''}
> logmethod  __init__ () {'pathname': ''}
> logmethod  __init__ () {'pathname': ''}
> logmethod  __init__ () {'pathname': ''}
> .
> .
> RuntimeError: maximum recursion depth exceeded in cmp
> 
> It starts with the __init__ of BFrame, that's correct. In the __init__ of 
> BFrame is a call to Base.__init__ with the pathname as argument. That is the 
> second call to __init__ in the output, but the class is wrong ! Instead of 
> the __init__ of Base the __init__ of BFrame is called.
> 
> is there any way i can correct this?
> 
> -- 
> += Johnson
> -- 
> ___
> 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] Non-ASCII

2010-10-07 Thread Evert Rol
> I'm going through an online tutorial for Jython (www.jython.org). I can't 
> find a place to ask a question on that site so I thought I'd try here. I 
> believe the code is supposed to traverse a directory, identifying file types. 
> The script is failing with the following message:
> 
>  File "", line None
> SyntaxError: Non-ASCII character in file 
> 'H:\workspace\test\src\root\nested\example.py', but no encoding declared; see 
> http://www.python.org/peps/pep-0263.html for details

Normally, this (obviously) means you have some non-ASCII characters (accented 
characters would already do this) in your source code. Since this is just a 
byte code at the lowest level, it needs to be decoded into something sensible, 
which you specify using an encoding. Since Python refuses to guess which 
encoding you want to use (the same character code could result in totally 
different characters for different encodings), it's bailing out instead of 
continuing (the exception being that by default, the Python interpreter assumes 
your encoding is ASCII, and happily proceeds with that until it comes across a 
character code outside the ASCII range).

In your code below, however, I don't see any non-ASCII characters. So my best 
guess is that there is some invisible control-character outside the ASCII range 
that's causing this error message. 
This could happen because of a particular type of text-editor/IDE you're using.

The odd thing I find about the SyntaxError is actually that there is no line 
number mentioned. In fact, 'File "", line None' is a very weird 
indication for telling where the error occurred. Might again be something to do 
with your IDE.

I've tried your code by simply copy-pasting, and that works fine for me. So the 
control-character didn't reach my mail program. In which case you could try to 
copy-past the code from this reply into a new file and see if that's gotten rid 
of the control-character (presuming that caused the problem).

Of course, if it's eg a known problem in Jython, I can't really tell you, 
because I simply don't know Jython. But try clean code for a start.

HTH,

  Evert


> 
> Thank you,
> Shawn
> 
> 

import os, sys 
from stat import *

def walktree(top, callback):
   '''recursively descend the directory tree rooted at top,
   calling the callback function for each regular file'''
   for f in os.listdir(top):
   pathname = os.path.join(top, f) 
   mode = os.stat(pathname)[ST_MODE] 
   if S_ISDIR(mode):
   # It's a directory, recurse into it 
   walktree(pathname, callback)
   elif S_ISREG(mode):
   # It's a file, call the callback function 
   callback(pathname)
   else:
   # Unknown file type, print a message 
   print 'Skipping %s' % pathname

def visitfile(file):
   print 'visiting', file

if __name__ == '__main__':
   walktree(sys.argv[1], visitfile)

> 
> ___
> 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] Rounding a Python float to the nearest half integer

2010-10-08 Thread Evert Rol
> I realise that one cannot have a half integer :) I meant how would one round 
> off to the first decimal nearest to either 0.5, or a whole number.
> 
> Ugh...does anyone get what I'm trying to articulate? :)

Multiply by 2, round(), divide by 2?


> 
> On Fri, Oct 8, 2010 at 2:51 PM, Sithembewena Lloyd Dube  
> wrote:
> Hi folks,
> 
> Supposing I had the float 4.4348 and I wished to round it off to the nearest 
> half-integer upwards or downwards, how would I go about it?
> 
> Many thanks...
> 
> --
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Rounding a Python float to the nearest half integer

2010-10-08 Thread Evert Rol
> @Evert, I didn't figure out that your response was a solution, thought it was 
> a question. Must be coffee time :P
> 
> I tried it and, for instance, the rounded value (9) / 2 gave me 4.0 Couldn't 
> get it until I noticed that @Joel divided the roudned figure by a decimal 
> 2.0. That gave 4.5, which is what I was looking for.

How do you get a rounded value of 9 (integer)? Round() returns a float, afaik; 
ie, you wouldn't the the 2.0, but just 2. (In fact, your return value is 4.0, 
which for integer division wouldn't work. So something was odd there, but I 
can't think of what.)

Also, perhaps better to use
from __future__ import division
to prevent these mistakes.

Cheers,

  Evert


> > I realise that one cannot have a half integer :) I meant how would one 
> > round off to the first decimal nearest to either 0.5, or a whole number.
> >
> > Ugh...does anyone get what I'm trying to articulate? :)
> 
> Multiply by 2, round(), divide by 2?
> 
> That sounds like a good idea: 
> 
> >>> n = [1.0 + x/10.0 for x in range(10)]  # get some numbers to test
> >>> n
> [1.0, 1.1001, 1.2, 1.3, 1.3999, 1.5, 
> 1.6001, 1.7, 1.8, 1.8999]
> >>> r = [round(2*x)/2.0 for x in n]   # double, round, then divide by 2.0
> >>> r
> [1.0, 1.0, 1.0, 1.5, 1.5, 1.5, 1.5, 1.5, 2.0, 2.0]
> >>> 
> 
> 
> -- 
> Joel Goldstick
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> 
> 
> -- 
> Regards,
> Sithembewena Lloyd Dube
> http://www.lloyddube.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


Re: [Tutor] OpenMP

2010-10-09 Thread Evert Rol
> Hi,
> I have searched about how to use openMP using python and I couldn't fine any 
> helpful info. anyone can help me on this.

No openMP, but iPython could do what you want (parallel and some distributed 
computing): http://ipython.scipy.org/doc/stable/html/

  Evert


>  
> My idea is that to use the different processer core for each section.
> for ex.
> lets say I have two loops and I want to test in which processer go through.
> ## core one should handle this
> a=[]
> for I in range (100):
>s= 10*I
>a.append( s)
>  
> ## core two should handle this
> b=[]
> for f in range (100):
>h= 10*f
>b.append( h)
>  
> ## collecting the data in one data file 
> data=[a, b]
>  
> my question is how to do that and is it possible in python to go from line to 
> line after give the order to core one to process than we go to next core for 
> the second process..
>  
> Really interesting to speed up the process based on no of CPUs that we have 
> using python.
> Looking forward to seeing your suggestions,
> Best regards,
> Ahmed
> ___
> 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] Multiple regex replacements, lists and for.

2010-10-12 Thread Evert Rol
> I'm new to python and inexperienced in programming but I'm trying hard.
> I have a shell script that I'm converting over to python.
> Part of the script replaces some lines of text.
> I can do this in python, and get the output I want, but so far only using sed.
> Here's an example script:
> 
> import subprocess, re
> list = ['Apples   the color red', 'Skyi am the blue color', 'Grass
> the
> colour green is here', 'Sky   i am the blue color']
> 
> def oldway():
>   sed_replacements = """
> s/\(^\w*\).*red/\\1:RED/
> s/\(^\w*\).*blue.*/\\1:BLUE/"""
>   sed = subprocess.Popen(['sed', sed_replacements],
> stdin=subprocess.PIPE, stdout=subprocess.PIPE)
>   data = sed.communicate("\n".join(list))[:-1]
>   for x in data:
>   print x
> oldway();
> 
> """ This produces:
> 
 Apples:RED
 Sky:BLUE
 Grass  the colour green is here
 Sky:BLUE
> 
> Which is what I want"""
> 
> print "---"
> 
> def withoutsed():
>   replacements = [
> (r'.*red', 'RED'),
> (r'.*blue.*', 'BLUE')]
>   for z in list:
>   for x,y in replacements:
>   if re.match(x, z):
>   print re.sub(x,y,z)
>   break
>   else:
>   print z
> withoutsed();
> 
> """ Produces:
> 
 RED
 Skyi am the blue color
 BLUE
 Grass  the colour green is here
 Grass  the colour green is here
 Skyi am the blue color
 BLUE
> 
> Duplicate printing + other mess = I went wrong"""
> 
> I understand that it's doing what I tell it to, and that my for and if
> statements are wrong.


You should make your Python regex more like sed. re.sub() always returns a 
string, either changed or unchanged. So you can "pipe" the two necessary 
re.sub() onto each other, like you do for sed: re.sub(replacement, replacement, 
re.sub(replacement, replacement, string). That removes the inner for loop, 
because you can do all the replacements in one go.
re.sub() will return the original string if there was no replacement (again 
like sed), so you can remove the if-statement with the re.match: re.sub() will 
leave the 'Grass' sentence untouched, but still print it.
Lastly, in your sed expression, you're catching the first non-whitespace 
characters and substitute them in the replacements, but you don't do in 
re.sub(). Again, this is practically the same format, the only difference being 
that in Python regexes, you don't need to escape the grouping parentheses.

I can give you the full solution, but I hope this is pointer in the right 
direction is good enough. All in all, your code can be as efficient in Python 
as in sed.

Cheers,

  Evert


Oh, btw: semi-colons at the end of a statement in Python are allowed, but 
redundant, and look kind of, well, wrong.


> What I want to do is replace matching lines and print them, and also
> print the non-matching lines.
> Can somebody please point me in the right direction?
> 
> Any other python pointers or help much appreciated,
> 
> Will.
> ___
> 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] urllib problem

2010-10-12 Thread Evert Rol
> I have this program :
> 
> import urllib
> import re
> f = 
> urllib.urlopen("http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=6";)
> inhoud = f.read()
> f.close()
> nummer = re.search('[0-9]', inhoud)
> volgende = int(nummer.group())
> teller = 1 
> while teller <= 3 :
>  url = "http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing="; + 
> str(volgende)
>  f = urllib.urlopen(url)
>  inhoud = f.read()
>  f.close()
>  nummer = re.search('[0-9]', inhoud)
>  print "nummer is", nummer.group()
>  volgende = int(nummer.group())
>  print volgende
>  teller = teller + 1
> 
> but now the url changes but volgende not.

I think number will change; *unless* you happen to retrieve the same number 
every time, even when you access a different url.
What is the result when you run this program, ie, the output of your print 
statements (then, also, print url)?
And, how can url change, but volgende not? Since url depends on volgende.

Btw, it may be better to use parentheses in your regular expression to 
explicitly group whatever you want to match, though the above will work (since 
it groups the whole match). But Python has this "Explicit is better than 
implicit" thing.

Cheers,

  Evert

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


Re: [Tutor] Writing elements of an array to a file using CSV module

2010-10-14 Thread Evert Rol
> I have a numpy array ('data') that is the result of reading a netCDF
> file, and it typically looks like this:
> 
> array([ 0.,  0.,  0.,  0.], dtype=float32)
> 
> 
> I want to write this, after a date and time, to a CSV file, so the CSV
> file would have the entry:
> 
>2000-02-01,09:00,0.0,0.0,0.0,0.0
> 
> 
> The code I'm using to test it, is:
> 
> # file_details[0] is the date and file_details[1] is the time
> writer.writerow(('%s' % (file_details[0]),'%s' %
> (file_details[1]),'%f' % (data[0])))
> 
> 
> In my opinion, this should give an output line:
> 
> 2000-02-01,09:00,0.0
> 
> 
> Instead, I get an error
> 
> TypeError: float argument required, not numpy.ndarray
> 
> 
> 
> Can someone please explain to me why data[0] is giving a numpy array
> rather than one element? I don't understand it, since I get:
> 
 data[0]
> 0.0

This means very little, since a string '0.0' will show the same output when 
printed:
>>> print '0.0'
0.0

The exception says 'TypeError', so try:

>>> type(data[0])


Which is indeed what you specified at the start using dtype=float32.

The standard string formatting doesn't know what to do with a numpy.float32, so 
you'll need to convert it to a float:

>>> '%f' % float(data[0])
'0.00'

(use proper float formatting to get at '0.0', which is what you apparently 
want.)


  Evert

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


Re: [Tutor] Writing elements of an array to a file using CSV module

2010-10-14 Thread Evert Rol
> Thanks for the reply. I've tried your suggestion and am still getting
> an error (posted below code). Since my posting, I've also added the
> code to convert the numpy array to a list. My complete script is:
> 
> -
> # -*- coding: utf-8 -*-
> 
> import pupynere
> import os
> import csv
> import glob
> 
> def get_file_details(filename):
>sub1='3B42.'
>sub2='.nc'
>extract=filename.split(sub1)[-1].split(sub2)[0]
>elements=extract.split('.')
>ure={'0':'00:00:00',
> '3':'03:00:00',
> '6':'06:00:00',
> '9':'09:00:00',
> '12':'12:00:00',
> '15':'15:00:00',
> '18':'18:00:00',
> '21':'21:00:00'}
>date='20'+elements[0]
>time=ure[elements[1]]
>return[date,time]
> 
> def get_rain_data(filename):
># trmm blocks covering study area
>rows=[87,86,85,86]
>cols=[833,833,833,834]
> 
># open file
>file = pupynere.netcdf_file(filename,'r')
># read data
>precipitation=file.variables['precipitation']
># close filefile.close()
> 
># read values for blocks of interest
>precip=precipitation[rows,cols]
># convert numpy array to list
>precip=precip.tolist()
>return[precip]

You just converted precip to a list (precip.tolist()), then, in the next line, 
you're turning that into a list.
So you get a list within a list, which results in the errors below. Exactly as 
you hinted at yourself below.

(In fact, if you now would do
>>> data[0]
[0.0, 0.0, 0.0, 0.0]
because this is the representation (repr). Not the 0.0 you previously showed.)

Once you get rid of the extra list, you can use either float(data[0]) and %f 
(if you require detailed formatting) or just simply %s, as Alan suggested.

  Evert



> 
> 
> # get list of .nc files in folder
> os.chdir('F:\\Hanlie\\UCT\\M.Sc\\Data\\TRMM\\2000\\02_Februarie')
> filepattern='*.nc'
> nc_files=glob.glob(filepattern)
> 
> # write to CSV-file with spaces as delimiter
> csv.register_dialect('spaces', delimiter=' ')
> outfilename="trmm_c83a_feb2000.txt"
> out_text=open(outfilename, 'wb')
> writer = csv.writer(out_text,dialect='spaces')
> 
> for file in nc_files:
>file_details=get_file_details(file)
>data=get_rain_data(file)
>writer.writerow(('%s' % (file_details[0]),'%s' %
> (file_details[1]),'%f' % float(data[0])))
> 
> out_text.close()
> -
> 
> I now get the error:
> -
> Traceback (most recent call last):
>  File 
> "F:\Hanlie\UCT\M.Sc\Data\TRMM\lees_netcdf_per_trmm_blok_skryf_vir_pcraster.py",
> line 76, in 
>writer.writerow(('%s' % (file_details[0]),'%s' %
> (file_details[1]),'%f' % float(data[0])))
> TypeError: float() argument must be a string or a number
> -
> 
> I tried the other suggestion on the list (posted by Alan Gould),
> namely to replace the %f formatting string with %s in the
> write.writerow statement:
> -
> writer.writerow( ( file_details[0], file_details[1], str(data[0])  ) )
> -
> 
> This produces a file with lines such as:
> -
> 2201 00:00:00 "[0.0, 0.0, 0.0, 0.0]"
> -
> 
> I seem to have a list within a list, I'm not sure why. I could write
> the list elements to variables before I write to the file, but it
> doesn't seem like a very elegant solution.
> 
> Can anyone see why I have such a nested data structure? Or is the
> problem something completely different?
> 
> Thanks
> Hanlie
> 
> 
> 2010/10/14, Evert Rol :
>>> I have a numpy array ('data') that is the result of reading a netCDF
>>> file, and it typically looks like this:
>>> 
>>> array([ 0.,  0.,  0.,  0.], dtype=float32)
>>> 
>>> 
>>> I want to write this, after a date and time, to a CSV file, so the CSV
>>> file would have the entry:
>>> 
>>>   2000-02-01,09:00,0.0,0.0,0.0,0.0
>>> 
>>> 
>>> The code I'm using to test it, is:
>>> 
>>> # file_details[0] is the date and file_details[1] is the time
>>> writer.writerow(('%s' % (file_details[0]),'%s' %
>>> (file_details[1]),'%f' % (data[0])))
>>> 
>>> 
>>> In my opinion, this should give an output line:
>>> 
>>> 2000-02-01,09:00,0.0
&

Re: [Tutor] Networking

2010-10-14 Thread Evert Rol
 Hi Chris,

Bit hard to comment on the actual code, as it was in attachments, but the 
important bit is here:

class Handler(SocketServer.BaseRequestHandler): #the handler
'''A handler which calls %s in the handle method.'''%handle_func
def handle(self): #the handle method
self.data = self.request.recv(1024) #the data
self.client = self.request #the client
handle_func(self) #call the handle method giving self


(I did a bit of reformatting, since I had to try the code myself, because I 
didn't spot the error immediately.)

In essence, your server accepts the client connection, then proceeds to the 
handle function, where it performs the necessary actions. It will *not* call 
the handle function for each set of data it receives, it just stays there. 
So you'll need a while loop in your handle function that keeps on processing 
the client data, until there is not client data anymore (EOF or similar), then 
return.


  Evert



 Dear Tutors, 
  I have attached my 2 programs for networking. It uses socket and 
 SocketServer, but it just simplifies it even more. The problem is it won't 
 work. The Client raises the error, (with trace back) 
 Traceback (most recent call last): 
File "G:\My Dropbox\My Dropbox\Chris\Not done\client.py", line 34, 
 in 
  print client.recv() 
File "G:\My Dropbox\My Dropbox\Chris\Not done\client.py", line 16, in 
 recv 
  return self.__sock.recv(1024) 
 error: [Errno 10053] An established connection was aborted by the software 
 in your host machine 
 The server seems to get an error of some sort, but also seems to catch and 
 print it. It prints 
  
 Exception happened during processing of request from ('127.0.0.1', 1424) 
 Traceback (most recent call last): 
File "C:\Python26\lib\SocketServer.py", line 281, in 
 _handle_request_noblock 
  self.process_request(request, client_address) 
File "C:\Python26\lib\SocketServer.py", line 307, in process_request 
  self.finish_request(request, client_address) 
File "C:\Python26\lib\SocketServer.py", line 320, in finish_request 
  self.RequestHandlerClass(request, client_address, self) 
 TypeError: 'NoneType' object is not callable 
  
 I look at both of the documentations of socket and SocketServer, but I 
 couldn't firgue it out. I don't know much about networking. Please Help 
>>> I don't know much about networking, less so about it on Windows; also, I've 
>>> only scanned quickly through the server script, but I notice your 
>>> create_handler() function doesn't return anything. I guess it needs to 
>>> return the Handler class. 
>>> The example in the Python docs doesn't use a factory function, but instead 
>>> directly puts the class as the second argument to TCPServer. 
>>> So the second argument needs to be a class, but since your create_handler() 
>>> function returns nothing, you presumably get this NoneType exception. 
>>> 
>>>Evert 
>>> 
>> Yeah, that could be a problem. It should return the class. 
> Now it won't send more than once. The Error the clients raises is:
> Traceback (most recent call last):
>   File "G:\My Dropbox\My Dropbox\Chris\Not done\client.py", line 34, in 
> 
> print client.recv()
>   File "G:\My Dropbox\My Dropbox\Chris\Not done\client.py", line 16, in recv
> return self.__sock.recv(1024)
> error: [Errno 10053] An established connection was aborted by the software in 
> your host machine
> The server is blissfully unaware of its crashing clients, and keeps on going 
> to help more clients to there dooms. The client can receive data multiple 
> times, but just can send twice. Please 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


Re: [Tutor] Networking

2010-10-14 Thread Evert Rol
>>> But what if I want it to serve one client, go to another and then go back.
>>> How does that work?
> 
> You do some I/O multi-plexing or multi-processing/threading.
> 
> You might want to do some reading on this.

The very last example on http://docs.python.org/library/socketserver.html may 
help you.
Or perhaps the asyncore/asynchat modules.

  Evert

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


Re: [Tutor] What's the best way to model an unfair coin?

2010-10-24 Thread Evert Rol
> What's the best way to model an unfair coin?
> 
> This is one way to do it, I suppose: Create a list containing only
> 'H's and 'T's. If you want the coin to have the probability of a head
> to be 6/11,
> 
> ['H', 'H', 'H', 'H', 'H', 'H', 'T', 'T', 'T', 'T', 'T']
> 
> is the list to use. Use random.choice on the list, for a 6/11 heads
> probability.
> 
> See .
> 
> That's the only way I can think of. But surely there's a better, more
> general solution. What if the probability I want is an irrational
> number, such as 1/e? Sure, I can calculate a fraction that's as close
> to that irrational number as I want, but..

My statistics might be too rusty to have this correct, but I would do something 
similar as you have now, just not for integer numbers.
Assuming you only want True or False, you can use a uniform distribution, 
through random.random(), and see if the result is lower or higher than your 
probability. 
Eg:

return random.random() < 1/e

or 

return random.random() < 6/11.

will return True or False with your specificied probability. 
Again, I just might be overlooking something in the statistics.

Cheers,

  Evert

Btw, to be pedantic, 1/e is not an irrational number, just a real number. i/e 
would be.


> 
> Am I missing something that's already there in Python 2.6 or 3.1 (the
> 2 I have)?
> 
> Dick Moores
> ___
> 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's the best way to model an unfair coin?

2010-10-24 Thread Evert Rol
> Btw, to be pedantic, 1/e is not an irrational number, just a real number. i/e 
> would be.

My bad: irrational != imaginary. And real = irrational.
Things are definitely a bit rusty...


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


Re: [Tutor] What's the best way to model an unfair coin?

2010-10-24 Thread Evert Rol
> Actually, I used the unfair coin model as the simplest example of the
> kind of thing I want to do -- which is to model the USD->Yen exchange
> rate. I want the next quote to vary in a controlled random way, by
> assigning probabilities to various possible changes in the rate. See
> . So I assign probability 1/40
> to a change of plus or minus .05; 3/40 to .04; 5/40 to .03, etc.
> 
> An analogy to this would be an unfair 6-sided die, with each side
> assigned probabilities slightly differing from 1/6 (but totaling 1, of
> course). I can't see off-hand how to apply the Evert-Steven-Alan
> solution to these, but is it possible? I'd just like a yes or no -- if
> yes, I'd like to try to work it out myself.

Yes, and in a very similar way.

Cheers,

  Evert

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


Re: [Tutor] possible to run a python script from non-cgi?

2010-10-30 Thread Evert Rol
> FYI: I am working in a linux environment with python 2.6.5
> am an experienced web developer with 8 years in python, but
> :) I have never tried this trick before:
> 
> I note that with the right .htaccess file, I can run a php file,
> from a non-cgi location.
> Example: On my machine, my wwwroot is at /home/http/, I have
> /home/http/php/test/index.php and I have run index.php as
> http://localhost/php/test/ (again with the correct .hataccess).
> 
> Is it possible to run a python script this way?

I wouldn't think so, because index.php is not run as a cgi-script. 
Whether Python will be interpreted correctly depends entirely on the 
configuration of your webserver, in particular whether you're using/loading the 
correct modules.
But if configured correctly, yes, you can 'run' Python scripts. Mod_wsgi 
arranges this for you, and this is generally how things like Django run.

But the easiest way to find out is to try it out, right?

I also guess this question might be better answered on the forum corresponding 
to your webserver (Apache?), since it appears to deal more with the server 
setup than actually with Python.

Those are my best guesses/ideas.

HTH,

  Evert

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


Re: [Tutor] scope, visibility?

2010-11-01 Thread Evert Rol
> Here is my main class:
> 
> class PenduGTK:
> 
> Inside the class is a method with a bit of code:
> 
> def masque(chaine,liInd=0):
> 
> i = 0
> lenght = len(chaine)
> 
> The offending line is the one with len(chaine)
> 
> Here are the error messages:
> 
>  penduGTK.py 
> Traceback (most recent call last):
>   File "/home/xxx/bin/penduGTK.py", line 23, in enter_callback
> self.lblMot.set_text(self.masque(self.motChoisi))
>   File "/home/xxx/bin/penduGTK.py", line 44, in masque
> lenght = len(chaine)
> AttributeError: PenduGTK instance has no attribute '__len__'

A method takes as its first argument a reference to the class. That is, in 'def 
some_method(blah1, blah2, blah3)', blah1 would be a reference to the class in 
which some_method is defined.
If you look at the error message, you see Python complains that the PenduGTK 
instance has no __len__ attribute, meaning 'chaine' is a PenduGTK instance: 
it's the first argument in the method, taking a reference to the class.
See eg http://diveintopython.org/object_oriented_framework/defining_classes.html
(also, carefully read the error and think what it could mean: it has a lot of 
hints to solve your problem).

Thus, define a method with an extra (first) argument. This is usually called 
self:

def masque(self, chaine, liInd=0):


Last note on a totally different thing, because this confused me a bit: 
preferably avoid avoid the lowercase L, lowercase i and uppercase I next to 
each other. It's very hard to read. See eg 
http://www.python.org/dev/peps/pep-0008/ (section 'Names to Avoid'). To me, it 
initially read something like iiind=0. Which is ok, as long as I don't have to 
work with the code. But it may also bite you some day.


> I would think it has to do with namespaces, scopes and visibility. But how do 
> I refer to built-in functions from inside a class?

Just as you did above: len(chaine). 
But since that wasn't your problem, I guess this answer is rather meaningless.

Cheers,

  Evert

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


Re: [Tutor] How to copy file from a source, I do not know the source file name, Only path to the src directory I know

2010-11-09 Thread Evert Rol
> Hi All
>   I am trying our "Python" .
>   My aim is to copy a file to a location and later removing the
> file.I had written a small script which works.It works only if I
> specify the source file name. I would like to make it work in a
> scenario in which I do not know the name of the source file(the source
> directory will have only one file at any time)

Have a look at the os module, specifically os.listdir()
The glob module could also be handy.

Cheers,

  Evert

> 
> I am posting the script which I have done,How to modify the script to
> copy the source file even if I do not know the name of the file
> my script is below
> 
> ###
> #!/usr/bin/python
> 
> # This script aims to copy file from one directoy to anothe and later
> removing the files
> # This script works when I know the source file name, I want to this
> script to function even if I do not know the name of
> # the file in "/home/joseph/Projects/Training/Python/example/One/"
> 
> import shutil
> # "FromOne" is a file in /home/joseph/Projects/Training/Python/example/One/
> src = "/home/joseph/Projects/Training/Python/example/One/FromOne"
> #
> dst2 = "/home/joseph/Projects/Training/Python/example/Two/"
> dst3 = "/home/joseph/Projects/Training/Python/example/Three/"
> #
> 
> #
> #shutil.move(src, dst)
> shutil.copy(src,dst2)
> shutil.move(src,dst3)
> 
> ##
> 
> 
> 
> 
> -- 
> Thanks
> Joseph John
> http://www.oss101.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


Re: [Tutor] How to copy file from a source, I do not know the source file name, Only path to the src directory I know

2010-11-09 Thread Evert Rol
> I was able to solve it
> by
> "
> dirList=os.listdir(src)
> for fname in dirList:
>   print fname
>   ffname = '/home/joseph/Projects/Training/Python/example/One/'+fname

tip: use os.path.join for concatenating paths. It's smart, and (in principle) 
OS-agnostic.

Also, if you use 'os.listdir(src)', why not use src again when assigning ffname?


Cheers,

  Evert

>   print ffname
>   #shutil.copy(ffname,dst2)
>   shutil.move(ffname,dst3)
> "
> 
> 
> On Tue, Nov 9, 2010 at 4:38 PM, Evert Rol  wrote:
>>> Hi All
>>>   I am trying our "Python" .
>>>   My aim is to copy a file to a location and later removing the
>>> file.I had written a small script which works.It works only if I
>>> specify the source file name. I would like to make it work in a
>>> scenario in which I do not know the name of the source file(the source
>>> directory will have only one file at any time)
>> 
>> Have a look at the os module, specifically os.listdir()
>> The glob module could also be handy.
>> 
>> Cheers,
>> 
>>  Evert
>> 
>>> 
>>> I am posting the script which I have done,How to modify the script to
>>> copy the source file even if I do not know the name of the file
>>> my script is below
>>> 
>>> ###
>>> #!/usr/bin/python
>>> 
>>> # This script aims to copy file from one directoy to anothe and later
>>> removing the files
>>> # This script works when I know the source file name, I want to this
>>> script to function even if I do not know the name of
>>> # the file in "/home/joseph/Projects/Training/Python/example/One/"
>>> 
>>> import shutil
>>> # "FromOne" is a file in /home/joseph/Projects/Training/Python/example/One/
>>> src = "/home/joseph/Projects/Training/Python/example/One/FromOne"
>>> #
>>> dst2 = "/home/joseph/Projects/Training/Python/example/Two/"
>>> dst3 = "/home/joseph/Projects/Training/Python/example/Three/"
>>> #
>>> 
>>> #
>>> #shutil.move(src, dst)
>>> shutil.copy(src,dst2)
>>> shutil.move(src,dst3)
>>> 
>>> ##
>>> 
>>> 
>>> 
>>> 
>>> --
>>> Thanks
>>> Joseph John
>>> http://www.oss101.com/
>>> ___
>>> Tutor maillist  -  Tutor@python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>> 
>> 
> 
> 
> 
> -- 
> Thanks
> Joseph John
> http://www.oss101.com/

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


  1   2   >