[Tutor] Tutor Digest, Vol 26, Issue 62

nywbon001 at mail.uct.ac.za nywbon001 at mail.uct.ac.za
Wed Apr 19 08:59:28 CEST 2006


Quoting tutor-request at python.org:

> Send Tutor mailing list submissions to
> 	tutor at python.org
>
> To subscribe or unsubscribe via the World Wide Web, visit
> 	http://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body 'help' to
> 	tutor-request at python.org
>
> You can reach the person managing the list at
> 	tutor-owner at python.org
>
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Tutor digest..."
>
>
> Today's Topics:
>
>    1. Help Entry  !!! (Cesar Garcia)
>    2. creating a tab delim file (Srinivas Iyyer)
>    3. Re: Olle-Olla (Kent Johnson)
>    4. Re: Tutorial on bitwise Python? (Alan Gauld)
>    5. Re: creating a tab delim file (Karl Pfl?sterer)
>    6. Version of a .pyc file (Don Taylor)
>    7. unit testing raw_input() (Andre Roberge)
>    8. Re: Version of a .pyc file (Terry Carroll)
>    9. Re: unit testing raw_input() (Michael)
>   10. Re: unit testing raw_input() (Danny Yoo)
>
>
> ----------------------------------------------------------------------
>
> Message: 1
> Date: Tue, 18 Apr 2006 11:14:03 -0700 (PDT)
> From: Cesar Garcia <cdgarciaq at yahoo.com>
> Subject: [Tutor] Help Entry  !!!
> To: tutor at python.org
> Message-ID: <20060418181403.20038.qmail at web51709.mail.yahoo.com>
> Content-Type: text/plain; charset="iso-8859-1"
>
> Hi !!!
>   Friends, i nedd process Data Entry in python
>   Example
>
>   Entry = 20
>   Result = 20*10
>
>   This Result in Windows (Tkinter)
>   How do you do Think !!!!!!!
>
>   Regards
>   Cesar
>   Exmaple
>   from Tkinter import *
>   class MyDialog:
>       def __init__(self, parent):
>         top = self.top = Toplevel(parent)
>         Label(top, text="Valor").pack()
>         self.e = Entry(top)
>         self.e.pack(padx=5)
>         b = Button(top, text="OK", command=self.ok)
>         b.pack(pady=5)
>       def ok(self):
>         print "value is", self.e.get()
>         self.top.destroy()
>   root = Tk()
> root.update()
> d = MyDialog(root)
> root.wait_window(d.top)
>
>
> ---------------------------------
> New Yahoo! Messenger with Voice. Call regular phones from your PC and save
> big.
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL:
>
http://mail.python.org/pipermail/tutor/attachments/20060418/0bb19d34/attachment-0001.htm
>
> ------------------------------
>
> Message: 2
> Date: Tue, 18 Apr 2006 11:53:58 -0700 (PDT)
> From: Srinivas Iyyer <srini_iyyer_bio at yahoo.com>
> Subject: [Tutor] creating a tab delim file
> To: tutor at python.org
> Message-ID: <20060418185358.365.qmail at web38113.mail.mud.yahoo.com>
> Content-Type: text/plain; charset=iso-8859-1
>
> Hi group,
>  I asked similar questions in the past. I am unable to
> get to the crux of this problem so that I can solve on
> my own. apologies for my ignorance.
>
>
> The problem:
>
> I have 50 tab delim files. Each file has 500 rows and
> 50 columns.
>
> I have to read the first column of each file. Repeat
> the same for 50 files and write a tab delim text file
> containing 500 rows and 50 columns.
>
> code that works through half of the problem:
>
> import glob
>
> files = glob.glob('*.proc')
>
>
> for each in files:
>       f = open(each,'r')
>       da = f.read().split('\n')
>       dat = da[:-1]
>       for m in dat:
>             mycol = m.split('\t')[0]
>             ..................
>
> >From here I am blanked out. Although I can extract the
> first column from each file:I have no idea how to
> store each list.
>
> thought 1. Create an empty string and join each by a
> tab.
> ##
>        mycol = ''
>        for m in dat:
>             mycol = m.split('\t')[0]
>             mstr = '\t'.join(mycol)
> how can i append the data from second file to that
> string.
>
>
> could tutors help me with this situation.
>
> Thanks
> srini
>
> __________________________________________________
> Do You Yahoo!?
> Tired of spam?  Yahoo! Mail has the best spam protection around
> http://mail.yahoo.com
>
>
> ------------------------------
>
> Message: 3
> Date: Tue, 18 Apr 2006 14:59:38 -0400
> From: Kent Johnson <kent37 at tds.net>
> Subject: Re: [Tutor] Olle-Olla
> To: Python Tutor <tutor at python.org>
> Message-ID: <4445371A.1000502 at tds.net>
> Content-Type: text/plain; charset=UTF-8; format=flowed
>
> Andre Engels wrote:
> > 2006/4/18, Kent Johnson <kent37 at tds.net>:
> >> J?nos Juh?sz wrote:
> >>> Hi All,
> >>>
> >>> Is it possible to replace the print statement with one of mine function ?
> >>>
> >>> In reality, I would like to replace the print in my PyCrust app with the
> >>> log.write() function.
> >> Best: Use a good editor to change your print statements to log.write()
> >
> > Even better: Use a good editor to change your print statements to
> > myprint() and then def myprint() to be log.write(). This has the
> > advantage that if (for example) you want prints later to be "usually
> > log.write() but if redFlagHighestWarning is True, then both
> > log.write() and print()", you don't need to go through all this again,
> > but just have to change myprint().
>
> Or use the logging module, which lets you make changes like this by
> editing a config file. I usually set it up so that INFO level and higher
> messages go to a console or GUI panel, and all messages go to a rollover
> file. Very handy.
>
> Kent
>
>
>
> ------------------------------
>
> Message: 4
> Date: Tue, 18 Apr 2006 20:56:01 +0100
> From: "Alan Gauld" <alan.gauld at freenet.co.uk>
> Subject: Re: [Tutor] Tutorial on bitwise Python?
> To: "Terry Carroll" <carroll at tjc.com>, <tutor at python.org>
> Message-ID: <00d401c66322$1ec8ecc0$0a01a8c0 at xp>
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
> 	reply-type=original
>
>
> > Can anyone point me to a tutorial on bit manipulations (testing and
> > setting) in Python?
>
> Look at the sidebar in my OS topic.
> It covers using bitmasks to test the bits set by the file stat functions.
>
> HTH,
>
> Alan G
> Author of the learn to program web tutor
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
>
>
> ------------------------------
>
> Message: 5
> Date: Tue, 18 Apr 2006 23:55:18 +0200
> From: Karl Pfl?sterer <khp at pflaesterer.de>
> Subject: Re: [Tutor] creating a tab delim file
> To: tutor at python.org
> Message-ID: <uacailghr.fsf at hamster.pflaesterer.de>
> Content-Type: text/plain; charset=us-ascii
>
> On 18 Apr 2006, srini_iyyer_bio at yahoo.com wrote:
>
> > The problem:
> >
> > I have 50 tab delim files. Each file has 500 rows and
> > 50 columns.
> >
> > I have to read the first column of each file. Repeat
> > the same for 50 files and write a tab delim text file
> > containing 500 rows and 50 columns.
> >
> > code that works through half of the problem:
> >
> > import glob
> >
> > files = glob.glob('*.proc')
> >
> >
> > for each in files:
> >       f = open(each,'r')
> >       da = f.read().split('\n')
> >       dat = da[:-1]
> >       for m in dat:
> >             mycol = m.split('\t')[0]
> >             ..................
>
> You don't need to read the whole file at once. You can read individual
> lines from a file with:
>       f = open('name')
>       for line in f:
>           # do something with line
>
> I'll show you a different solution for your problem; if you don't
> understand it ask (I try to explain it).
>
> --8<---------------cut here---------------start------------->8---
> import glob
>
> filehdls = [file(f) for f in glob.glob('*.proc')]
> out = open('reordered.prc', 'w')
>
> col_1 = [f.readline().split('\t')[0] for f in filehdls]
> while col_1[0]:
>     out.write('\t'.join(col0))
>     out.write('\n')
>     col_1 = [f.readline().split('\t')[0] for f in filehdls]
>
>
> out.close()
> for f in filehdls: f.close()
>
> --8<---------------cut here---------------end--------------->8---
>
> filehdls is a list of file handles.
> col_1 is a list of the values of column 1 of each of the files.
> How does it work?
>     f.readline().split('\t')[0]
> Read it from left to right.
> First we call readline() which reads the next line from file or returns
> the empty string if it reached the end of the file.
> Then we call split('\t') on the string returned from readline().  This
> returns a list of strings obtained from splitting the string at each
> tab.
> Then we take the first element from thew list (index 0) since we are
> only interested in column 1.
> We do this for every file in the list of file handles.
>
> The while loop runs as long as the first element in our list of
> columns is not false (at eof we get here an empty string which counts as
> false).  We join the columns with a tab, write that string to our output
> file and write a newline to that file.  Then we try to read the next
> line.
>
> The above will only work if all files have equal length.
>
>
>    Karl
> --
> Please do *not* send copies of replies to me.
> I read the list
>
>
> ------------------------------
>
> Message: 6
> Date: Tue, 18 Apr 2006 18:10:47 -0400
> From: Don Taylor <nospamformeSVP at gmail.com>
> Subject: [Tutor] Version of a .pyc file
> To: tutor at python.org
> Message-ID: <e23o58$sq8$1 at sea.gmane.org>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> I want like to write a script to scan all of the .pyc on my pythonpath
> to find out if they were built with Python 2.3 or 2.4.
>
> How can I tell if a .pyc file was built with 2.3 or 2.4?
>
> Thanks,
>
> Don.
>
>
>
> ------------------------------
>
> Message: 7
> Date: Tue, 18 Apr 2006 19:34:48 -0300
> From: "Andre Roberge" <andre.roberge at gmail.com>
> Subject: [Tutor] unit testing raw_input()
> To: Tutor <tutor at python.org>
> Message-ID:
> 	<7528bcdd0604181534i3aa3e4a8v3a936eb82f072a5f at mail.gmail.com>
> Content-Type: text/plain; charset=ISO-8859-1
>
> Hi all-
>
> Suppose I had a function like the following:
>
> def y_n(prompt="Answer yes or no"):
>     while True:
>         answer = raw_input(prompt)
>         if answer in ['y', 'Y', 'yes']:
>             print "You said yes!"
>             break
>         elif answer in ['n', 'N', 'no']:
>             print "You said no!"
>             break
>         else:
>             print "%s is an invalid answer."%answer
>
> How could I go about to write an automated test for it?
>
> Andr?
>
>
> ------------------------------
>
> Message: 8
> Date: Tue, 18 Apr 2006 16:01:28 -0700 (PDT)
> From: Terry Carroll <carroll at tjc.com>
> Subject: Re: [Tutor] Version of a .pyc file
> To: tutor at python.org
> Message-ID:
> 	<Pine.LNX.4.44.0604181559500.31735-100000 at violet.rahul.net>
> Content-Type: TEXT/PLAIN; charset=US-ASCII
>
> On Tue, 18 Apr 2006, Don Taylor wrote:
>
> > How can I tell if a .pyc file was built with 2.3 or 2.4?
>
> There's a "Magic Number" in the first 2 or 4 bytes, (depending on whether
> you consider the \r\n part of the MN).
>
> >>> f = open("pycfile.pyc", "rb")
> >>> magictable = {'\x3b\xf2\r\n': "2.3", '\x6d\xf2\r\n' : "2.4"}
> >>> magic = f.read(4)
> >>> release = magictable.get(magic,"unknown")
> >>> print "Python release:", release
> Python release: 2.4
>
>
>
> ------------------------------
>
> Message: 9
> Date: Wed, 19 Apr 2006 00:15:51 +0100
> From: Michael <ms at cerenity.org>
> Subject: Re: [Tutor] unit testing raw_input()
> To: tutor at python.org
> Message-ID: <200604190015.51904.ms at cerenity.org>
> Content-Type: text/plain;  charset="iso-8859-1"
>
> On Tuesday 18 April 2006 23:34, Andre Roberge wrote:
> > Hi all-
> >
> > Suppose I had a function like the following:
> >
> > [ function that interacts with the outside world ]
> ...
> > How could I go about to write an automated test for it?
>
> You create a mock for raw_input, put the above code inside a module and
> rebind
> raw_input in the module before calling your function.
>
> ie:
> ------------(CONTENTS of y_n.py)------------
> def y_n(prompt="Answer yes or no"):
>     while True:
>         answer = raw_input(prompt)
>         if answer in ['y', 'Y', 'yes']:
>             print "You said yes!"
>             break
>         elif answer in ['n', 'N', 'no']:
>             print "You said no!"
>             break
>         else:
>             print "%s is an invalid answer."%answer
> ------------(END CONTENTS of y_n.py)------------
>
> You can even create and test a mock in the command line interpreter, so
> here's
> a quick example:
>
> >>> import y_n   # Import the module
> >>> def raw_input_mock(prompt): # create a mock
> ...     return "y"
> ...
> >>> y_n.raw_input = raw_input_mock      # rebind the name inside the module
> >>> y_n.y_n() # Run, this now calls our mock instead of the real raw_input
> You said yes!
>
> To my mind this is generally useful for testing error conditions with complex
> modules (select & socket spring to mind).
>
> To do this properly with your module, it makes more sense for your function
> to return strings, which would allow you to directly test the result.
> Alternatively you could wrap print in a function and then mock that instead.
>
> The key thing about a mock is that it simply provides the results you want.
> If
> it's important *how* the mock was called (eg you're testing correct use of a
> library), your mock could append parameters to a list for later comparision.
>
> Eg
> >>> mocktrace = []
> >>> def raw_input_mock(prompt): # create a mock
> ...     mocktrace.append((prompt,))
> ...     return "y"
> ...
>
> As I say though, this sort of thing is (IME) often more about testing the
> correct usage of something.
>
> Regards,
>
>
> Michael.
>
>
> ------------------------------
>
> Message: 10
> Date: Tue, 18 Apr 2006 18:39:29 -0700 (PDT)
> From: Danny Yoo <dyoo at hkn.eecs.berkeley.edu>
> Subject: Re: [Tutor] unit testing raw_input()
> To: Andre Roberge <andre.roberge at gmail.com>
> Cc: Tutor <tutor at python.org>
> Message-ID: <Pine.LNX.4.64.0604181828310.21097 at hkn.eecs.berkeley.edu>
> Content-Type: TEXT/PLAIN; charset=US-ASCII; format=flowed
>
>
>
> On Tue, 18 Apr 2006, Andre Roberge wrote:
>
> > Suppose I had a function like the following:
> >
> > def y_n(prompt="Answer yes or no"):
> >    while True:
> >        answer = raw_input(prompt)
> >        if answer in ['y', 'Y', 'yes']:
> >            print "You said yes!"
> >            break
> >        elif answer in ['n', 'N', 'no']:
> >            print "You said no!"
> >            break
> >        else:
> >            print "%s is an invalid answer."%answer
> >
> > How could I go about to write an automated test for it?
>
>
> Hi Andre,
>
> One way to do this is to parameterize y_n() a little more to make it more
> amendable to unit testing.
>
>
> If we look at y_n(), we'd say that "raw_input()" is a free variable in
> here --- its meaning comes from the outside environment as part of
> builtins.  We can change this by making it an explicit parameter:
>
> ########################################################
> def y_n(prompt="Answer yes or no", raw_input=raw_input):
>      while True:
>          answer = raw_input(prompt)
>          if answer in ['y', 'Y', 'yes']:
>              print "You said yes!"
>              break
>          elif answer in ['n', 'N', 'no']:
>             print "You said no!"
>              break
>          else:
>              print "%s is an invalid answer."%answer
> ########################################################
>
> Looks a little funny.  *grin*
>
>
> But now we can hardcode particular inputs by sending y_n() a mock
> "raw_input" that returns precooked values.
>
> ###########################
> def yes1_raw_input(prompt):
>      return "y"
>
> def yes2_raw_input(prompt):
>      return "Y"
>
> def yes3_raw_input(prompt):
>      return "yes"
>
> def yes4_raw_input(prompt):
>      return "YES"
> ###########################
>
> And then we can use these as part of our test case:
>
>      y_n(raw_input=yes1_raw_input)
>
>
>
> We can also parameterize output in the same way.  Right now, the function
> is printing out the answer.  Testing printed output is a little harder in
> Python without fiddling around with stdout, but we can also make this also
> a parameter of the function:
>
> ###################################################
> def y_n(prompt="Answer yes or no",
>          raw_input=raw_input,
>          output=sys.stdout):
>      while True:
>          answer = raw_input(prompt)
>          if answer in ['y', 'Y', 'yes']:
>              print >>output, "You said yes!"
>              break
>          elif answer in ['n', 'N', 'no']:
>              print >>output, "You said no!"
>              break
>          else:
>              print >>output, "%s is an invalid answer."%answer
> ###################################################
>
>
> Now we can inject our own output string that we can use to test what has
> happened:
>
>      ## pseudocode
>
>      import StringIO
>      test_output = StringIO.StringIO()
>      y_n(raw_input = yes4_raw_input,
>          output = test_output)
>
>      assertEquals("You said yes!", test_output.getvalue())
>
> Does this make sense so far?  y_n() in its original form might not be in
> the right shape to make it easy to test, but we can turn it into a form
> that is more easily testable.
>
>
> Good luck!
>
>
> ------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
> End of Tutor Digest, Vol 26, Issue 62
> *************************************
> haai guys:
i want to write a function which will sort the sentence by the length of each
word in the sentece, short length first.please help.




----------------------------------------------------------------
This message was sent using IMP, the Internet Messaging Program.



More information about the Tutor mailing list