Re: [Tutor] Passing perimeters in dictionary values?

2009-02-27 Thread Richard Lovely
On 25/02/2009, Alan Gauld  wrote:
>
> "nathan virgil"  wrote
>
> > Whenever I try to use the talk method (which reports the mood, and doesn't
> > take parameters), it says I gave it too many parameters.
> >
>
> Sorry, I should have pointed out that you will need to redefine
> all your functions to accept a parameter.
>
> Alan G
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

Always makes me smile when (experienced) people redesign the wheel...

>From the docs (http://www.python.org/doc/2.6/library/functools.html):

"The partial() is used for partial function application which
“freezes” some portion of a function’s arguments and/or keywords
resulting in a new object with a simplified signature."

-- 
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Passing perimeters in dictionary values?

2009-03-01 Thread Richard Lovely
2009/2/28 Alan Gauld :
>
> "Richard Lovely"  wrote
>
>> > Sorry, I should have pointed out that you will need to redefine
>> > all your functions to accept a parameter.
>>
>> Always makes me smile when (experienced) people redesign the wheel...
>>
>> From the docs (http://www.python.org/doc/2.6/library/functools.html):
>>
>> "The partial() is used for partial function application which
>> “freezes” some portion of a function’s arguments and/or keywords
>> resulting in a new object with a simplified signature."
>
> I'm not sure how you would use partial in this case, I still think you'd
> need to add a parameter to the function definitions. partial would
> remove the need for lambda in some of the other solutions though.
>
> But an interesting module that I've not seen before. Although since it was
> only introduced in 2.5 I'm not surprised, I've been focussing more
> on v3 lately rather than the new stuff in 2.5/2.6 (in fact I don't even
> have 2.6 loaded yet and only have 2.5 on one PC...)
>
> Thanks for highlighting it.
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
> ___
> Tutor maillist  -  tu...@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

Ooops... quoted the wrong message.  That should have been quoting the
message about lambdas...

-- 
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] adding dictionary values

2009-03-20 Thread Richard Lovely
2009/3/20 Chris Fuller :
> You should iterate over the keys of the dictionary:
> for k in a.keys():
> because if you iterate over the full dictionary, your items are the values,
> not the keys.  Otherwise your code looks correct, and I don't think its
> terribly bad form.  You could do something interesting with sets:
> sa = set(a.keys())
> sb = set(b.keys())
>
> The next step could be a for loop, but if you enjoy terseness and taking
> advantage of language features (also should be faster for big enough dicts):
> c = dict( \
>   [(k, a[k]+b[k]) for k in sa&sb ] + \
>   [(k, a[k]) for k in sa-sb ] + \
>   [(k, b[k]) for k in sb-sa ]
> )
>
> which creates a new dict from a list of key, value pairs.  The list is a sum
> of three lists:  those keys in both a and b, those only in a, and those only
> in b.
>
> Cheers
>
> On Friday 20 March 2009 10:11, Emad Nawfal wrote:
>> Hi Tutors,
>> I have two pickled dictionaries containing word counts from two different
>> corpora. I need to add the values, so that a word count is the sum of both.
>> If the word "man" has a count of 2 in corpus A and a count of 3 in corpus
>> B, then I need a new dictionary that  has "man": 5. Please let me know
>> whether the following is correct/incorrect, good/bad, etc.
>> Your help appreciated:
>>
>> def addDicts(a, b):
>>     c = {}
>>     for k in a:
>>         if k not in b:
>>             c[k] = a[k]
>>         else:
>>             c[k] = a[k] + b[k]
>>
>>     for k in b:
>>         if k not in a:
>>             c[k] = b[k]
>>     return c
>>
>> # test this
>> dict1 = {"dad": 3, "man": 2}
>> dict2 = {"dad": 5, "woman": 10}
>> newDict = addDicts(dict1, dict2)
>> print(newDict)
>> # This gives
>>
>> {'dad': 8, 'woman': 10, 'man': 2}
> ___
> Tutor maillist  -  tu...@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

Just to add another tool to your toolbox, defaultdicts, available from
version 2.5, are good for word counts, and simplifies your function no
end:

from collections import defaultdict
def addDict(a, b):
newdict = defaultdict(int, a)
for k,v in b.iteritems():
newdict[k] += v
return newdict

you can chage the last line to "return dict(newdict)" if the returned
value MUST be a dict, but there is very little advantage to doing so
in properly written code.

Extra credit:
To do a word count with a defaultdict is simple:
wordcount = defaultdict(int)
for word in list_of_words:
wordcount[word] += 1

Look it up in the docs if you want details of defaultdict.
-- 
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] incrementing one minute

2009-03-30 Thread Richard Lovely
2009/3/30 pa yo :
> I need to add one minute to a string that has a date and a time in
> MMDDHHMM format.
> e.g:  200903281346 should become 200903281347
>
> the following script converts the string into time and adds one
> minute; but somehow I also add an hour and I don't understand why.
>
> 
>
> import time
>
> #set the initial time as a string and convert it into time format:
> fromtimestring = '200903281346'
> fromtimetime = time.strptime(fromtimestring, "%Y%m%d%H%M")
> #convert this time format into UNIX time (seconds since the start of UNIX 
> time):
> fromtimeseconds = time.mktime(fromtimetime)
> #add 60 seconds and reformat the result into the MMDDHHMM format
> totimeseconds = fromtimeseconds + 60
> totimetime = time.gmtime(totimeseconds)
> # convert the new time into a string:
> totimestring = time.strftime("%Y%m%d%H%M", totimetime)
>
> #print the results:
> print (fromtimestring)
> print (fromtimetime)
> print (totimetime)
> print (totimestring)
>
> 
>
> any help or suggestions would be much appreciated.
>
>
> Payo
> ___
> Tutor maillist  -  tu...@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

When does it add an hour?  Is it only on specific input strings, or is
it arbitrary?  If its the former, what input strings does it happen
on? Can you spot any pattern to the inputs that it occurs on?

It's possible that it's getting confused with dates either side of the
British Summertime change.

Also, your variable names are rather cryptic... you might consider
using studlyCapsWithCapitalInitialLetters or
underscores_between_words.

-- 
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: range() fractional increment

2009-04-01 Thread Richard Lovely
forgot to reply-all...

-- Forwarded message --
From: Richard Lovely 
Date: 1 Apr 2009 18:13
Subject: Re: [Tutor] range() fractional increment
To: Alan Gauld 


There's always the itertools solution:

import itertools
def rangeInThirds(start,end):
   for whole, frac in itertools.product(range(start,end), (0, 0.3, 0.6)):
   yield whole + frac

The simplist way is to use a list comprehension:
[whole + frac for whole in xrange(start, end) for frac in [0, 0.3, 0.6]]

Then you just need to turn the iterable (generator in the first case,
list in the second into your "array".

On 31/03/2009, Alan Gauld  wrote:
>
> "james carnell"  wrote
>
> > example:
> > x row = 25 : col = 10
> > x row = 26 : col = 10.3
> > x row = 27 : col = 10.6
> > 0x000 row = 28 : col = 11
> >
>
> > for col in range(10,12, 0.3): #<- Crash Bang doesn't work 0.3 = zero =
> infinite loop?
> >
>
> If you know the limits (rather than their being variables) you can do
>
> for n in range(100,120,3)
>n = n/10
>
> But if you have variable range limits then a generator
> or while loop are your best bets I think.
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/l2p/
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>


--
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com


-- 
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Suggestions for while loop

2009-05-10 Thread Richard Lovely
2009/5/11 David :
> Hi, I am going through Wesley Chun's book and this is Exercise 8-11;
> Write a program to ask the user to input a list of names, format "Last Name"
> "comma" "First Name". Write a function that manages the input so that
> when/if the user types in the names in the wrong format the error is
> corrected, and keep track of the number of errors. When done sort the list.
>
> Questions;
>
> This;
> answers = raw_input('Enter Name: ')
> index = answers.find(',')
>
> Does not seem to be a very good to me, how could I check for a comma between
> two words?

Look up string.split(), see what happens if the comma isn't in the
string you try to split.  You could also try the "in" operator.

>
> And This;
> try:
>    total_names = int(raw_input('Enter Total Number of Names: '))
> except ValueError:
>    print 'You must enter a number!'
>    total_names = int(raw_input('Enter Total Number of Names: '))
>
> Does not handle the second input for exceptions.

while True: # loop forever
try:
total_names = int(raw_input('Enter Total Number of Names: '))
except ValueError:
print 'You must enter a number!'
else:
# execution only gets to here if no exception occurred
break # exit the loop

You could do the same using a continue statement in the except:
clause, and break outside the entire structure.

total_names = -1 # set an invalid initial value
while not 0 < total_names < 50: # loop while total_names has an invalid value
try:
# If this excepts, total_names is not changed.
total_names = int(raw_input('Enter Total Number of Names: '))
# if total_names now has a valid value, the loop exits.
except ValueError:
print 'You must enter a number!' # loop continues.


-- 
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to control the not existent keys in a dict

2009-05-10 Thread Richard Lovely
2009/5/10 Emilio Casbas :
>
> Hello,
>
> I have some problems testing keys not existent in a dictionary.
> The code works testing existent keys with his corresponding value, but
> If I enter a not existent key, an exception is raised.
> How can I control the not existent key and assign him a default value?
>
> u...@cipher:~/project/programming/python$ python3.0 test.py
> ¿What is your name? KEY-NOT-EXISTENT
> Good Morning KEY-NOT-EXISTENT
> ¿Which is the secret word? any
> Traceback (most recent call last):
>  File "test.py", line 30, in 
>    while not correct_password(name,guess,dictionary):
>  File "test.py", line 8, in correct_password
>    if (is_in_dict and password == dict[nombre.capitalize()]):
> KeyError: 'KEY-NOT-EXISTENT'
>
> -relevant code snippet-
> dictionary = {'Mark': 'python', 'Dave': 'java', 'Ane': 'C++', 
> 'default':'pass'}
>
> def correct_password(name,password,dict):
>        if (not is_in_dict and password == dict['default']):
>                return 1
>        elif (is_in_dict and password == dict[nombre.capitalize()]):
>                return 1
>        return 0
>
> def is_in_dict(nom,dict):
>        for n in dict:
>                if nom.lower() == n.lower():
>                        return 1
>        return 0
> -end relevant code snippet-
>
> Regards
>
>
>
>
> ___
> Tutor maillist  -  tu...@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

There's also collections.defaultdict, which you can initialise with a
"default value factory" which will generate a value for every attempt
to get a non-existent key.  It can be a lot of fun with a bit of
thought.


-- 
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] converting xls to csv

2009-05-31 Thread Richard Lovely
2009/5/31 Nick Burgess :
> Got it.
>
> the row is not a string or buffer but the cell is..
>
> for row in spamReader:
>    for cell in row:
>        if pattern.search(cell):
>            print ', '.join(row)
>
>
Alternatively, if you know that the string you want to search for only
appears in a single cell from the row, you could use

for row in spamReader:
   if pattern.search(cell[coll_number_here]):
   print ', '.join(row)

If there is a range of adjacent cells that could contain the text, you
could try something like
if pattern.search('|'.join(row[3:5])

For non-adjacent cells, try something like

targetCells = [1,3,5]
for row in spamReader:
   if pattern.search('|'.join(row[i] for i in targetCells))

Both of these solutions will be faster than iterating over th entire
row, unless tht is specifically what you want.
-- 
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] string pickling and sqlite blob'ing

2009-06-24 Thread Richard Lovely
2009/6/24 Dinesh B Vadhia :
> Hi Vince
>
> That's terrific!  Once a string is compressed with gzip.zlib does it make a
> difference whether it is stored it in a TEXT or BLOB column?
>
> Dinesh
>
>
>From the MySQL language reference:
"""A BLOB is a binary large object that can hold a variable amount of
data. The four BLOB types TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB
differ only in the maximum length of the values they can hold.

The four TEXT types TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT
correspond to the four BLOB types and have the same maximum lengths
and storage requirements. The only difference between BLOB and TEXT
types is that sorting and comparison is performed in case-sensitive
fashion for BLOB values and case-insensitive fashion for TEXT values.
In other words, a TEXT is a case-insensitive BLOB."""

gzip.zlib outputs binary data, so you should use BLOB.
Pickle, I believe, outputs an ascii string, so should use TEXT.

Hope that makes it a bit clearer.
-- 
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Problems with parameter queries

2009-06-24 Thread Richard Lovely
(oops... forgot to reply-all)


-- Forwarded message --
From: Richard Lovely 
Date: 2009/6/25
Subject: Re: [Tutor] Problems with parameter queries
To: Eduardo Vieira 


2009/6/24 Eduardo Vieira :
> Hello, I am accessing a Pervasive SQL data source using odbc and I'm
> having this trouble:
>
> import dbi
> import odbc
>  # the first execute works
> pnumber = '09F153'
> wh = '00'
> qty = 3
> myconn = odbc.odbc('DSN=MKPT01')
> mycursor = myconn.cursor()
> mycursor.execute("""
> SELECT "INVENTORY"."CODE", "INVENTORY"."INV_DESCRIPTION" FROM "INVENTORY"
> WHERE "INVENTORY"."CODE" = ? AND WHSE = ?
>
> """, [pnumber, wh])
> results = mycursor.fetchall()
>
> print results
>
> # this one below doesn't
>
> mycursor.execute("""UPDATE INVENTORY SET ONHAND = ?
> WHERE CODE = ? AND WHSE = '00'
>
> """, [pnumber, qty])
> #mycursor.commit()
> mycursor.close()
>
> If I don't use parameter in the update code, it updates fine. Am I
> missing something? Is this a problem specific to the Pervasive SQL?
> For example, this works:
> mycursor.execute("""UPDATE INVENTORY SET ONHAND='0'
> WHERE CODE = '09F153' AND WHSE = '00'
>
> """)
>
> Thanks
>
> Eduardo
> ___
> Tutor maillist  -  tu...@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

Isn't the arguement list to the non-working query back-to-front?

--
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com



-- 
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] string pickling and sqlite blob'ing

2009-06-25 Thread Richard Lovely
2009/6/25 Lie Ryan :
>
> Although pickle output only ascii string, it is not meant to be human
> readable at all. Basically there is no difference how it is stored as
> long as what goes in is equal with what goes out. I can't think of a
> need to sort or compare raw pickle data.
>
> ___
> Tutor maillist  -  tu...@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

But you never know, do you.  I mean, it wouldn't be the first time SQL
has been abused for something much easier to do in code...
see http://thedailywtf.com/Articles/The-Int-Divide.aspx for one, and
I'm sure there's many more out there.  A couple of rough ideas for
usage are already forming, but not to a sharable degree.

-- 
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] character counter

2009-06-27 Thread Richard Lovely
2009/6/27 julie :
> Hello,
>
> I need help with the following problem:
>
> Write a loop that reads each line of a file and counts the number of lines
> that are read until the total length of the lines is 1,000 characters. Use a
> break statement to make sure that you don't continue reading the file once
> the 1,000 characters are read.
>
> I figured out how to open a file, count and print the lines, however I
> cannot figure out or find online ...or anywhere else how to count characters
> in a file. This is what i have so far:
>
> file = open("/Users/meitalamitai/Documents/Computer
> Science/Python/Homework/Lorem_Ipsum.py")
> lines = 0
> for line in file:
>     lines=lines+1
> print '%r has %r lines' % ("Lorem_Ipsum.py", lines)
>    if char >= 1000:
>     break
>
> Thanks!
>
>
> ___
> Tutor maillist  -  tu...@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
In python, we don't explictily count, unless we absolutely have to.
Instead, in your situation, we measure the length of things.  Length
is what you need to be searching for.  Specifically, finding the
length of a string.

-- 
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Concatenation vs formatting

2008-09-01 Thread Richard Lovely
Just a couple of quick questions:
What differences are there in efficency (i.e. time and memory) between
string concatenation ("foo" + "bar") and printf style formatting
("%s%s" % ("foo","bar")).
Is there any place where one is better than the other, and any places
where either should be avoided?  (I tend to program entirely using
formatting.)

Thanks
-- 
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] absolute beginner

2008-09-11 Thread Richard Lovely
I'd absolutely recommend "Python for Dummies" published by Wileys.

I've not used that actual book, but I've found other books in the
series extremely helpful.

http://www.amazon.com/Python-Dummies-Computer-Tech/dp/0471778648/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1221146720&sr=8-1

On Thu, Sep 11, 2008 at 3:54 PM,  <[EMAIL PROTECTED]> wrote:

>  - Original Message -
>  From: Johnny
>  To: Python
>  Sent: Thursday, September 11, 2008 4:29 AM
>  Subject: [Tutor] absolute beginner
>
>
>  Anyone have any advice for an all out beginner?
>  Advice as in... The best book?...best tutor web page?
>  I am wanting so badly to learn Python.
>
>  I have went to this site...
>  http://www.awaretek.com/tutorials.html
>
>  This gave me lots of info,, but with so many books to choose from, I can't 
> seem to find that special one that will give me (a complete dummy) the info I 
> need.
>
>  thanks
>  Johnny
-- 
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Creating a chat system Server

2008-09-16 Thread Richard Lovely
Does anyone have any links and or know of any good libraries for
writing chat servers similar to IRC?  I'm looking to add chat
facilities to a game I'm working on.

Thanks.
-- 
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive using the os.walk(path) from the os module

2008-09-18 Thread Richard Lovely
The way I'd do it is create a dict mapping extensions to folders
(something like {'doc': 'word', 'pdf': 'acrobat'} ), then use
os.renames(old, new), which works the same as moving when you give it
a different path for new, and also magically handles creating new
directories for you.  The documentation for the os.walk() contains an
example that could easily be modified to do what you want.

The documentation is your friend.

> Message: 8
> Date: Thu, 18 Sep 2008 08:50:58 +0100
> From: "Alan Gauld" <[EMAIL PROTECTED]>
> Subject: Re: [Tutor] recursive using the os.walk(path) from the os
>module
> To: tutor@python.org
> Message-ID: <[EMAIL PROTECTED]>
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
>reply-type=original
>
>
> "A. Joseph" <[EMAIL PROTECTED]> wrote
>
>> I want to search through a directory and re-arrange all the files
>> into e.g
>>
>> All .doc files go into MS WORD folder, all .pdf files goes into PDF
>> Folder.
>>
>> I`m thinking of doing something with the os.walk(path) method from
>> os
>
> Which aspect is puzzling you? The use of os walk to traverse the
> folders? Or the algorithm to put the files into new folders?
>
> In either case you might get the answer in my Using the OS topic in
> my tutorial.
>
> Otherwise try posting a bit more detail on what you need.
>
> Thanks,
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
>
>
> --
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
> End of Tutor Digest, Vol 55, Issue 56
> *
>



-- 
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to replace instances

2008-09-26 Thread Richard Lovely
Hi, I'm not going to guess at why this doesn't work, but I've got a
potential solution for you:

class Z(object):
def __init__(self,y):
self.y = y
def replaceZ (self,withWhat):
self.__dict__ = withWhat.__dict__

Is there a reason you can't use a simple assignment (x=y) outside of the class?

On 9/25/08, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Date: Thu, 25 Sep 2008 04:24:31 -0400
> From: "Steve Collins" <[EMAIL PROTECTED]>
> Subject: [Tutor] How to replace instances
> To: tutor@python.org
> Message-ID:
><[EMAIL PROTECTED]>
> Content-Type: text/plain; charset="iso-8859-1"
>
> I've written a save/load function for a simple program using cPickle. Upon
> saving, a master list, to which all instances are added in their __init__,
> is pickled. when the program starts, if the user wishes to load, a variable
> "load" is set to one, and the pickled list is loaded. All the classes either
> A) initialize using the arguments provided or B) using the the attributes of
> the instances in the un-pickled list. This seems a little clunky to me, but
> it basically works.
> However, some of the instances refer explicitly to other instances
> instances. It's obvious why this causes problems. It occurred to me to
> simply replace the instances with the ones in the un-pickled list, but I
> don't know how.
>
> I tried using the following approach:
>
> class Z:
>def __init__(self,y):
>self.y = y
>def replaceZ (self,withWhat):
>self = withWhat
>
>
> That doesn't raise any errors, but it also doesn't work:
>
> >>> a = X(10)
> >>> b = X(20)
> >>> print a.y
> 10
> >>> print b.y
> 20
> >>> b.replaceZ(a)
> >>> print b.y
> 20
> >>> a
> <__main__.X instance at 0x00D4AE18>
> >>> b
> <__main__.X instance at 0x00D54328>
> >>>
>
> Can anyone tell me how to achieve this?
> -- next part --
> An HTML attachment was scrubbed...
> URL: 
> 
>

-- 
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pysqlite and SQLite

2008-09-29 Thread Richard Lovely
If you're compiling from source you do:
http://oss.itsystementwicklung.de/trac/pysqlite/browser/doc/install-source.txt

If you've got an installer, it shouldn't let you install if you don't
have the right things installed.

Even if you can install pysqlite, you wouldn't be able to run any
pysqlite code if you don't have the sqlite software.

2008/9/29 Adrian Greyling <[EMAIL PROTECTED]>:
> Probably a really dumb question, but...  Do I have to download and install
> SQLite before pysqlite will work properly?
> Thanks,
> Adrian
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>



-- 
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] More Pythonesque or a more efficient method

2008-10-07 Thread Richard Lovely
In a slightly related matter, Is is possible to use all() with a list
comprehension to check if a word contains all of the letters of
another?

-- 
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] finding numbers in range of of numbers

2008-10-21 Thread Richard Lovely
Guessing you mean [5,100] as the inclusive interval notation, so all
but the last element of the example pass?

if any(True for x, y in listoflists if 5 <= x and y <= 100):
   #do stuff

does this do it for you?

Or if you want to know if any elements of the lists within the larger
list are within the range, and the sublists always have two elements
you could do:

if any(True for x,y in listoflists if 5<= x <=100 and 5<= y <=100):
#do stuff

otherwise, for a list of arbirtary length lists:

from itertools import chain
if any(True for x in chain(*listoflists) if 5<= x <=100):
#do stuff

You can be slightly faster (but less readable) by changing the
if any(...):
to
if [...]:

This is probably more pythonic, as well.

(There might be a better way, but I like itertools).

Hope something in here was helpful...

On 20/10/2008, Srinivas Iyyer <[EMAIL PROTECTED]> wrote:
> dear group,
> a simple question that often challenges me.
>
> I have
>
> I have a list of list:
>
> [[10,45],[14,23],[39,73],[92,135]]
>
> I want to identify if any of the items in this list are in range of [5,100]
>
> These numbers are large in original data, I will be using xrange for memory 
> issues.
>
>  thank you.
> srini
>
> __
> Do You Yahoo!?
> Tired of spam?  Yahoo! Mail has the best spam protection around
> http://mail.yahoo.com
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] finding numbers in range of of numbers

2008-10-21 Thread Richard Lovely
I felt I need to appolgise for my first post in this thread...

I don't have internet access, and I've yet to find a public computer
with Python, so I'm unable to test any code I write.  I'm going have
to discpline myself not to post to here unless its: a) a problem of my
own, or b) an answer that doesn't contain code...

I also have nothing like the experience of some of you guys, who I'm
pretty much in awe of...

If I'm tempted again, I might have to remove myself from the list.

I'm just glad my session timed out before I was able to send the
other, more useless message.  (it's done that twice now, and I suppose
I should count myself as lucky...)

-- 
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need help w/ a for loop

2008-10-23 Thread Richard Lovely
Why not throw in itertools.cycle while you're at it? ;-)

pi = sum(4. / (1+x) * itertools.cycle((1,-1)).next() for x in range(0,
4 * n, 2))

I'd also be so tempted just to call the file 'approximate' (read it
with extension...)

Let's also not forget about integer division...

2008/10/23 bob gailer <[EMAIL PROTECTED]>:
> Monte Milanuk wrote:
>
> Hello all,
>
> New guy here, so go easy on me ;)
>
> We save the whips and chains for the more hardened questers. Newcomers get
> the feathers.
>
>
> I'm starting to work my way through Python Programming by Zelle, and have
> hit a bit of a wall on one of the programming exercises in Chapter 3 (#15 if
> anyone has the book handy).
>
> What the question ask is:  Write a program that approimates the value of pi
> by summing the terms of this series: 4/1 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11+...
> The program should ask the user for 'n', the number of terms to sum, and
> then output the sum of the first 'n' terms of this series.
>
> Where I am running into problems is how to do the '-' & '+', depending on
> the value of 'n'.  i.e. if 'n' = 3, it's going to be a - & an +, if 'n' =5
> its going to be -, +, -, +, etc.  How to make that work in terms of an
> algorithm is making my head hurt (and its so early in the book yet... ;) )
>
> There are many ways to handle this. Others have given some hints.
>
> The simplest IMHO is to set the range stride to 4 instead of 2 and then use
> x += 4.0/i - 4.0/(i + 2).
>
> You could also use a multiplier (let's call it m) that alternates between 1
> and -1. Roughly:
>
> x = 0
> m = 1
> for in in range...
>   x += 4.0/i*m
>   m =  -m
>
> For more generality and anticipating more complex algorithms:
>
> import operator
> ops = (operator.add, operator.sub)
> x = 0
> m = 0
> for in in range...
>   x = ops[m](x, 4.0/i)
>   m =  1-m
>
> And just for the heck of it you could write 2 for loops, each with a stride
> of 4. The first would just add all the fractions to be added and the second
> would add all the fractions to be subtracted, then combine them. Throwing in
> the sum function and generator expressions:
> pi = sum(4.0/i for i in range(1, n*2, 4)) - sum(4.0/i for i in range(3, n*2,
> 4))
>
> Applying sum and generator expressions to my original solution you get:
> pi = sum(4.0/i - 4.0/(i + 2) for i in range(1, 4*n, 4))
>
> Ah I can go on can't I? A lot more than you asked for!
>
> --
> Bob Gailer
> Chapel Hill NC
> 919-636-4239
> When we take the time to be aware of our feelings and
> needs we have more satisfying interatctions with others.
> Nonviolent Communication provides tools for this awareness.
> As a coach and trainer I can assist you in learning this process.
> What is YOUR biggest relationship challenge?
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>



-- 
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Problems with Calculator Program

2008-10-30 Thread Richard Lovely
Hi,  I'm trying to teach myself Tkinter by making a desktop calculator.

I've got the Tkinter bit working, but getting the output to work how I
want it to is causing serious brainfreeze...

The buttons 0 through 9 and '.' all append to a queue, which
makeNumber(queue) returns as an actual python number.  That all works.

Pressing one of the operators (+, -, /, *, or =) calls the following function:

def evaluate(op):
"""Evaluate a queue of button presses:
eg: [1, 2, 3, '+', 3, 2, 1] => 123 + 321 = 444"""

global last_op, total

initial_total = total
try:
operand = makeNumber(queue)
except ValueError:
operand = ''

if last_op == 'add':
disp_op = '+'
total += operand if operand != '' else 0

elif last_op == 'sub':
disp_op = '-'
total -= operand if operand != '' else 0

elif last_op == 'div':
disp_op = '/'
total /= float(operand) if operand != '' else 1

elif last_op == 'mul':
disp_op = '*'
total *= operand if operand != '' else 1

else:
disp_op = ''
if int(total) == total:
total = int(total)

if last_op == '':
print operand,
else:
print initial_total, disp_op, operand, '=', total
last_op = op
clearqueue()

What I want it to do is something like:
(the first list indicates button presses NOT the contents of the queue
[1, 2, 3, '+', 3, 2, 1, '*' 2] =>
queue = [1,2,3]; evaluate('add') gives output:
123 + 321 = 444
queue = [3,2,1]; evaluate('mul') gives output:
444 * 2 = 888

Like I said, the makeNumber function works, and the numbers are
definatly getting appended to the queue.  The logic within the above
function is the problem.  The main problem is allowing button
sequences like:
number op number equals, number op number equals


Did that make any sense at all?
-- 
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Help Optimise Code

2008-11-19 Thread Richard Lovely
I'm pretty new to code optimisation, so I thought I'd ask you all for advice.

I'm making an iterative prime number generator. This is what I've got so far:

Code: Select all
import math, array

def count2(start_at=0):
'Yield every third integer, beginning with start_at'
# this has been tested as faster than using itertools.count
while True:
yield start_at
start_at += 2

def iprimes():
'generate an endless sequence of prime numbers'
yield 2
yield 3
yield 5
sqrt = math.sqrt
knownPrimes = array.array("L",(3,5)) # 'L' for unsigned long - not
tested if using a smaller type is faster
for x in count2(7):
sqrtX = sqrt(x) # take extra function calls out of the inner loop
for p in knownPrimes):
test = (not x % p) and -1 or p > sqrtX
if test == -1: # (not x % p) == true
break
elif test: # (p > sqrtX) == true
yield x
knownPrimes.append(x)
break


I've tried a the sieve of erath-whatever as in test_generator,
implemented using itertools functions, but it hit max recusion depth
somewhere before 1000 primes, and I'm after millions of primes.

I'm not particularly bothered about startup overheads, just the loops.

Quick thought: would the following work (I'm on a public computer
without python, so can't test):

Code: Select all
def iprimes():
'generate an endless sequence of prime numbers'
yield 2
yield 3
yield 5
sqrt = math.sqrt
knownPrimes = array.array("L",(3,5)) # 'L' for unsigned long - not
tested if using a smaller type is faster
for x in count2(7):
sqrtX = sqrt(x) # take extra function calls out of the inner loop
for test in ((not x % p) and -1 or p > sqrtX for p in
knownPrimes)): # a generator _should_ be faster...
if test == -1: # (not x % p) == true
break
elif test: # (p > sqrtX) == true
yield x
knownPrimes.append(x)
break


Please don't suggest changing languages. I like python. Although if
you want to write an extension for me, and provide the source and a
makefile, please feel free. I have a MinGW install that's doing
nothing.  (Just kidding - almost.)

This is NOT homework.

-- 
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] noise function

2008-12-02 Thread Richard Lovely
There's probably something like what you want within the "random" module.

at the interactive prompt, try:

import random
help(random)

---
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com



2008/12/2 Alan Gauld <[EMAIL PROTECTED]>:
>
> "Christopher Spears" <[EMAIL PROTECTED]> wrote
>>
>> Does anyone know if python has a noise function?
>
> What kind of noise function?
> What would you expect it to produce?
> A stream of random numbers perhaps?
> A single number each time it is called?
>
> And which noise profile should it follow?
> Or would it be a multi dimensional noise model?
>
> I don't know of any such function and I'm not sure wiothout more details how
> it would work in a general way even if it did exist. Can you give a
> speciofic example of what you expect?
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Working with lists

2008-12-13 Thread Richard Lovely
When you need indexes for a list you're iterating over, you want to
look at the function enumerate(), which returns an iterator yielding
(key, value) tuples.

If you're working with multiple lists, itertools.imap and
itertools.imap_longest are handy if you want to keep the lists in
lockstep:

>>> l1 = [1,2,3,4,5]
>>> l2 = ['a','b','c','d','e','f']
>>> for key, value in enumerate(l1):
>>> print key, value
0 1
1 2
2 3
3 4
4 5
>>> import itertools
>>> for i1, i2 in itertools.izip(l1, l2):
>>> print i1, i2
1 'a'
2 'b'
3 'c'
4 'd'
5 'e'
>>> for i1, i2 in intertools.izip_longest(l1, l2, fillvalue=0):
>>> print i1, i2
1 'a'
2 'b'
3 'c'
4 'd'
5 'e'
0 'f'

Preventing yourself from using invalid indexes is harder, and depends
on exactly what you want to happen to the last value in the source
list.  To skip that last value, you could use something like the
following:
if value == longest_list[-1]:
break

using -1 as an index will always return the last value of that list.
Passing a unique value to fillvalue on izip_longest is another way.  I
normally use a specially created class:

class EndOfList(object):
pass

then you do:
for values in izip_longest(l1, l2... fillvalue=EndOfList)
if EndOfList in values: # one of the lists has run out of values
# do something special, then
break

And another way of doing your first example, that's one of the
extremly useful tools in python's armoury:

newlist = [a+b for a,b in itertools.izip(l1[:-1], l1[1:])]
This is a list comprehension, and is a very useful tool when you want
to build a list from another list (or any other iterable).  The
'slices' each give you a list with one less item, the first missing
the last item, the second, the first item.

Hope there's the information somewhere in this somewhat jumbled
response to help you.


Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com



2008/12/13  :
> Hi everyone,
>
> I seem to use this pattern alot when writing functions and I'm wondering if
> there is a more efficient method. It comes up whenever I want to work with
> more than one item in a list; for instance, say I want to add each
> consecutive number in alist and output the new list. Ideally, I'd be able to
> write:
>
> for num in list1:
> newlist.append(num+nextnum)
>
> This doesn't work, though because there's no way to access "nextnum" unless
> I implement a "count" variable like this:
>
> count=1
> for num in list1:
> newlist.append(num+list1[count])
> count+=1
>
> Instead, it usually ends up easier to write:
>
> for index in range (len(list1)-1):
> newlist.append((list1[index]+list1[index+1]))
>
> It's not a big deal to have to write the additional code, but problems arise
> when I use this structure in the context of more complex functions, when I
> am passing multiple lists of varying length, because it is easy to get
> confused with the index numbers and I can't do anything to the last value of
> the list, since I then get an "indexerror" because the function tries to
> call "list[i+1]".
>
> Is there a simpler way to do a procedure like this?
>
> Thanks.
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Class Extend Help

2008-12-20 Thread Richard Lovely
There are three ways as I see it: using __getattr__, using a new init,
or using a property decorator.  The last two are probably the most
pythonic, but I'm not familiar with decorators, so here's how I'd do
the second of the three:

try:
 from google.appengine.api.urlfetch import fetch
except:
 from urllib import urlopen

 class fetch(urlopen):
 def __init__(self, *args):
 urlopen.__init__(self, *args)
 self.content = self.read()


This probably doesn't behave exactly the same way as the google class,
but it should be similar enough?
---
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com



2008/12/20 Omer :
> Hey.
>
> I'm trying to do something I think is basic and am failing.
>
> The goal is:
> [mimicking the google urlopen syntax]
>
> try:
> from google.appengine.api.urlfetch import fetch
> except:
> from urllib import urlopen as fetch
>
>
> How do I add this "fetch" the property of content?
>
> I basically want fetch(url.com).content to replace urlopen(url.com).read()
>
> Mind, content is not a method.
>
> Thoughts?
>
> Thx. Omer.
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Class Extend Help

2008-12-23 Thread Richard Lovely
OK, going on Kent's post:

from urllib import urlopen

class fetch(object):
def __init__(self, *args):
self.response = urlopen(*args)
self.content = self.response.read()


I forgot urlopen was a function.  It made sense in my head for it to
be a class, instead of _returning_ a class.

It's trying to call __init__ on a functionType instance, and it's
getting confused.

See http://dpaste.com/hold/101951/ for another example.  The error
message is something cryptic, but between #python and I we think it's
something to do with calling type().
---
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com



2008/12/23 Kent Johnson :
> On Tue, Dec 23, 2008 at 9:31 AM, Omer  wrote:
>
> from urllib import urlopen
> class fetch(urlopen):
>> ... def __init__(self,*args):
>> ... urlopen.__init__(self, *args)
>> ... self.content = self.read()
>> ...
>>
>> Traceback (most recent call last):
>>   File "", line 1, in 
>> TypeError: Error when calling the metaclass bases
>> function() argument 1 must be code, not str
>>
>> Anybody, any idea what's up with that?
>
> That's pretty obscure, not sure why you get exactly that error!
>
> Anyway the code should be
> class fetch(object):
>
> urlopen is a function, not a class, so it can't be a base class of
> fetch. There is no need for it to be a base class, either; just use
> object.
>
> Kent
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Suggestions for more efficient and optimized coding technique,

2009-01-08 Thread Richard Lovely
2009/1/8 Kent Johnson :
>
> This is a strange requirement. If you want to try all combinations of
> lowercase letters, the simplest way to do that is with nested loops.
> The loops will generate all combinations without repeating, so there
> is no need to save the used combinations.
>


or itertools.product

---
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Active State Python with IDLE Python 2.5

2009-01-14 Thread Richard Lovely
The Activestate package IS vanilla python.  It just comes packaged
with a few addon modules for things such as ActiveX and with windows
GUI libraries.  If it works with Vanilla Python, there's virtually no
reason it won't work with the activestate distribution, and vice
versa, as long as you don't use any of the activestate modules in
applications you want to work on other operating systems.

It's like the TK modules, if you don't import them, you don't need to
worry about whether your users have them or not.

On 12/01/2009, Wayne Watson  wrote:
> Thanks. Is it possible to just disable the vanilla version? I may want to
> switch between the two. Most users of the program I'm about to modify use
> the vanilla version. At some point, I may want to go back to it to verify
> that in their world all is OK.
>
>
> Alan Gauld wrote:
>
> "Wayne Watson"  wrote
>
> I installed "Python" 2.5 a few months ago, and decided I'd like to try
> windowpy from ActiveState. Is having both of these installed going to
> cause me trouble?
>
> Multiple versions of Python should not be a problem provided you put
> them in different folders.
>
> C:\python25
>
> and
>
> C:\ASpython25
>
> for example
>
> You will have to remember which one is the default version (ie will
> be used when you double click a python file for example) but you
> can set things up to run both. But there is little point. If you are
> on Windows I'd personally uninstall the vanilla version and install
> the ActiveState version, it has a lot more features for Windows users.
>
> Alan G.
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
> --
>  Wayne Watson (Watson Adventures, Prop., Nevada City, CA)

 (121.01 Deg. W,
> 39.26 Deg. N) GMT-8 hr std. time)

 "What killed the electric car?
> Expensive batteries did."
 -- Physics for Future Presidents, Richard A.
> Muller

 Web Page: 
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Richard "Roadie Rich" Lovely, part of the JNP|UK Famile
www.theJNP.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor