Re: [Tutor] Append function
On Sun, 30 Jan 2005, kumar s wrote: > I have a bunch of files where the first column is always the same. I > want to collect all those files, extract the second columns by file wise > and write the first column, followed by the other columns(extracted from > files) next to each other. Hi Kumar, Can you show us an example of what you mean? I think you're looking for something takes a list of line elements, like ### lines = """ 1 Alpha 1 Beta 1 Gamma 1 Delta 1 Epsilon """.split('\n') ### and combines input lines with the same first column into something like this: ### 1 Alpha|Beta|Gamma|Delta|Epsilon ### But I'm not positive if something like this is what you're trying to do. You mentioned multiple files: can you show us a small, simple example with two files? An example like this will help clarify the problem, and help us know if we're really answering your question. Best of wishes to you! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] files in a directory
> Now that I am reading many files at once, I wanted, to > have a tab delim file op that looks like this: > > My_coors Int_file 1 Int_file2 > IntFile3 > 01:26 34 235 > 245.45 > 04:42 342.4452.445.5 > 02:56 45.4 34.5 557.8 [code cut] Hi Kumar, Ok, I think I see the source of the bug. Let's check how the code writes each of my_vals: > for line in my_vals: > f2.write(line+'\t') => asking for tab delim.. > f2.write('\n') The problematic statement is the last one: between each of the values, the code writes a newline as well as the tab character. Push the newline-writing code outside of the loop, and you should be ok. As a note: you can simplify the tab-writing code a bit more by using a string's "join()" method. For example: ### >>> "/".join(["this", "is", "a", "test"]) 'this/is/a/test' ### So we can join a bunch of elements together without using an explicit 'for' loop. In your program, you can use join() to create a large string of the my_vals elements with tabs joining them. If you'd like to see more, the library documentation: http://www.python.org/doc/lib/string-methods.html#l2h-192 mentions more information on the join() method and the other methods that strings support. Please feel free to ask more questions on any of this. (But when you reply, try to cut down on the number of lines that you quote from the previous message. I almost missed your question because I couldn't see it at first! *grin*) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dividing 1 by another number ?
> What Alan meant, presumably, was this: > > one = 1 > other = 42 > result = float(one)/other Whoops! Yes indeedy! Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Newbie struggling with Tkinter/canvas tags
On Sun, 30 Jan 2005, Glen wrote: > As a Python/Tkinter newbie, I thought I was getting on ok... > then I hit this problem. > > I have a canvas (c1) > A group of objects are drawn on c1 and given a tag > c1.addtag_all('group_A') > Another group of objects are drawn, I wish to tag these 'group_B'. Hi Glen, Ok, so you're looking for something like a hypothetical "find_withouttag" to define 'group_B' then. I don't think such a function exists directly, but we can make it up. > At the moment I 'get by' with... > > a=c1.find_withtag('group_A') > b=c1.find_all() > c=b[len(a):] > for i in range(len(c)): > c1.addtag_above('group_B',len(a)+i) There's one problem here: the system doesn't guarantee that all the 'group_A' elememts will end up at the beginning of 'b', so there's a very strong possibility of tagging the wrong elements here. I think that getting this right will take some more work. Here's a definition of a function called find_withouttag(): ### def find_withouttag(canvas, tag): """Returns all the objects that aren't tagged with 'tag'.""" all_objects = canvas.find_all() tagged_objects = canvas.find_withtag(tag) return subtract_instances(all_objects, tagged_objects) def subtract_instances(l1, l2): """Returns a list of all the object instances in l1 that aren't in l2.""" identity_dict = {} for x in l1: identity_dict[id(x)] = x for x in l2: if id(x) in identity_dict: del identity_dict[id(x)] return identity_dict.values() ### [Side note to other: the work that subtract_instances() does is similar to what IdentityHashMap does in Java: does anyone know if there's already an equivalent dictionary implementation of IdentityHashMap in Python?] We can see how subtract_instances() works on a simple example: ### >>> class MyClass: ... def __init__(self, name): ... self.name = name ... def __repr__(self): ... return str(self.name) ... >>> frodo, elrond, arwen, aragorn, sam, gimli = ( ...map(MyClass, "Frodo Elrond Arwen Aragorn Sam Gimli".split())) >>> hobbits = frodo, sam >>> everyone = frodo, elrond, arwen, aragorn, sam, gimli >>> >>> subtract_instances(everyone, hobbits) [Arwen, Aragorn, Gimli, Elrond] ### This subtract_instances() function should do the trick with instances of the canvas items. There's probably a simpler way to do this --- and there are things we can do to make it more efficient --- but I have to go to sleep at the moment. *grin* Best of wishes to you! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Newbie struggling with Tkinter/canvas tags
On Mon, 31 Jan 2005, Danny Yoo wrote: > I think that getting this right will take some more work. Here's a > definition of a function called find_withouttag(): [Code cut] Oh! Never mind; this can be a lot simpler. According to the "Gotchas" section of: http://tkinter.unpythonic.net/wiki/Widgets/Canvas the items in a Canvas are actually not object instances themselves, but integers. I made an assumption that canvas items were object instances, so I wrote that subtract_instances() to take care of issues with them. But if canvas items are really integers, then we don't need subtract_instances() at all. We can just use sets and subtract one set from the other. Here is a redefinition of find_withouttag() which should work better: ### from sets import Set def find_withouttag(canvas, tag): """Returns all the objects that aren't tagged with 'tag'.""" all_objects = Set(canvas.find_all()) tagged_objects = Set(canvas.find_withtag(tag)) return all_objects - tagged_objects ### Here's a small example with sets to make it more clear how this set manipulation stuff will work: ### >>> from sets import Set >>> numbers = range(20) >>> primes = [2, 3, 5, 7, 11, 13, 17, 19] >>> Set(numbers) - Set(primes) Set([0, 1, 4, 6, 8, 9, 10, 12, 14, 15, 16, 18]) ### For more information on sets, see: http://www.python.org/doc/lib/module-sets.html Best of wishes to you! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Newbie struggling with Tkinter/canvas tags
Danny Yoo wrote: Oh! Never mind; this can be a lot simpler. According to the "Gotchas" section of: http://tkinter.unpythonic.net/wiki/Widgets/Canvas the items in a Canvas are actually not object instances themselves, but integers. I made an assumption that canvas items were object instances, so I wrote that subtract_instances() to take care of issues with them. ?? Sets can contain any object that is usable as a dictionary key. But if canvas items are really integers, then we don't need subtract_instances() at all. We can just use sets and subtract one set from the other. Here is a redefinition of find_withouttag() which should work better: ### from sets import Set Note that Python 2.4 has set built-in with the name 'set'. To be compatible with both you could write try: set except NameError: from sets import Set as set def find_withouttag(canvas, tag): """Returns all the objects that aren't tagged with 'tag'.""" all_objects = Set(canvas.find_all()) tagged_objects = Set(canvas.find_withtag(tag)) return all_objects - tagged_objects ### or all_objects = Set(canvas.find_all()) all_objects.difference_update(canvas.find_withtag(tag)) return all_objects Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] help with regexps/filename parsing
Hey all. I've got an issue that's been driving me a bit nuts. I'm sure it _can_ be done with a regexp, although I'm missing a piece needed to tie it together to work for all cases. I need to parse out a list of RPMs in this case, but it seems the RPM naming convention has changed, as there are files I'll need to parse that are NOT in the normal name-version-release.arch.rpm format. I need to be able to grab the 'basename' for each file, as well as the version and arch, although these can be done seperately. The problem can be shown by the following list of filenames: XFree86-ISO8859-15-75dpi-fonts-4.3.0-78.EL.i386.rpm (Note the EL embedded in name) xfig-3.2.3d-12.i386.rpm (standard naming) rhel-ig-ppc-multi-zh_tw-3-4.noarch.rpm perl-DateManip-5.42a-0.rhel3.noarch.rpm openoffice.org-style-gnome-1.1.0-16.9.EL.i386.rpm Those should represent the set of variations now possible. I can handle most, but not all of the cases...any suggestions that would cover all of the above allowing the extraction of: basename- in this case: XFree86-ISO8859-15-75dpi-fonts, xfig, rhel-ig-ppc-multi-zh_tw, perl-DateManip, openoffice.org-style-gnome version: 4.3.0-78.EL (yes, including the .EL unfortunately, although I'd be OK without it and munging it on end if needed) 3.2.3d-12 3-4 5.42a-0 1.1.0-16.9.EL arches: i386, i386, noarch, noarch, i386 respectively. Any help greatly appreciated, as I've been beating myself up on this one for a bit. Thanks, Scott ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with regexps/filename parsing
Slight correction which I realized after sending, see below for version/release seperation, which I should have seen but blame lack of sleep ;-) Scott W wrote: Hey all. I've got an issue that's been driving me a bit nuts. I'm sure it _can_ be done with a regexp, although I'm missing a piece needed to tie it together to work for all cases. I need to parse out a list of RPMs in this case, but it seems the RPM naming convention has changed, as there are files I'll need to parse that are NOT in the normal name-version-release.arch.rpm format. I need to be able to grab the 'basename' for each file, as well as the version and arch, although these can be done seperately. The problem can be shown by the following list of filenames: XFree86-ISO8859-15-75dpi-fonts-4.3.0-78.EL.i386.rpm(Note the EL embedded in name) xfig-3.2.3d-12.i386.rpm(standard naming) rhel-ig-ppc-multi-zh_tw-3-4.noarch.rpm perl-DateManip-5.42a-0.rhel3.noarch.rpm openoffice.org-style-gnome-1.1.0-16.9.EL.i386.rpm Those should represent the set of variations now possible. I can handle most, but not all of the cases...any suggestions that would cover all of the above allowing the extraction of: basename- in this case: XFree86-ISO8859-15-75dpi-fonts, xfig, rhel-ig-ppc-multi-zh_tw, perl-DateManip, openoffice.org-style-gnome version: 4.3.0-78.EL(yes, including the .EL unfortunately, although I'd be OK without it and munging it on end if needed) 3.2.3d-12 3-4 5.42a-0 1.1.0-16.9.EL corrected versions: 4.3.0 3.2.3d 3 5.42a 1.10 (new) releases: 78.EL 12 4 0 16.9.EL arches: i386, i386, noarch, noarch, i386 respectively. Any help greatly appreciated, as I've been beating myself up on this one for a bit. Thanks, Scott ___ 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] Newbie struggling with Tkinter/canvas tags
Kent Johnson wrote: Note that Python 2.4 has set built-in with the name 'set'. To be compatible with both you could write try: set except NameError: from sets import Set as set Clarification: you don't _have_ to do this to be compatible with 2.4. The sets module is in both 2.3 and 2.4. The difference in 2.4 is that set is also a built-in data type implemented in C with the same interface as sets.Set. The code above will take advantage of the built-in set if it is available, otherwise use sets.Set. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with regexps/filename parsing
This works: names = [ 'XFree86-ISO8859-15-75dpi-fonts-4.3.0-78.EL.i386.rpm', #(Note the EL embedded in name) 'xfig-3.2.3d-12.i386.rpm', #(standard naming) 'rhel-ig-ppc-multi-zh_tw-3-4.noarch.rpm', 'perl-DateManip-5.42a-0.rhel3.noarch.rpm', 'openoffice.org-style-gnome-1.1.0-16.9.EL.i386.rpm', ] import re pattern = r''' (?P.+) -(?P[\w.]+) -(?P[\w.]+) \.(?P\w+) \.rpm ''' patternRe = re.compile(pattern, re.VERBOSE) for name in names: m = patternRe.search(name) if m: print m.group('base', 'version', 'release', 'arch') else: print 'No match:', name I figured this out by working from right to left: - always ends with .rpm - everything back to the next . is the arch - everything back to the first (rightmost) - is the release - everything to the next - is version - everything left is the base name Note the release for perl-DateManip-5.42a-0.rhel3.noarch.rpm is 0.rhel3 not 0 as you gave it. Kent Scott W wrote: Slight correction which I realized after sending, see below for version/release seperation, which I should have seen but blame lack of sleep ;-) Scott W wrote: Hey all. I've got an issue that's been driving me a bit nuts. I'm sure it _can_ be done with a regexp, although I'm missing a piece needed to tie it together to work for all cases. I need to parse out a list of RPMs in this case, but it seems the RPM naming convention has changed, as there are files I'll need to parse that are NOT in the normal name-version-release.arch.rpm format. I need to be able to grab the 'basename' for each file, as well as the version and arch, although these can be done seperately. The problem can be shown by the following list of filenames: XFree86-ISO8859-15-75dpi-fonts-4.3.0-78.EL.i386.rpm(Note the EL embedded in name) xfig-3.2.3d-12.i386.rpm(standard naming) rhel-ig-ppc-multi-zh_tw-3-4.noarch.rpm perl-DateManip-5.42a-0.rhel3.noarch.rpm openoffice.org-style-gnome-1.1.0-16.9.EL.i386.rpm Those should represent the set of variations now possible. I can handle most, but not all of the cases...any suggestions that would cover all of the above allowing the extraction of: basename- in this case: XFree86-ISO8859-15-75dpi-fonts, xfig, rhel-ig-ppc-multi-zh_tw, perl-DateManip, openoffice.org-style-gnome version: 4.3.0-78.EL(yes, including the .EL unfortunately, although I'd be OK without it and munging it on end if needed) 3.2.3d-12 3-4 5.42a-0 1.1.0-16.9.EL corrected versions: 4.3.0 3.2.3d 3 5.42a 1.10 (new) releases: 78.EL 12 4 0 16.9.EL arches: i386, i386, noarch, noarch, i386 respectively. Any help greatly appreciated, as I've been beating myself up on this one for a bit. Thanks, Scott ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ 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] help with regexps/filename parsing
On 31 Jan 2005, [EMAIL PROTECTED] wrote: > I've got an issue that's been driving me a bit nuts. I'm sure it _can_ > be done with a regexp, although I'm missing a piece needed to tie it > together to work for all cases. > > I need to parse out a list of RPMs in this case, but it seems the RPM > naming convention has changed, as there are files I'll need to parse > that are NOT in the normal name-version-release.arch.rpm format. > > I need to be able to grab the 'basename' for each file, as well as the > version and arch, although these can be done seperately. The problem > can be shown by the following list of filenames: > > XFree86-ISO8859-15-75dpi-fonts-4.3.0-78.EL.i386.rpm (Note the EL > embedded in name) > xfig-3.2.3d-12.i386.rpm (standard naming) > rhel-ig-ppc-multi-zh_tw-3-4.noarch.rpm > perl-DateManip-5.42a-0.rhel3.noarch.rpm > openoffice.org-style-gnome-1.1.0-16.9.EL.i386.rpm Perhaps try the following regexp. import sre reg = sre.compile( r''' (?P ^[-\w]+ # name is the match in our string which can consist of # nearly everything (\.\D[-\w]+?)?) # if it contains a point it is followed by a non-digit char # we search till we find - # a hyphen (?P \d+[-.]\d+ # version always starts with one or more digits a hyphen or a point # and one or more digits .*) # we grab everything else till \. # we find a point (?P .+?)# arch is the shortest everything between .rpm and the point \.rpm$''' , sre.X) In an interactive session I get (with names being a list with the names of the rpms): , | >>> for name in names: | m = reg.search(name) | print m.groupdict() | ... ... ... | {'version': '4.3.0-78.EL', 'arch': 'i386', 'name': 'XFree86-ISO8859-15-75dpi-fonts'} | {'version': '3.2.3d-12', 'arch': 'i386', 'name': 'xfig'} | {'version': '3-4', 'arch': 'noarch', 'name': 'rhel-ig-ppc-multi-zh_tw'} | {'version': '5.42a-0.rhel3', 'arch': 'noarch', 'name': 'perl-DateManip'} | {'version': '1.1.0-16.9.EL', 'arch': 'i386', 'name': 'openoffice.org-style-gnome'} ` I'm not sure about the version of perl-DateManip; you didn't include the trailing 'rhel3'. Did you forget it or should that be trimmed? But it shouldn't be too complicated to augment the above regexp in that way if needed. Karl -- Please do *not* send copies of replies to me. I read the list ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with regexps/filename parsing
On 31 Jan 2005, [EMAIL PROTECTED] wrote: > > Slight correction which I realized after sending, see below for > version/release seperation, which I should have seen but blame lack of > sleep ;-) > corrected versions: > 4.3.0 > 3.2.3d > 3 > 5.42a > 1.10 > > (new) releases: > 78.EL > 12 > 4 > 0 > 16.9.EL > > >> arches: >> i386, >> i386, >> noarch, >> noarch, >> i386 The regexp for the above could be: reg = sre.compile( r''' (?P ^[-\w]+ # name is the match in our string which can consist of # nearly everything (\.\D[-\w]+?)?) # if it contains a point it is followed by a non-digit char # we search till we find -# a hyphen (?P \d+(\.\w+)*) # a version consists of digits and points # we search till we find -# a hyphen (?P [\d.]+(EL)?) # release consists of digits seperated by a point and ends # optionally with EL \.(\w*\.)? # no comes a point and optionally a string (?P \w+?)# arch is the shortest everything between .rpm and the point \.rpm$''' , sre.X) , | >>> for name in names: | m = reg.search(name) | print m.groupdict() | ... ... ... | {'release': '78.EL', 'version': '4.3.0', 'arch': 'i386', 'name': 'XFree86-ISO8859-15-75dpi-fonts'} | {'release': '12', 'version': '3.2.3d', 'arch': 'i386', 'name': 'xfig'} | {'release': '4', 'version': '3', 'arch': 'noarch', 'name': 'rhel-ig-ppc-multi-zh_tw'} | {'release': '0', 'version': '5.42a', 'arch': 'noarch', 'name': 'perl-DateManip'} | {'release': '16.9.EL', 'version': '1.1.0', 'arch': 'i386', 'name': 'openoffice.org-style-gnome'} | >>> ` Karl -- Please do *not* send copies of replies to me. I read the list ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] TypeError: can only concatenate list (not "str") to list
You can also do... Umm, if you're going to make nmr and pbr the values you're printing, why are you printing the values? Nevermind, look at this instead. BTW, aren't rows the horizontal things on tables? nmr = nmrows[i] pbr = cols[0] print "%s\t%s" % (nmr,pbr) >nmr = nmrows[i] pbr = cols[0] print nmrow[i] +'\t'+cols[0] nmr = str(nmrows[i]) pbr = cols[0] print nmrow[i]+'\t'+cols[0] will print what you want. k --- Srinivas Iyyer <[EMAIL PROTECTED]> wrote: Hello group, I am trying to print rows from two lists together: how can i deal with TypeError' where i have to print a list and a string. for line in pb: # tab delim text with 12 columns cols = line.split('\t') temp_seq = cols[7].split('\n') # extract 7thcol seq = temp_seq[0].split(',') #splitting it by , for nm in seq: for i in range(len(nmrows)): if nm == nmrows[i][0] and nmrows[i][3] < cols[4] and nmrows[i][4] > cols[5]: nmr = nmrows[i] pbr = cols[0] print nmrow[i] +'\t'+cols[0] I tried the following also : I created an empty list outside for loop and tried to extend the elements of the list and string nmr = nmrows[i] pbr = cols[0] result.extend(nmr+'\t'+pbr) # result is the list i created. nmr is a list, and pbr is a string. can any one plaease help. thanks Srini __ Do you Yahoo!? The all-new My Yahoo! - Get yours free! http://my.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor __ Do you Yahoo!? Yahoo! Mail - 250MB free storage. Do more. Manage less. http://info.mail.yahoo.com/mail_250 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Better structure?
I think this thing is screaming for better structure, but previous attempts at using oop for it have failed. I think Derintegral is okay, I'm focusing on FunctionGrapher5.py--but you can comment on both. (To Johan Nilsson: I haven't had time to implement Simpson's rule instead of Reimann's sum yet... but I have gotten it to work faster anyway.) I will probably expand the code yet... Add extra things like find area between curve and x axis in interval [a,b]... Any suggestions are greatly appreciated. If you want the code to work on your machine, you'll need to have my Derintegral.py sys.path, obviously. Start of FunctionGrapher5.py ### from __future__ import division from visual import * import Derintegral import os, random from math import * ja = 0 scenexdefault = 375 def start(): for objects in scene.objects: objects.visible = 0 scene.title = "Function Grapher by Jacob, Inc." scene.x = scenexdefault scene.visible=1 scene.exit=0 scene.userspin = 0 scene.range=(10,10,1) scene.background=(1,1,1) global xaxis global yaxis xaxis = curve(pos=[(100,0,0),(-100,0,0)],color=color.black) yaxis = curve(pos=[(0,100,0),(0,-100,0)],color=color.black) global radiusaxis global radiusaxis2 radiusaxis = curve(pos=[(-100,-100),(100,100)],color=color.black) radiusaxis2 = curve(pos=[(-100,100),(100,-100)],color=color.black) radiusaxis.visible = 0 radiusaxis2.visible = 0 start() d = 1 print """\ List of Commands: clear quit remove lines return lines gotl # (Graph One Tangent Line) w/optional x coordinate gatl # (Graph All Tangent Lines) w/optional step gonl # (Graph One Normal Line) w/optional x coordinate ganl # (Graph All Normal Lines) w/optional step Function Syntax: [y,x,or r] = function [range] ["s" followed by float for step] Brackets mean that it's not required. So, in effect, you don't have to type a function """ def graphit(type,f,range2,step): li = curve(color=color.blue) if type in ['y','x']: x = -15 radiusaxis.visible = 0 radiusaxis2.visible = 0 while -15 <= x <= 15: if eval(range2): try: a = f(x) if -15 <= a <= 15: if type == 'y': li.append(pos=(x,a,0)) elif type == 'x': li.append(pos=(a,x,0)) else: li = curve(color=color.blue) except: pass else: li = curve(color=color.blue) x = x+step elif type == 'r': exec "def m(t): return f(t)*cos(t)" exec "def n(t): return f(t)*sin(t)" t = 0 while 0 <= t <= 10*pi: if eval(range2): try: li.append(pos=(m(t),n(t),0)) except: li = curve(color=color.blue) t = t+step print 'Please type in functions in below. ' while 1: lists=[] y = raw_input(">") if y == 'clear': scene.visible=0 start() print "-"*36 continue elif y == 'quit': scene.visible = 0 del scene break elif y == 'remove lines': a = [radiusaxis,radiusaxis2,xaxis,yaxis] for x in a: x.visible = 0 d = 0 continue elif y == 'return lines': a = [radiusaxis,radiusaxis2,xaxis,yaxis] for x in a: x.visible = 1 d = 1 continue elif y.startswith('gatl'): try: step2 = float(y.lstrip("gatl ")) except: step2 = 0.5 x = -20 while -20 <=x<= 20: try: der = Derintegral.diffatpt(f,x) if abs(der)<=25: if type == 'y': curve(pos=[(-15,eval("der*(-15-x)+f(x)")),(15,eval("der*(15-x)+f(x)"))],color=color.red) else: curve(pos=[(eval("der*(-15-x)+f(x)"),-15),(eval("der*(15-x)+f(x)"),15)],color=color.red) except: pass x = x + step2 continue elif y.startswith('ganl'): try: step2 = float(y.lstrip("ganl ")) except: step2 = 0.5 x = -20 while -20 <=x<= 20: try: der = Derintegral.diffatpt(f,x) if abs(der)<=25: if type == 'y': curve(pos=[(-15,eval("(-1/der)*(-15-x)+f(x)")),(15,eval("(-1/der)*(15-x)+f(x)"))],color = color.red) else: curve(pos=[(eval("(-1/der)*(-15-x)+f(x)"),-15),(eval("(-1/der)*(15-x)+f(x)"),15)],color = color.red) except: pass x = x + step2 continue elif y.startswith('gotl'): try: x = float(y.lstrip('gotl ')) except: x = float(raw_input('What x coordinate do you want the tangent line at? ')) der = Derintegral.di
RE: [Tutor] Diffing two files.
Thanks, So simple...DAA just do an equivalency on the list...no need to do sets or step through each line. John -Original Message- From: Kent Johnson [mailto:[EMAIL PROTECTED] Sent: Saturday, January 29, 2005 06:05 Cc: Tutor@python.org Subject: Re: [Tutor] Diffing two files. OK, that is clear. diffutils is probably overkill. A simple loop to accumulate the lines of interest should work. Here is some untested (!) code that may do what you want :-) def getCommonPart(filePath): ''' Get a list containing all the lines of a file that fall between the start and end lines. The returned list does not include the actual start and end lines. If start is not found, returns None. If end is not found, returns the lines after start. ''' start = '-Beginning flag\n' end = '-Ending flag\n' common = None # This will be the list of lines, also a flag of whether start has been seen for line in open(filePath): if common is None and line == start: common = [] elif line == end: break else: common.append(line) return common # Now it's easy to compare the two files: lines1 = getCommonPart(file1) lines2 = getCommonPart(file2) if lines1 != lines2: # Do what you need to do in case of a mismatch... # If you want details of the differences then you might want to use difflib here Kent Ertl, John wrote: > Kent > > What I need to do is find what should be common and see if it really is. I > have two output files...The output files will have a bunch of systems stuff > then the text of interest and then a bunch more systems stuff. The systems > stuff may be different for each file but the text of interest will always > have a fixed line in front of it and behind it. > > The idea is to get the text of interest (using the known beginning and > ending flags in the text) from each file and then check to make sure the > text of interest is the same in both files. > > I have not done much text stuff so this is new territory for me. I will > take a look at difflib. > > Thanks again > > John Ertl > > Simplified example of a text files. > > Sldfsdf > Sdfsdfsf > Sdfsdfsdfwefs > Sdcfasdsgerg > Vsadgfasgdbgdfgsdf > -Beginning flag > This > Text > Should be > The > Same in the other file. > -Ending flag > Sdfsdfsdfsd > Sdfsdfsdfasd > Sdfsadfsdf > Sdfsadfasdf > Sdfsdfasd > Sdfasdf > s > > > -Original Message- > From: Kent Johnson [mailto:[EMAIL PROTECTED] > Sent: Friday, January 28, 2005 15:23 > Cc: Tutor@python.org > Subject: Re: [Tutor] Diffing two files. > > You don't really say what you are trying to accomplish. Do you want to > identify the common text, or > find the pieces that differ? > > If the common text is always the same and you know it ahead of time, you can > just search the lines > of each file to find it. > > If you need to identify the common part, difflib might be useful. There is > an example on this page > of finding matching blocks of two sequences: > http://docs.python.org/lib/sequencematcher-examples.html > > In your case the sequences will be lists of lines rather than strings (which > are sequences of > characters) > > Kent > > Ertl, John wrote: > >>All, >> >>I have two text files that should contain a section of text that is the >>same. Luckily the section of text has a defined beginning and end. It >>looks like the most straightforward thing would be to read the targeted > > text > >>from each file (only 50 lines or so) into lists and then compare the > > lists. > >>I would think I could use sets to find a unique list (hopefully there > > would > >>not be anything)...or I could do line by line comparison. Any advise on >>what is the better method. Should I avoid the list comparison > > approach...is > >>there a built in way of comparing entire files instead of dealing > > explicitly > >>with the lines? >> >>Thanks, >> >>John Ertl >>___ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ 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] Newbie struggling with Tkinter/canvas tags
On Mon, 2005-01-31 at 12:34, Kent Johnson wrote: > Kent Johnson wrote: > > Note that Python 2.4 has set built-in with the name 'set'. To be > > compatible with both you could write > > try: > > set > > except NameError: > > from sets import Set as set > > Clarification: you don't _have_ to do this to be compatible with 2.4. The sets module is in both 2.3 > and 2.4. The difference in 2.4 is that set is also a built-in data type implemented in C with the > same interface as sets.Set. The code above will take advantage of the built-in set if it is > available, otherwise use sets.Set. > In 2.4 I tried 'from sets import set' Traceback (most recent call last): File "/home/glen/set4.py", line 1, in -toplevel- from sets import set ImportError: cannot import name set It did allow 'from sets import *' but when using the set command I got some odd output... from sets import * a=[12,54,67,47,98,76] b=[47,54] print set(a)-set(b) >>> set(['dog','sheep,'cow']) set([76, 98, 67, 12]) >>> It seems to save the output from the last use, and reproduces it later, even after a system reboot I got the same output. Using the inbuilt commands works fine. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Newbie struggling with Tkinter/canvas tags
On Mon, 2005-01-31 at 09:06, Danny Yoo wrote > > Here's a small example with sets to make it more clear how this set > manipulation stuff will work: > > ### > >>> from sets import Set > >>> numbers = range(20) > >>> primes = [2, 3, 5, 7, 11, 13, 17, 19] > >>> Set(numbers) - Set(primes) > Set([0, 1, 4, 6, 8, 9, 10, 12, 14, 15, 16, 18]) > ### Thanks Danny, sets work great (inbuilt for 2.4) I'd never heard of them before today. I look forward to finding other uses for them. Now I've just got to work out how to tag a list of id's... There doesn't seem to be a way to tag a known id, it has to be tagged by reference from an id above or below which seems odd! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] How to sum rows and columns of a matrix?
Hi all of you, I'm representing a 4x4 matrix as a 16-element list, e.g. m=range(16) first 4 elements first row, second four elements second row etc. I want to sum rows and columns like i-th row: sum(m[4*i:4*i+4]) and ith column: sum(m[i::4]) This seems to be slow because of the formation of the slices. I wonder if there is a way using generators or generator-expressions (which I didn't study yet) to compute these sums without copying parts of the matrix to a new list. (I'd guess that there should exist some canonical generator for sequences, which produces their elements ..., maybe also for slices ?) All comments, hints, solutions are welcome. Regards, Gregor -- Gregor Lingl Reisnerstrasse 3/19 A-1030 Wien Telefon: +43 1 713 33 98 Mobil: +43 664 140 35 27 Autor von "Python für Kids" Website: python4kids.net ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to sum rows and columns of a matrix?
There's a specific package for arrays http://www.stsci.edu/resources/software_hardware/numarray that implements array mathematics. I use it for pixel map manipulation in pygame, so it's relatively fast. On Mon, 31 Jan 2005 19:09:59 +0100, Gregor Lingl <[EMAIL PROTECTED]> wrote: > Hi all of you, > > I'm representing a 4x4 matrix as a 16-element list, e.g. > > m=range(16) > > first 4 elements first row, second four elements second row etc. > I want to sum rows and columns like > > i-th row: > > sum(m[4*i:4*i+4]) > > and ith column: > > sum(m[i::4]) > > This seems to be slow because of the formation of the slices. > I wonder if there is a way using generators or generator-expressions > (which I didn't study yet) to compute these sums without copying > parts of the matrix to a new list. (I'd guess that there should exist > some canonical generator for sequences, which produces their elements > ..., maybe also for slices ?) > > All comments, hints, solutions are welcome. > > Regards, > Gregor > > -- > Gregor Lingl > Reisnerstrasse 3/19 > A-1030 Wien > > Telefon: +43 1 713 33 98 > Mobil: +43 664 140 35 27 > > Autor von "Python für Kids" > Website: python4kids.net > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Better structure?
> def start(): lots of lines... > global xaxis > global yaxis Its traditional to put global statements at the top of the function. Also you only need one line to list all of the global variables > global radiusaxis > global radiusaxis2 Similarly here., and again you can put all four in one place. > radiusaxis2.visible = 0 And since there is no input parameter and no return statement and you only call start() once... > start() Why bother with defining a function? Just put all the code inline and omit the globals and it will be the same... but better is probably to jkeep the function and use if __name__ == '__main__; start() > def graphit(type,f,range2,step): > li = curve(color=color.blue) > if type in ['y','x']: > x = -15 > radiusaxis.visible = 0 > radiusaxis2.visible = 0 > while -15 <= x <= 15: > if eval(range2): > try: > a = f(x) > if -15 <= a <= 15: > if type == 'y': > li.append(pos=(x,a,0)) > elif type == 'x': > li.append(pos=(a,x,0)) > else: > li = curve(color=color.blue) > except: > pass This is iffy. If *anthing* happens you ignore it. Now suppose due to a bug you go into an infinite loop and you try to stop using CTRL-C - it won't work! If you must use a catch-all except then do something with it - print a message at least! I got a sore head after that... I'll leave the rest for others to remark upon. :-) Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Newbie struggling with Tkinter/canvas tags
On Mon, 2005-01-31 at 18:20, Kent Johnson wrote: > > In 2.4 I tried 'from sets import set' > > should be 'from sets import Set' - the class in the sets module is called > Set, the builtin class is set. > I tried it as 'set' and 'Set' but got the same result > > > > Traceback (most recent call last): > > File "/home/glen/set4.py", line 1, in -toplevel- > > from sets import set > > ImportError: cannot import name set > > > > It did allow 'from sets import *' but when using the set command > > I got some odd output... > > > > from sets import * > > a=[12,54,67,47,98,76] > > b=[47,54] > > print set(a)-set(b) > > > > > > set(['dog','sheep,'cow']) > > set([76, 98, 67, 12]) > > ?? Where did the animals come from?? That's the odd output, that was from a previous set command, even after a reboot it still came out the same. Inbuilt set works fine. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Control flow
Thanks for the enthusiasm on how input/raw_input() works - my original intention was to ask a question on control flow so I didn't spend that much time testing out this piece of input code besides typing. But I did learn a lot. Thanks! Gilbert Jacob S. wrote: I noticed that too, Liam. b = input("Weather is really bad, still go out to jog? [y/n]") # Would it kill you to have whitespace in a prompt? should really be b = raw_input("Weather is really bad, still go out to jog? [y/n]") to get the effect he wants. input() doesn't only take integers, it takes valid python objects. Integers are objects, but so are lists, dictionaries, tuples, actually it takes everything, BUT!!! it trys to return a valid python object for input. So it will take a string--don't quote me on this--if you explicitly put the string in quotes. If you don't put the string in quotes, it instead searches the namespaces for that object. So say the user typed in bad_weather when the interpreter gave that prompt. Then, b == "y" evaluates true because bad_weather == "y". Did I explain it right? Or am I trying to explain something you already know? I know I get frustrated when people try to explain concepts that I already know... HTH, Jacob Schmidt < erk, to the list, to the List!> if ( bad_weather =='y' ): # ask user only if weather is bad. b = input ( "Weather is really bad, still go out to jog?[y/n]" ) if b == 'y': go_jogging() Anyone else notice that he's never gonna go jogging if the weather is bad? Unless I've got input() wrong, it only takes integers... ? Regards, Liam Clarke -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Dictionary Nesting
-Original message- From: Orri Ganel [EMAIL PROTECTED] Date: Sat, 29 Jan 2005 17:22:48 -0500 To: Kent Johnson [EMAIL PROTECTED] Subject: Re: Fwd: [Tutor] Control flow > Kent Johnson wrote: > > > Bob Gailer wrote: > > > >> At 04:43 AM 1/29/2005, Liam Clarke wrote: > >> > >>> < erk, to the list, to the List!> > >>> > >>> if ( bad_weather =='y' ): > >>># ask user only if weather is bad. > >>>b = input ( "Weather is really bad, still go out to jog?[y/n]" ) > >>>if b == 'y': > >>> go_jogging() > >>> > >>> Anyone else notice that he's never gonna go jogging if the weather > >>> is bad? > >>> Unless I've got input() wrong, it only takes integers... ? > >> > >> > >> > >> From the docs: > >> input( [prompt]) > >> Equivalent to eval(raw_input(prompt)). > > > > > > So, it takes more than just integers, but it won't work the way the OP > > expects: > > >>> print input('Type something: ') > > Type something: 'spam ' * 4 > > spam spam spam spam > > >>> print input('Type something: ') > > Type something: y > > Traceback (most recent call last): > > File "", line 1, in ? > > File "", line 0, in ? > > NameError: name 'y' is not defined > > - because eval('y') looks for a variable named y > > > > >>> print input('Type something: ') > > Type something: 'y' > > y > > > > It works with the quotes - it is evaluating a string literal > > > > raw_input() would work better. > > > > Kent > > > > ___ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > Or you could just define a variable y and a variable n which equal "y" > and "n", respectively. Using raw_input() is probably easier though. > > -- > Email: singingxduck AT gmail DOT com > AIM: singingxduck > Programming Python for the fun of it. > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor Hi, If I want to put a dictionary in a dictionary, does the syntax for assigning and getting at the stuff in the inner dictionary look something like this: outer_dictionary[inner_dictionary][key] = 'value' ? Thanks. Jim ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Newbie struggling with Tkinter/canvas tags
> Now I've just got to work out how to tag a list of id's... There > doesn't seem to be a way to tag a known id, it has to be tagged by > reference from an id above or below which seems odd! Hi Glen, Have you tried the addtag_withtag() method? It looks like it should be able to do what you're thinking of. The documentation here: http://tkinter.unpythonic.net/pydoc/Tkinter.Canvas.html should talk about addtag_withtag(). ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Newbie struggling with Tkinter/canvas tags
Danny Yoo wrote: Now I've just got to work out how to tag a list of id's... There doesn't seem to be a way to tag a known id, it has to be tagged by reference from an id above or below which seems odd! Hi Glen, Have you tried the addtag_withtag() method? It looks like it should be able to do what you're thinking of. The documentation here: http://tkinter.unpythonic.net/pydoc/Tkinter.Canvas.html should talk about addtag_withtag(). itemconfig() also looks promising. http://www.pythonware.com/library/tkinter/introduction/x2017-concepts.htm Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Nesting
jhomme wrote: Hi, If I want to put a dictionary in a dictionary, does the syntax for assigning and getting at the stuff in the inner dictionary look something like this: outer_dictionary[inner_dictionary][key] = 'value' > ? If inner_dictionary is the key to outer_dictionary, then that is right. For example, Create the outer dict: >>> outer = {} Create an inner dict: >>> outer['outerkey'] = {} Add a key/value pair to the inner dict >>> outer['outerkey']['innerkey'] = 'myvalue' >>> outer {'outerkey': {'innerkey': 'myvalue'}} Retrieve the inner dict: >>> outer['outerkey'] {'innerkey': 'myvalue'} Retrieve an entry from the inner dict: >>> outer['outerkey']['innerkey'] 'myvalue' setdefault() is handy here because you may not know if the inner dict has been created yet when you want to add an entry. If not, setdefault will do it for you: >>> outer.setdefault('outerkey2', {})['innerkey2'] = 'anotherValue' >>> outer {'outerkey2': {'innerkey2': 'anotherValue'}, 'outerkey': {'innerkey': 'myvalue'}} If the inner dict is there already setdefault will use it: >>> outer.setdefault('outerkey2', {})['innerkey3'] = 'yetAnotherValue' >>> outer {'outerkey2': {'innerkey2': 'anotherValue', 'innerkey3': 'yetAnotherValue'}, 'outerkey': {'innerkey': 'myvalue'}} Kent Thanks. Jim ___ 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] Dictionary Nesting
> If I want to put a dictionary in a dictionary, does the syntax > for assigning and getting at the stuff in the inner dictionary > look something like this: outer_dictionary[inner_dictionary][key] = 'value' Yes. Sometimes it's easier with Python to just try it at the >>> prompt rather than ask the question... >>> d1 = {'a':1,'b':2} >>> d2 = {'alpha':d1, 'beta': {'c':3,'d':4}} >>> print d2['alpha']['a'] 1 >>> d2['beta']['d'] = 42 >>> print d2['beta']['d'] 42 HTH, Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to sum rows and columns of a matrix?
Gregor Lingl wrote: Hi all of you, I'm representing a 4x4 matrix as a 16-element list, e.g. m=range(16) first 4 elements first row, second four elements second row etc. I want to sum rows and columns like i-th row: sum(m[4*i:4*i+4]) and ith column: sum(m[i::4]) This seems to be slow because of the formation of the slices. I wonder if there is a way using generators or generator-expressions (which I didn't study yet) to compute these sums without copying parts of the matrix to a new list. (I'd guess that there should exist some canonical generator for sequences, which produces their elements ..., maybe also for slices ?) All comments, hints, solutions are welcome. Regards, Gregor The way I usually handle this is to have a 2-d array, such that every list within the main list is a row: >>> m = list(range(4) for i in range(4)) >>> m [[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]] >>> m[0][0] = 1 >>> m [[1, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]] >>> m = [range(4) for i in range(4)] >>> m [[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]] >>> m[0][0] = 1 >>> m Either of the above works. Then, to some a row, you just do this: >>> m [[1, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]] >>> sum(m[0]) 7 -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Traffic Network simulator
Hi, I need a traffic network simulator(for roads) for my project work.I would prefer the simulator to be in python so that i can reprogram/modify it according to my needs. does anyone know where i can find something of the sort or are there any special modules available which can help me build one? Shitiz __ Do you Yahoo!? All your favorites on one personal page Try My Yahoo! http://my.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Newbie struggling with Tkinter/canvas tags
> > Have you tried the addtag_withtag() method? It looks like it should be > > able to do what you're thinking of. The documentation here: > > > > http://tkinter.unpythonic.net/pydoc/Tkinter.Canvas.html > > > > should talk about addtag_withtag(). > > itemconfig() also looks promising. > > http://www.pythonware.com/library/tkinter/introduction/x2017-concepts.htm > Thanks Danny and Kent, I see it now. With so many options on offer it's easy to miss the obvious. All of this new information should keep me occupied for quite some time. Thanks again. Glen ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Comparing files, Counting Value
Hello all, I'm very new to Python and have been trying to write a script to compare data from 2 files and getting a total. One of the two files contains x, y positions of pixels and a color value(z) of each, so it has three columns in the file. The other file has two columns; x1, y1. I'd like to get only x, y positions which match to x1, y1 of the second file and then look up the z value. If the z value is greater than a certain number, it counts 1, otherwise it moves on the next x, y position. Finally, I'm able to get total count of the pixels that are over the threshold. The script I'm using is below step by step, however, I haven't been able to figure out the error massage "IndexError: list index out of range" on z value. Any comments would be appreciated! Regards, Michiyo file 1: file 2: 299 189 8.543e-02 260 168 300 189 0.000e+00 270 180 301 189 0.000e+00 299 189 302 189 0.000e+00 300 170 0188 5.095e-02 301 189 1188 5.108e-02. . . . . . . . . . .. #!usr/local/bin/python import sys i=open("file 1") #value data o=open("file 2") #look-up file l=open("result", 'w')#result results={} line=i.readline() line=o.readline() while line: fields=line.split() x1=fields[0, 1] in i#x,y position in file 1 z=fields[2] in i #value data in file 1 x2=fields[0, 1] in o #x,y position in file 2 if x1 == x2: read(z) if z >= 5.000e-02: z=1 count(n=0) print>>l, count(1) i.close() o.close() l.close() ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] carriage return on windows
Orri Ganel wrote: Jacob S. wrote: Thanks Kent and Max! Wow, I didn't know it did that. I'm too dumb to figure it out on my own I guess... Oh well! I found a cool new thing to play with at least! Thanks, Jacob On Jan 30, 2005, at 02:40, Jacob S. wrote: I don't think that's what he wants. I think he wants to *overwrite* what's in the shell with new output. For example. so that the whole line is overwritten. In my experience, this is not possible and if anyone can show me how to do it, I would be grateful. HTH, Jacob It *is* possible, that's exactly what my code does (well, as long as you don't run it on Mac OS 9). The carriage return (\r, as opposed to the linefeed \n) moves the cursor to the beginning of the *current* line. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor Just a note: This does not work on IDLE, so for those who try this and are frustrated when it fails, try it in the dos-box (command prompt). I played around with this output issue and I love the way it works. Now, how do you do this in *nix? I tried the same approach and I get a blank line for 5 seconds (or whatever number of cycles you have on your example) and the a final line with the last value of the iterable. Do you happen to know how this in done? Thanks. Victor worked around this problem and I love the solution. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Comparing files, Counting Value
Michiyo, When you ask a question to the list, you should be more careful to highlight your problem so that it doesn't seem like you're asking people to write a script for you. I don't think that's what you were doing, but just try to reduce your problem to a minimal example in the future. I don't know what your script is doing; array[0, 2] is not legal as far as I know in python (it is legal on numarray.array types, but not on regular python lists AFAIK). I also don't know what that "in i" stuff you're doing means. When I run your code, I get a "TypeError: list indices must be integers" on the fields[0, 1] line. You should try to write your code in small bites to make it easier to debug. That said, I dig doing this sort of text processing, so I wrote my own script to do it. Perhaps it'll help clear up some ideas for you; if you have any questions, feel free to ask me about them: ==begin file testprocess.py= one = open('one') two = open('two') out = open('out', 'w') THRESHOLD = .05 #build dict of {(x,y): z} from 'one' pts = {} for line in one: x, y, z = [float(i) for i in line.split()] #convert strings to floats pts[(x,y)] = z #insert point into dictionary #now check to find each pixel in 'two' in the pts dictionary bigpixels = 0 for line in two: x, y = [float(i) for i in line.split()] #convert strings to floats if (x,y) in pts and pts[(x,y)] > THRESHOLD: bigpixels += 1 print "%d pixels over %f" % (bigpixels, THRESHOLD) end file== Peace Bill Mill bill.mill at gmail.com On Mon, 31 Jan 2005 15:27:24 -0800, Michiyo LaBerge <[EMAIL PROTECTED]> wrote: > Hello all, > > I'm very new to Python and have been trying to write a script to > compare data from 2 files and getting a total. One of the two files > contains x, y positions of pixels and a color value(z) of each, so it > has three columns in the file. The other file has two columns; x1, y1. > I'd like to get only x, y positions which match to x1, y1 of the second > file and then look up the z value. If the z value is greater than a > certain number, it counts 1, otherwise it moves on the next x, y > position. Finally, I'm able to get total count of the pixels that are > over the threshold. The script I'm using is below step by step, > however, I haven't been able to figure out the error massage > "IndexError: list index out of range" on z value. Any comments would be > appreciated! > > Regards, > Michiyo > > file 1: file 2: > 299 189 8.543e-02260 > 168 > 300 189 0.000e+00270 > 180 > 301 189 0.000e+00299 > 189 > 302 189 0.000e+00300 > 170 >0188 5.095e-02 301 > 189 >1188 5.108e-02 . > . >.. . > . . >.. . > .. > > #!usr/local/bin/python > > import sys > > i=open("file 1") #value data > o=open("file 2") #look-up file > l=open("result", 'w')#result > > results={} > > line=i.readline() > line=o.readline() > > while line: > fields=line.split() > x1=fields[0, 1] in i#x,y position in file 1 > z=fields[2] in i #value data in file 1 > x2=fields[0, 1] in o #x,y position in file 2 > > if x1 == x2: > read(z) > > if z >= 5.000e-02: >z=1 >count(n=0) >print>>l, count(1) > > i.close() > o.close() > l.close() > > ___ > 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] Traffic Network simulator
Hi, Don't know if there's any network simulator. But I know about SimPy: http://simpy.sourceforge.net/ Looks well documented. Check the examples, it seems you can do pretty robust things with not toomuch code. I readed about it in the charming python section of IBM developers works: http://www-106.ibm.com/developerworks/linux/library/l-simpy.html?dwzone=linux Check also the SimPy Wiki: http://www.mcs.vuw.ac.nz/cgi-bin/wiki/SimPy?SimPy Enjoy, Guille On Mon, 31 Jan 2005 14:50:34 -0800 (PST), Shitiz Bansal <[EMAIL PROTECTED]> wrote: > Hi, > > I need a traffic network simulator(for roads) for my > project work.I would prefer the simulator to be in > python so that i can reprogram/modify it according to > my needs. > does anyone know where i can find something of the > sort or are there any special modules available which > can help me build one? > > Shitiz > > > __ > Do you Yahoo!? > All your favorites on one personal page â Try My Yahoo! > http://my.yahoo.com > ___ > 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] carriage return on windows
Victor Rex wrote: I played around with this output issue and I love the way it works. Now, how do you do this in *nix? I tried the same approach and I get a blank line for 5 seconds (or whatever number of cycles you have on your example) and the a final line with the last value of the iterable. It sounds like the '\r' is erasing the line, not just moving the cursor. Try putting the '\r' at the beginning of the output rather than the end: for i in range(10): print '\r', 'i is', i time.sleep(1) Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Comparing files, Counting Value
Hi Michiyo, Ok, let's take a look at the code. > i=open("file 1") #value data > o=open("file 2") #look-up file > l=open("result", 'w')#result We strongly recommend renaming these names to ones that aren't single characters. It's difficult to tell here what 'i', 'o', and 'l' mean, outside of the context of the assignments. The letters 'i' and 'o' often stand for the words "input" and "output". The way that you're using these as variable names for input files will break the expectation of people who read the code. Futhermore, 'l' can easily be misread as 'i'. In short, those names should be changed to something readable. This is a pure style issue, but I think it's important as programmers to make the code easy for humans to understand. > results={} > > line=i.readline() > line=o.readline() This looks problematic. The 'line' name here, by the end of these two statements, is bound to the value of the look-up file's line. I believe you need to keep those values distinct. > while line: > fields=line.split() > x1=fields[0, 1] in i#x,y position in file 1 > z=fields[2] in i #value data in file 1 > x2=fields[0, 1] in o #x,y position in file 2 There are several fundamental issues with this. Conventionally, a file-loop has the following structure: ### for line in inputFile: # ... do something with that line ### and anything that tries to iterate across a file in a different way should be looked at with some care. The way that your code is trying to iterate across the file won't work. We strongly recommend you read through a tutorial like: http://www.freenetpages.co.uk/hp/alan.gauld/tutfiles.htm which has examples of how to write programs that work with files. The way the program's structured also seems a bit monolithic. I'd recommend breaking down the problem into some phases: Phase 1: read the value-data file into some data structure. Phase 2: taking that data structure, read in the lookup file and identify which positions are matching, and record matches in the output file. This partitioning of the problem should allow you to work on either phase of the program without having to get it correct all at once. The phases can be decoupled because we can easily feed in some kind of hardcoded data structure into Phase 2, just to check that the lookup-file matching is doing something reasonable. For example: ### hardcodedDataStructure = { (299, 189) : 8.543e-02, (300, 189) : 0.000e+00, (301, 189) : 0.000e+00, (1, 188) : 5.108e-02 } ### is a very small subset of the information that your value data contains. We can then take this hardcodedDataStructure and work on the second part of the program using 'hardcodedDataStructure'. Later on, when we do get Phase 1 working ok, we can use the result of Phase 1 instead of the hardcodedDataStructure, and it should just fit into place. Does this make sense? Don't try writing the program all at once and then start trying to make it all work. But instead, try building small simple programs that do work, and then put those together. The statements: > fields=line.split() > x1=fields[0, 1] in i#x,y position in file 1 won't work. 'fields[0, 1]' does not represent the first and second elements of 'fields': it means something else, but you should get errors from it anyway. For example: ### >>> values = ["hello", "world", "testing"] >>> values[0, 1] Traceback (most recent call last): File "", line 1, in ? TypeError: list indices must be integers ### So you should have already seen TypeErrors by this point of the program. What you probably meant to write was: ### fields = line.split() x1 = (fields[0], fields[1]) ### Alternatively: ### fields = line.split() x1 = fields[0:1] ### The significance of accidentely using the comma there won't make too much sense until you learn about tuples and dictionaries, so I won't press on this too much. I'd recommend that you read through one of the Python tutorials before trying to finishing the program. Some of the things that your program contains are... well, truthfully, a little wacky. There are several good tutorials linked here: http://www.python.org/moin/BeginnersGuide/NonProgrammers If you have more questions, please feel free to ask! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Better structure?
On Mon, 31 Jan 2005, Jacob S. wrote: > I think this thing is screaming for better structure, but previous attempts > at using oop for it have failed. Hi Jacob, Ok, I see one big refactoring that should help things quite a bit. There's a large case-analysis off if/elif/elif statements that involves 'y'. Let me just grep for the lines here: > if y == 'clear': > elif y == 'quit': > elif y == 'remove lines': > elif y == 'return lines': > elif y.startswith('gatl'): > elif y.startswith('ganl'): > elif y.startswith('gotl'): > elif y.startswith('gonl'): > elif y.startswith('getpt'): > elif y == 'regraph': The structure can be improves by using that dispatch-table method we talked about a few days ago. We can't directly apply the dispatch technique, because there's a little bit of nonuniformity. Some of the statements compare y by equality, while others use 'startswith' checks. But I think we can handle it by making everything a little bit more uniform: we can make everything an 'equality' check against the first word on the line. Here's some pseudocode for the proposed fix: ### Pseudocode commandDispatchTable = {'clear' : clearCommand 'quit' : quitCommand 'remove' : removeCommand 'return' : returnCommand 'gatl' : gatlCommand 'ganl' : ganlCommand 'gotl' : gotlCommand 'gonl' : gonlCommand 'getpt' : getplCommand 'regraph': regraphCommand def evaluate(line): """Evaluates the line.""" pieces = line.split() cmd, rest = pieces[0], pieces[1:] if cmd in commandDispatchTable: dispatchTable[cmd](rest) elif isAssignment(line): ... else: ... ### The evaluate() function tries to handle the common-case stuff with a dispatch-table method, and otherwise follows up with special-case stuff to handle the rest of the case analysis. One other neat feature of this is that, because we split() against the whole line, we've broken down the line into 'cmd' and the 'rest' of the arguments to that command. This might also help clean up some of the logic that grabbing the argument on the rest of the line, step2 = float(y.lstrip("gatl ")) x = float(y.lstrip('gotl ')) x = float(y.lstrip('gonl ')) y = y.lstrip("getpt ") You can avoid doing so many lstrip()s by using the 'rest' argument list. Best of wishes to you! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Presentation
I am trying to get Python established here in the Philippines. Currently I am in charge of operations at a business based in Manila and I have asked my IT staff to start using Python (with some success). A local university has now asked that I give a talk to their IT people on Python - so here is an opportunity to spread the word and get some more converts and maybe introduce python into their computer science courses. Any help I can get would be much appreciated - such as language comparisons, companies and systems that use python, debates about what python is good for (almost everything), examples of elegant code.. When I was a member of the Forth Interest Group in the USA we learned that Forth was used on the buggy that went to mars, that it started life controlling huge radio telescopes which only had 4k (yes 4k) of memory for both language and application. Anything like the above concerning python would be useful. Any other suggestions would help also, the audience will have computers, so a demonstration of small workshop would also be good - the presentation/session is for 4 hours on the 10th February. Paul ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Presentation
On Feb 1, 2005, at 16:35, Paul Hartley wrote: When I was a member of the Forth Interest Group in the USA we learned that Forth was used on the buggy that went to mars, that it started life controlling huge radio telescopes which only had 4k (yes 4k) of memory for both language and application. Anything like the above concerning python would be useful. Well, that's probably not as awe-inspiring, but BitTorrent is written entirely in Python (with the wxPython graphical toolkit for the Windows and X11 versions, and PyObjC for the Mac OS X version). Google also use the language extensively, although I don't exactly know why, thanks to their obsession with secrecy. You could point out that Python's greatest strength (aside from its extreme readability -- unlike most people, The Whitespace Thing always struck me as an excellent design decision, although had I been Guido, I'd have forced the use of either tabs or spaces but not allowed both) is the fact that it's multi-paradigm. You can work procedurally, object-orientedly, and even in some cases functionally. And you can mix-and-match those 3 paradigms depending on your needs. This can be very useful. Oh, and make sure you mention iterators and list comprehensions at some point. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Presentation
On Tue, 1 Feb 2005, Paul Hartley wrote: > When I was a member of the Forth Interest Group in the USA we learned > that Forth was used on the buggy that went to mars, that it started life > controlling huge radio telescopes which only had 4k (yes 4k) of memory > for both language and application. > > Anything like the above concerning python would be useful. I just did a google on "Pyton success stories," and found this page, which you may find useful. http://www.pythonology.com/success See also the two O'Reilley links on that page. Since you mentioned use in space exploration, always a sexy example, I search for "Nasa Python" also turned up these: NASA Ames Processing in Python: http://home.badc.rl.ac.uk/astephens/software/nappy/ Space shuttle engineers use Python to streamline mission design: http://builder.com.com/5100-6401-1045764.html ... and others. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Better structure?
def start(): lots of lines... global xaxis global yaxis Its traditional to put global statements at the top of the function. Also you only need one line to list all of the global variables global radiusaxis global radiusaxis2 What, like global radiusaxis, radiusaxis2 Similarly here., and again you can put all four in one place. radiusaxis2.visible = 0 And since there is no input parameter and no return statement and you only call start() once... Not true. If y == 'clear', then start is called to "redraw" the window. Very important part. def graphit(type,f,range2,step): li = curve(color=color.blue) if type in ['y','x']: x = -15 radiusaxis.visible = 0 radiusaxis2.visible = 0 while -15 <= x <= 15: if eval(range2): try: a = f(x) if -15 <= a <= 15: if type == 'y': li.append(pos=(x,a,0)) elif type == 'x': li.append(pos=(a,x,0)) else: li = curve(color=color.blue) except: pass This is iffy. If *anthing* happens you ignore it. Now suppose due to a bug you go into an infinite loop and you try to stop using CTRL-C - it won't work! If you must use a catch-all except then do something with it - print a message at least! I think I'll do that, but of course I'll have to add ValueError -- because of math domain errors on my function. That's what the try except block is for. Otherwise I wouldn't need it. I got a sore head after that... I'll leave the rest for others to remark upon. :-) Alan G. I'd send some Advil or something, but it doesn't work too well through email. ;-) Thanks for the help, Jacob Schmidt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Traffic Network simulator
> I need a traffic network simulator(for roads) for my > project work.I would prefer the simulator to be in > python so that i can reprogram/modify it according to > my needs. I don't jnow of anything ready made. But a Google search may find someting somewhere... > does anyone know where i can find something of the > sort or are there any special modules available which > can help me build one? These kinds of simulators usually entail a set of interacting queues. There might be python modules around for building queues. You might also find a math book or web site on queuing theory useful... Also you will certainly want to use the random module for this. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Better structure?
Ah, I like. BTW, it was a few months ago, not days... but the thought still counts. At least you remember. I was getting stumped by the difference in comparing y The check for seeing what the first word is made me slamp my forehead... Thanks! Jacob Schmidt On Mon, 31 Jan 2005, Jacob S. wrote: I think this thing is screaming for better structure, but previous attempts at using oop for it have failed. Hi Jacob, Ok, I see one big refactoring that should help things quite a bit. There's a large case-analysis off if/elif/elif statements that involves 'y'. Let me just grep for the lines here: if y == 'clear': elif y == 'quit': elif y == 'remove lines': elif y == 'return lines': elif y.startswith('gatl'): elif y.startswith('ganl'): elif y.startswith('gotl'): elif y.startswith('gonl'): elif y.startswith('getpt'): elif y == 'regraph': The structure can be improves by using that dispatch-table method we talked about a few days ago. We can't directly apply the dispatch technique, because there's a little bit of nonuniformity. Some of the statements compare y by equality, while others use 'startswith' checks. But I think we can handle it by making everything a little bit more uniform: we can make everything an 'equality' check against the first word on the line. Here's some pseudocode for the proposed fix: ### Pseudocode commandDispatchTable = {'clear' : clearCommand 'quit' : quitCommand 'remove' : removeCommand 'return' : returnCommand 'gatl' : gatlCommand 'ganl' : ganlCommand 'gotl' : gotlCommand 'gonl' : gonlCommand 'getpt' : getplCommand 'regraph': regraphCommand def evaluate(line): """Evaluates the line.""" pieces = line.split() cmd, rest = pieces[0], pieces[1:] if cmd in commandDispatchTable: dispatchTable[cmd](rest) elif isAssignment(line): ... else: ... ### The evaluate() function tries to handle the common-case stuff with a dispatch-table method, and otherwise follows up with special-case stuff to handle the rest of the case analysis. One other neat feature of this is that, because we split() against the whole line, we've broken down the line into 'cmd' and the 'rest' of the arguments to that command. This might also help clean up some of the logic that grabbing the argument on the rest of the line, step2 = float(y.lstrip("gatl ")) x = float(y.lstrip('gotl ')) x = float(y.lstrip('gonl ')) y = y.lstrip("getpt ") You can avoid doing so many lstrip()s by using the 'rest' argument list. Best of wishes to you! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Traffic Network simulator
> I need a traffic network simulator(for roads) for my > project work.I would prefer the simulator to be in > python so that i can reprogram/modify it according to > my needs. Have you looked at SimPy: http://simpy.sourceforge.net/ -- Andrew McNamara, Senior Developer, Object Craft http://www.object-craft.com.au/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor