pylab, integral of sinc function
Hello, In [19]: def simple_integral(func,a,b,dx = 0.001): : return sum(map(lambda x:dx*x, func(arange(a,b,dx : In [20]: simple_integral(sin, 0, 2*pi) Out[20]: -7.5484213527594133e-08 ok, can be thought as zero In [21]: simple_integral(sinc, -1000, 1000) Out[21]: 0.99979735786416357 hmm, it should be something around pi it is a way too far from it, even with a=-1,b=1 In [22]: def ppp(x): : return sin(x)/x : In [23]: simple_integral(ppp, -1000, 1000) Out[23]: 3.1404662440661117 nice is my sinc function in pylab broken? is there a better way to do numerical integration in pylab? Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: pylab, integral of sinc function
my fault In [31]: simple_integral(lambda x:sinc(x/pi), -1000, 1000) Out[31]: 3.14046624406611 -- http://mail.python.org/mailman/listinfo/python-list
Re: pylab, integral of sinc function
[...] In [19]: def simple_integral(func,a,b,dx = 0.001): : return sum(map(lambda x:dx*x, func(arange(a,b,dx Do you mean def simple_integral(func,a,b,dx = 0.001): return dx * sum(map(func, arange(a,b,dx))) yes, this should be faster :) -- http://mail.python.org/mailman/listinfo/python-list
Re: builtin set literal
{:} for empty dict and {} for empty set don't look too much atrocious to me. this looks consistent to me -- http://mail.python.org/mailman/listinfo/python-list
Re: builtin set literal
faulkner schrieb: On Feb 14, 11:55 am, Schüle Daniel [EMAIL PROTECTED] wrote: Hello, lst = list((1,2,3)) lst = [1,2,3] t = tupel((1,2,3)) t = (1,2,3) s = set((1,2,3)) s = ... it would be nice feature to have builtin literal for set type maybe in P3 .. what about? s = 1,2,3 Regards, Daniel sets aren't quite that useful or common. just use a list. and '' and '' already have syntactic meanings. well, I thought about this the empty set has the meaning of != now as far as I remember is depricated and will disappear When they are gone in P3000, could be reused as empty set. and that would make python look more like C++, which nobody wants. I dont think that actually many people fear this. we have {} for dicts and I doubt anybody mistake them for C++ brakets. In my previuos post I forgot to mention d = dict() d = {} s = set() s = why not, on the first sight everybody will see ... here our algorithmus deals with unique things/objects ... put in a set. Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: builtin set literal
Steven Bethard schrieb: Schüle Daniel wrote: Hello, lst = list((1,2,3)) lst = [1,2,3] t = tupel((1,2,3)) t = (1,2,3) s = set((1,2,3)) s = ... it would be nice feature to have builtin literal for set type maybe in P3 .. what about? s = 1,2,3 In Python 3.0, this looks like:: s = {1,2,3} jepp, that looks not bad .. as in a mathe book. the only disadvantage I see, that one may confuse it with a dict. Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: builtin set literal
[...] In Python 3.0, this looks like:: s = {1,2,3} jepp, that looks not bad .. as in a mathe book. the only disadvantage I see, that one may confuse it with a dict. Perhaps with a very cursory inspection. But the lack of any ':' characters is a pretty quick clue-in. there is one a bigger disadvantage though {} empty set clashes with empty dict {} set() still must be used to generate the empty set or a hack like s = {None}.clear() I think something like {-} as the substitution for empty set will seem bit to perlish for most of us? :) Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
builtin set literal
Hello, lst = list((1,2,3)) lst = [1,2,3] t = tupel((1,2,3)) t = (1,2,3) s = set((1,2,3)) s = ... it would be nice feature to have builtin literal for set type maybe in P3 .. what about? s = 1,2,3 Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: pylab, matplotlib ... roots function question
Hi, [...] No, that's actually wrong. What version of numpy are you using? With a recent SVN checkout of numpy, I get the correct answer: In [3]: roots([1,0,0]) Out[3]: array([ 0., 0.]) In [17]: import sys, numpy In [18]: sys.version Out[18]: '2.5 (r25:51908, Sep 23 2006, 01:23:14) \n[GCC 4.1.1]' In [19]: numpy.version.version Out[19]: '1.0rc1' moon:/pool/PROG/python # uname -a Linux moon 2.6.16.13-4-smp #1 SMP Wed May 3 04:53:23 UTC 2006 x86_64 x86_64 x86_64 GNU/Linux I think I will get and compile newer version of source BTW, I also look for good (more or less complete and/or interessting) tutoruals on signal processing with python something like low/high-pass filtering/ploting of wave files etc I would appreciate pointers very much. I am learning this at the moment, when it all starts to make sense to me, I will write such a tutorial on my own later Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
pylab, matplotlib ... roots function question
Hello NG, given this call to roots funtion from pylab In [342]: roots([0,2,2]) Out[342]: array([-1.]) as far as I understand it [a0,a1,a2] stands for a0+a1*x+a2*x^2 in the above case it yields 2x^2+2x = 2x(1+x) and the roots are 0 and -1 I am wondering why roots function gives me only the -1 second try In [343]: roots([1,0,0]) Out[343]: array([], dtype=float64) ok, as it should be In [344]: roots([0,0,1]) Out[344]: array([], dtype=float64) here again, 0 is the root of x^2 Do I miss something important? Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
why is this different?
Hello snakes :) In [38]: f = [lambda:i for i in range(10)] In [39]: ff = map(lambda i: lambda : i, range(10)) In [40]: f[0]() Out[40]: 9 In [41]: f[1]() Out[41]: 9 In [42]: ff[0]() Out[42]: 0 In [43]: ff[1]() Out[43]: 1 I don't understand why in the first case f[for all i in 0..9]==9 what is different from (more usefull) In [44]: f = [%i % i for i in range(10)] In [45]: f Out[45]: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] doing it like this works again In [54]: def d(x): : return lambda:x : In [55]: f = [d(i) for i in range(10)] In [56]: f[0]() Out[56]: 0 In [57]: f[1]() Out[57]: 1 in a C programmer sence I would say there seems to be no sequence point which would separate now from next Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: why is this different?
Gabriel Genellina schrieb: Gabriel Genellina schrieb: On 7 dic, 22:53, Schüle Daniel [EMAIL PROTECTED] wrote: In [38]: f = [lambda:i for i in range(10)] In [39]: ff = map(lambda i: lambda : i, range(10)) In [40]: f[0]() Out[40]: 9 In [41]: f[1]() Out[41]: 9 In [42]: ff[0]() Out[42]: 0 In [43]: ff[1]() Out[43]: 1 I don't understand why in the first case f[for all i in 0..9]==9 In the first case, i is a free variable. That means that Python will get it from other place (the global namespace, likely [surely?]) f=[lambda:i for i in range(10)] f[0]() 9 i=123 f[0]() 123 print f[0].func_closure None In the second case, the inner i is a free variable, but local to its enclosing scope (outer lambda). It's a closure: ff = map(lambda i: lambda : i, range(10)) ff[4]() 4 ff[4].func_closure (cell at 0x00ACEA90: int object at 0x00995344,) i=321 ff[4]() 4 what is different from (more usefull) In [44]: f = [%i % i for i in range(10)] In [45]: f Out[45]: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] This is a simple expression evaluated at each iteration doing it like this works again In [54]: def d(x): : return lambda:x : x inside lambda is a free variable, but since it's local to d, this becomes a closure: d(1) function lambda at 0x00A35EF0 d(1).func_closure (cell at 0x00A2A4F0: int object at 0x00995338,) In [55]: f = [d(i) for i in range(10)] In [56]: f[0]() Out[56]: 0 In [57]: f[1]() Out[57]: 1 This is similar to the ff example above in a C programmer sence I would say there seems to be no sequence point which would separate now from next No, the problem is that C has no way to express a closure; this is a functional concept absolutely extraneous to the C language. On 7 dic, 22:53, Schüle Daniel [EMAIL PROTECTED] wrote: In [38]: f = [lambda:i for i in range(10)] In [39]: ff = map(lambda i: lambda : i, range(10)) In [40]: f[0]() Out[40]: 9 In [41]: f[1]() Out[41]: 9 In [42]: ff[0]() Out[42]: 0 In [43]: ff[1]() Out[43]: 1 I don't understand why in the first case f[for all i in 0..9]==9 In the first case, i is a free variable. That means that Python will get it from other place (the global namespace, likely [surely?]) f=[lambda:i for i in range(10)] f[0]() 9 i=123 f[0]() 123 print f[0].func_closure None intersting I think I got it [] I have two more examples, but now I understand the difference In [70]: x = [eval(lambda:i) for i in range(10)] In [71]: y = [eval(lambda:%i % i) for i in range(10)] I think [71] is most obvious what the programmer intends Thx -- http://mail.python.org/mailman/listinfo/python-list
how to convert a function into generator?
Hello, I came up with this algorithm to generate all permutations it's not the best one, but it's easy enough # lst = list with objects def permute3(lst): tmp = [] lenlst = len(lst) def permute(perm, level): if level == 1: tmp.append(perm) return for i in lst: if i not in perm: permute(perm + (i,), level - 1) for item in lst: permute((item,), lenlst) return tuple(tmp) now I want to make a generator from it the idea is to get each time a new permutation I don't really understand how to handle the case when my function has an inner function which has a yield statement .. I would say that the inner function becomes an generator and stopsyields the value on each yield .. but in reality I want to propogate these values to the caller of the outer function I hope you got the idea of what I mean the code is the sketch of the idea def permute3gen(lst): lenlst = len(lst) def permute(perm, level): if level == 1: yield perm return # not sure return without a value is allowed, theoretically it could be replaces with if/else block for i in lst: if i not in perm: permute(perm + (i,), level - 1) for item in lst: yield permute((item,), lenlst) # makes generator from the outer function too this is what I get In [67]: reload permute --- reload(permute) Out[67]: module 'permute' from 'permute.pyc' In [68]: p = permute.permute3gen([a,b,c,d]) In [69]: p Out[69]: generator object at 0x2af3a44795f0 In [70]: x = p.next() In [71]: y = p.next() In [72]: x Out[72]: generator object at 0x2af3a448e830 In [73]: y Out[73]: generator object at 0x2af3a448e878 In [74]: x.next() --- type 'exceptions.StopIteration' Traceback (most recent call last) /pool/PROG/python/permute/ipython console in module() type 'exceptions.StopIteration': I don't understand why the generator x raises StopIteration exception I would expect that x.next() would call permute((a,), 4) and would stop at abcd thanks in advance regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
re question
Hello all, I didn't found more appropriate news group for this question, please let me know if there is ng with regular expression as its main topic I am trying to construct a case where a greedy and non greedy operation produce different result. I dont see the difference between 'a??b' and 'a?b' As far I understand is that ? will first try to match a (it's greedy) and only if it fails then it step back and lets a unmatched. The other doesn't match a at first, only if the pattern fails to match it steps back and match a. But don't they do eventually the same thing? Can someone provide an example where 2 patterns yield different results. Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
basic questions on cmp, and sort
Hello, first question In [117]: cmp(ABC,['A','B','C']) Out[117]: 1 against what part of the list is the string ABC compared? second question In [119]: class X(object): .: pass .: In [120]: X() X() Out[120]: True In [121]: X() X() Out[121]: False In [122]: X() X() Out[122]: True In [123]: X() X() Out[123]: True In [124]: X() X() Out[124]: False class X does not implement and cmp what is this comparision is based on? third question sort([[1,2,3],[ABC],['Z','A'], X(), 4) how does python handle heterogenous items in the list in this case? first I assumed that cmp function used in sort is based on len, when the items are sequences, but this is wrong Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: simple question
Steve Holden schrieb: Maxine Weill wrote: I need to install Python Imaging Library (PIL) - imaging-1.1.5.tar.gz (source ) onto Suse Linux 10.1 system in order for (latest) Scribus 1.3.3.2 to install and work. Plesae indicate how I perform PIL install (exact commands/procedures) in manner where files are automatically placed in proper directories, etc. I though that PIL now used the standard setup system. If the package's top level directory includes a file called setup.py then just run python setup.py install if there are more versions of python installed and one wants to install for specific version then /pool/pathToMyInstalledSoftware/bin/python2.4 setup.py install /pool/pathToPetersInstalledSoftware/bin/python2.2 setup.py install this is what I figured out my 2 cents -- Daniel -- http://mail.python.org/mailman/listinfo/python-list
self question
Hi all, given python description below import random class Node: def __init__(self): self.nachbarn = [] class Graph(object): # more code here def randomizeEdges(self, low=1, high=self.n): pass graph = Graph(20) graph.randomizeEdges(2,5) I am burned by high=self.n quick test with cnt = 1 def foo(): global cnt cnt += 1 return cnt def bar(x=foo()): print x bar() # 2 bar() # 2 bar() # 2 this is not behaviour C++ programmer would expect does someone know why this kind of behaviour is/was choosen? Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: self question
[EMAIL PROTECTED] schrieb: cnt = 1 def foo(): global cnt cnt += 1 return cnt def bar(x=foo()): print x bar()# 2 bar()# 2 bar()# 2 Looks to me like you want to use the following programming pattern to get dynamic default arguments: cnt = 1 def foo(): global cnt cnt += 1 return cnt def bar(x=None): if x is None: x = foo() print x bar() # 2 bar() # 3 bar() # 4 yes, I haven't thought of that nowI changed my class to class Graph: settings = { NumNodes : 10, MinNodes : 2, MaxNodes : 5 } def randomizeEdges(self, lowhigh = (settings[MinNodes], settings[MaxNodes])): low, high = lowhigh for node in self.nodes: x = random.randint(low, high) # link the nodes maybe the only minor point is that no relationship can be expressed settings = { NumNode : 10, MinNode : settings[NumNode] / 2, MaxNode : settings[NumNode] } but I think the solution is nevertheless ok Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: self question
correction :) class Graph: settings = { NumNodes : 10, MinNodes : 2, MaxNodes : 5 } def randomizeEdges(self, lowhigh = (settings[MinNodes], settings[MaxNodes])): of course this should be Graph.settings[MinNodes], Graph.settings[MaxNodes]) -- http://mail.python.org/mailman/listinfo/python-list
re question
Hello, consider the following code re.search([a-z](?i)[a-z],AA) _sre.SRE_Match object at 0x40177e20 this gives a match if we provide an extra group for the first character it still works re.search(([a-z])(?i)[a-z],AA).group(1) 'A' it doesn't matter where (?i) is placed, right? the re engine would glance at once on the entire pattern string analize it (complain if pattern doesn't make sense, eg invalid) and it would be the same as if the option was given expicitely as re.IGNORECASE. Is there a way to switch-off the option resp. switch-on the option in the middle of the pattern? Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: array of array of float
[EMAIL PROTECTED] schrieb: i used C too much and haven't used Python for a while... like in C, if we want an array of array of float, we use float a[200][500]; now in Python, seems like we have to do something like a = [ [ ] ] * 200 and then just use a[1].append(12.34) etc but it turns out that all 200 elements points to the same list... and i have to use a = [ ] for i in range (0, 200): a.append([ ]) is there a simpler way... i wonder... a = [[] for in range(200)] -- http://mail.python.org/mailman/listinfo/python-list
Re: array of array of float
Schüle Daniel schrieb: [EMAIL PROTECTED] schrieb: i used C too much and haven't used Python for a while... like in C, if we want an array of array of float, we use float a[200][500]; now in Python, seems like we have to do something like a = [ [ ] ] * 200 and then just use a[1].append(12.34) etc but it turns out that all 200 elements points to the same list... and i have to use a = [ ] for i in range (0, 200): a.append([ ]) is there a simpler way... i wonder... a = [[] for in range(200)] correction :) a = [[] for i in range(200)] -- http://mail.python.org/mailman/listinfo/python-list
Re: delete first line in a file
Juergen Huber schrieb: Fredrik Lundh wrote: Juergen Huber wrote: ok...i thought as much, that i have to copy this file! how will i do that?! how will i fix this file = delete the first line?! with which commands could i do that?! start here: http://docs.python.org/tut/node9.html#SECTION00920 /F that documentation i have already read, but it wouldn`t help me for my problem! i know, how i can read the first line an print them on the screen! but...how can i say python, delete the first line?! thats my problem! in the entry of my posting i wrote, that i am a newbie and so please understand me, that i ask so questions?! :-) thanks for your help! simple! f = file(old.file) ignore = f.readline() file(new.file, w+).write(f.read()) hth, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: string replace
A solution could be that replace accept a tuple/list of chars, like that was add into the new 2.5 for startswith. I don't know, but can be this feature included into a future python release? I don't know, but I think it would be useful as for now I use this import re chars = re.compile(r'[abc]') text = aAbBcCdD chars.sub(,text) 'ABCdD' Thanks, Michele Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: How to control permission of file?
Grant Edwards schrieb: When one open()s a file (that doesn't exist) for writing , how does one control that file's permissions (it's mode in Unix terms). what do you mean by contor file's mode? usually you try to open and if you are not allowed you will get the exception try: ... f = file(/etc/shadow) ... print f.read() ... except IOError, e: ... print e ... [Errno 13] Permission denied: '/etc/shadow' if you want to know more about file attributes use os.stat and constants from stat module import os os.stat(/etc/shadow) (33184, 245390L, 771L, 1, 0, 15, 604L, 1151702662, 1149675585, 1149675585) import stat stat.ST_SIZE 6 os.stat(/etc/shadow)[stat.ST_SIZE] 604L http://docs.python.org/lib/module-stat.html hth, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: How to control permission of file?
True, but I don't see what it has to do with my question. my mistake, I misunderstood your question as Sreeram said, os.open can be used help(os.open) Help on built-in function open: open(...) open(filename, flag [, mode=0777]) - fd Open a file (for low level IO). import os fd=os.open(secret, os.O_WRONLY|os.O_CREAT, 0400) os.write(fd,not for everybody) 17 os.close(fd) ls -l secret -r1 root root 17 2006-07-01 00:05 secret Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: for and while loops
[EMAIL PROTECTED] schrieb: i was wondering if anyone could point me to some good reading about the for and while loops i am trying to write some programs Exercise 1 Write a program that continually reads in numbers from the user and adds them together until the sum reaches 100. Write another program the hidden hint here is ... read until you can't know ahead how many numbers it will be, the pattern in this case is to use while sum smaller then 100 sum = 0 while sum 100: sum = sum + input(more numbers please: ) that reads 100 numbers from the user and prints out the sum. here you know that you are going to read exactly 100 numbers sum = 0 for i in range(100): sum = sum + input(please number #%i: % (i+1)) the only unclear point here is range(100) it generates a list with number [0,1,2 ... 99] and iterates through it one could write it like for i in [0,1,2,3,4]: do_something_with(i) but it gets tedious to write such a long list but im not quite grasping those functions.. please bear im mind i am an extreme newbie at this...thanks in advance hth, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: @func call syntax
this is decorator, this is how it's may be implented def returns(t): ... def dec(f): ... def wrapped(*args, **kwargs): ... ret = f(*args, **kwargs) ... assert type(ret) is t ... return ret ... return wrapped ... return dec ... @returns(int) ... def f1(): ... return 1 ... @returns(float) ... def f2(): ... return 2.0 ... @returns(str) ... def f3(): ... return 1 ... f1() 1 f2() 2.0 f3() Traceback (most recent call last): File stdin, line 1, in ? File stdin, line 5, in wrapped AssertionError I can imagine that stuff like this may be extremely usefull when testing you program later one could parse and remove all such assertations easy and cut them all at once Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: Importing again and again
it's import-ed only once # magic.py file #!/usr/bin/python print here import magic# try to import itself then try # bad_magic.py #!/usr/bin/python print here import bad_magic reload(bad_magic) hth, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner code problem
Hello Here's the code I wrote: import random flip = random.randrange(2) heads = 0 tails = 0 count = 0 while count 100: if flip == 0: flip never changes again it's not reassigned in the while loop heads += 1 else: tails += 1 count += 1 print The coin landed on heads, heads, 'times ' \ and tails, tails, 'times' in case you know how many times to iterate it's better to use for loop (in python and eq C also) from random import randrange as flip result = [0,0] for i in range(100): result[flip(2)] += 1 or from random import randrange as flip result = {head:0, tail:0} for i in range(100): result[[head,tail]flip(2)] += 1 or class Coin: ... def flip(self): ... import random ... return (head, tail)[random.randrange(2)] c = Coin() result = {head:0,tail:0} for i in range(100): result[c.flip()] += 1 or many many more the important thing is .. to know what is the most suitable data representation for you is it throw-away-code or is this going to be read by other people .. etc hth, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: integer to binary...
[EMAIL PROTECTED] schrieb: does anyone know a module or something to convert numbers like integer to binary format ? unfortunately there is no builtin function for this int(111,2) 7 str(7) '7' str(7,2) Traceback (most recent call last): File stdin, line 1, in ? TypeError: str() takes at most 1 argument (2 given) int, str are not symmetrical I hope this will change in future rebel on you can use Ruby's 7.to_s(2) for this irb(main):001:0 7.to_s(2) = 111 irb(main):002:0 7.to_s(3) = 21 irb(main):003:0 /rebel on for example I want to convert number 7 to 0111 so I can make some bitwise operations... you can use bitwise operations on int's anyway 7 3 == 3 (1 20) | (1 10) == 2**20+2**10 and so on -- http://mail.python.org/mailman/listinfo/python-list
Re: can this be done without eval/exec?
Kent Johnson schrieb: Schüle Daniel wrote: and now the obvious one (as I thought at first) lst=[] for i in range(10): ... lst.append(lambda:i) ... lst[0]() 9 i 9 I think I understand where the problem comes from lambda:i seems not to be fully evalutated it just binds object with name i and not the value of i thus lst[0]() is not 0 The problem is that variables in closures are not bound until the variable goes out of scope. So each lambda is bound to the final value of i. are there other solutions to this problem without use of eval or exec? The workaround is to use a default argument to bind the current value of i: In [1]: lst = [] In [2]: for i in range(10): ...: lst.append(lambda i=i: i) ...: ...: In [3]: lst[0]() Out[3]: 0 In [4]: lst[5]() Out[4]: 5 A list comp makes this IMO cleaner: In [5]: lst = [ lambda i=i: i for i in range(10) ] In [6]: lst[0]() Out[6]: 0 In [7]: lst[5]() Out[7]: 5 Kent many thanks for the explaination, it look much simpler than my solutions too Daniel -- http://mail.python.org/mailman/listinfo/python-list
can this be done without eval/exec?
Hello group, lst=[] for i in range(10): ... lst.append(eval(lambda:%i % i)) ... lst[0]() 0 lst[1]() 1 lst[9]() 9 lst=[] for i in range(10): ... exec tmp = lambda:%i % i # assignment is not expression ... lst.append(tmp) ... lst[0]() 0 lst[1]() 1 lst[9]() 9 and now the obvious one (as I thought at first) lst=[] for i in range(10): ... lst.append(lambda:i) ... lst[0]() 9 i 9 I think I understand where the problem comes from lambda:i seems not to be fully evalutated it just binds object with name i and not the value of i thus lst[0]() is not 0 are there other solutions to this problem without use of eval or exec? Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: can this be done without eval/exec?
are there other solutions to this problem without use of eval or exec? Using a factory function closures instead of lambda: def a(x): ... def b(): ... return x ... return b ... lst=[] for i in range(10): ... lst.append(a(i)) ... lst[0]() 0 lst[1]() 1 lst[9]() 9 yes this works I was playing a little more with this idea and got into the next trouble :) cnt=0 def a(): ... def b(): ... return cnt ... global cnt ... cnt += 1 ... return b ... lst=[] for i in range(10): ... lst.append(a()) ... lst[0]() 10 lst[1]() 10 I figured out what was wrong, here is corrected version cnt = 0 def a(): ... global cnt ... tmp = cnt ... def b(): ... return tmp ... cnt += 1 ... return b ... lst=[] for i in range(10): ... lst.append(a()) ... lst[0]() 0 lst[1]() 1 Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
can someone explain why ..
I don't understand what is the difference between commented lines 1 and 2 with 1 uncommented and 2 commented it works as expected with 1 commented and 2 uncommented the picture doesn't appear here is my code #!/usr/bin/env python from Tkinter import * from Tkconstants import * root = None class Main: def __init__(self): global root root = Tk(className = Zeitrechner) root.config(borderwidth = 5, relief = GROOVE) root.geometry(0x0+100+50) #self.im = image = PhotoImage(file = ./flower1.gif) #1 image = PhotoImage(file = ./flower1.gif) #2 frame1 = Frame(master = root, borderwidth = 3, relief = SUNKEN) imageLabel = Label(master = frame1, image = image) root.minsize(width = image.width(), height = image.height()) root.maxsize(width = 2*image.width(), height = image.height()) imageLabel.pack() frame1.pack(side = LEFT) def mainloop(self): root.mainloop() main = Main() main.mainloop() -- http://mail.python.org/mailman/listinfo/python-list
Re: can someone explain why ..
Farshid Lashkari schrieb: Schüle Daniel wrote: I don't understand what is the difference between commented lines 1 and 2 with 1 uncommented and 2 commented it works as expected with 1 commented and 2 uncommented the picture doesn't appear I'm not familiar with Tkinter, but it seems as thought with 2, the image variable is garbage collected after the constructor of Main is called. With 1, you save a reference to the image, so it does not get garbage collected. thx for quick reply :) image is local variable of imageLabel I would expect that in case imageLabel lives, it should hold alife objects bound to its local variables I am just curious *why* reference to image is not hold by imageLabel which on his part is hold by frame1 .. which is hold by global root Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: can someone explain why ..
[..] These are the only lines of code that reference imageLabel: imageLabel = Label(master = frame1, image = image) imageLabel.pack() Unless the constructor of Label adds a reference of itself to frame1, imageLabel will also become garbage collected at the end of the constructor. Are you sure this is the case? yes, now i see it even can frame1 be dead after __init__ it binds itself too root with frame1 = Frame(master = root) frame1.pack(side = LEFT) frame1.pack may append frame1 to root's list of all widgets, we cannot see it, but it also may not do it Thx -- http://mail.python.org/mailman/listinfo/python-list
Re: Confused by Python and nested scoping (2.4.3)
Sean Givan schrieb: Hi. I'm new to Python welcome ago. I was doing some experiments with nested functions, and ran into something strange. This code: def outer(): val = 10 def inner(): print val inner() outer() ...prints out the value '10', which is what I was expecting. But this code.. def outer(): val = 10 def inner(): print val val = 20 inner() print val outer() ...I expected to print '10', then '20', but instead got an error: print val UnboundLocalError: local variable 'val' referenced before assignment. I'm thinking this is some bug where the interpreter is getting ahead of itself, spotting the 'val = 20' line and warning me about something that just a little carefull thought if something that basic should really be a bug how many thousand people would discover it daily? doesn't need warning. Or am I doing something wrong? yes, you can't modify it you can do it for global namespace or local but not inbetween val = 0 def outer(): val = 10 def inner(): global val val = 30 inner() print val outer() 10 # outer val is not changed print val # global is modified 30 hth, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: Help - strange behaviour from python list
Sean Hammond schrieb: I've managed to create a scenario in which editing an object in a list of objects seems to edit every object in the list, rather than just the one. I'm totally stumped and wondered if anyone would be kind enough to read my explanation and see if they have any suggestions. I have probably stumbled into some typical newbie problem, but anyway: just a hint def foo(val,lst=[]): ... lst.append(val) ... print lst ... foo(1) [1] foo(2) [1, 2] foo(3) [1, 2, 3] foo(4,[0]) [0, 4] here list lst is created and bound once compare with this one (which is what you really want) def bar(val, lst=None): ... if lst is None: ... lst = [] ... lst.append(val) ... print lst ... bar(1) [1] bar(2) [2] bar(3, [0]) [0, 3] hth, Daniel -- http://mail.python.org/mailman/listinfo/python-list
int - str asymmetric
Hello what I sometimes miss in Python is the possibility to switch tha base of a number for example this is how it's done in Ruby irb(main):099:0* a = 10.to_s(2) = 1010 irb(main):100:0 a.to_i(2) = 10 irb(main):101:0 irb(main):102:0* a = 10.to_s(3) = 101 irb(main):103:0 a.to_i(3) = 10 the Python int-Function behaves similar int(1010,2) 10 however we lack the reverse functionality the logical str(10,2) Traceback (most recent call last): File stdin, line 1, in ? TypeError: str() takes at most 1 argument (2 given) fails it would not break anything if str interface would be changed what do you think? Is this already proposed or maybe implemented in 2.5? Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: what's going on here?
[...] So finally here's my question: If you are using data.append(), doesn't that just put all the numbers into one long list? no, append appends extend does what you think How are the tuples still being created in this case so that the list comprehensions still work? It seems like there is no longer any 'row' to refer to in data. why not to fire interpreter to see what happens line1 = 1 2 3 4 line2 = 5 6 7 8 lst = [] lst.append(map(float, line1.split())) lst [[1.0, 2.0, 3.0, 4.0]] lst.append(map(float, line2.split())) lst [[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0]] hth, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: My Generator Paradox!
it's easy to explain class X: pass x=X() y=X() x and y are different instances one can put in x x.item = 1 y doesn't even have an attribute item for example similar with generators they are *different* objects of same kind generator def fib(): ... a,b = 1,1 ... while True: ... a,b = b,a+b ... yield a,b ... f1 = fib() f2 = fib() f1 generator object at 0x4042866c f2 generator object at 0x404db42c# different addresses f1 is f2 False f1.next() (1, 2) f1.next() (2, 3) f1.next() (3, 5) f2.next() (1, 2) it's only natural that each objects starts it's own fibonaci serie hth, Daniel -- http://mail.python.org/mailman/listinfo/python-list
__slots__ in derived class
Hello, consider this code class A(object): ... def __init__(self): ... self.a = 1 ... self.b = 2 ... class B(A): ... __slots__ = [x,y] ... b=B() b.a 1 b.b 2 b.x = 100 b.y = 100 b.z = 100 no exception here does __slots__ nothing when used in derived classes? class Z(object): ... __slots__ = [x,y] ... z=Z() z.x = 100 z.y = 100 z.z = 100 Traceback (most recent call last): File stdin, line 1, in ? AttributeError: 'Z' object has no attribute 'z' here it works like expected Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: pow (power) function
Russ wrote: I have a couple of questions for the number crunchers out there: Does pow(x,2) simply square x, or does it first compute logarithms (as would be necessary if the exponent were not an integer)? Does x**0.5 use the same algorithm as sqrt(x), or does it use some other (perhaps less efficient) algorithm based on logarithms? you can try and timeit 111**111 10736201288847422580121456504669550195985072399422480480477591117562507619578334702249122617009363462146610374309298696786330067310159463303558666910091026017785587295539622142057315437069730229375357546494103400699864397711L timeit.Timer(pow(111,111)).timeit() 40.888447046279907 timeit.Timer(111**111).timeit() 39.732122898101807 timeit.Timer(111**0.5).timeit() 2.0990891456604004 timeit.Timer(pow(111,0.5)).timeit() 4.1776390075683594 timeit.Timer(111**0.3).timeit() 2.3824679851531982 timeit.Timer(pow(111,0.3)).timeit() 4.2945041656494141 interesting result seems that ** computates faster -- http://mail.python.org/mailman/listinfo/python-list
Re: Mutable complex numbers [was Re: output formatting for classes]
Steven D'Aprano wrote: On Fri, 10 Mar 2006 02:19:10 +0100, Schüle Daniel wrote: yeah, i miss some things in complex implementation for example c=complex() c.abs = 2**0.5 c.angle = pi/2 should result in 1+1j :) Smiley noted, but consider: c = complex() = what is the value of c here? default value is 0, for complex number that means real = 0, imag = 0 is the same as c.abs=0, c.angle=0 ok mathematically c.angle can be of arbitrary value but defaulting it to zero is very handy c = complex() c.abs = 10 yields 10+0j c=complex() c.real = 2 c.imag = 2 c.abs = 50**0.5 # angle remains, length changed yields 5+5j c.angle = 0 yields 50**0.5 + 0j c.abs = 2**0.5 = what is c's value now? c.abs = 2**0.5 c.angle = 0 c.angle = pi/2 = now c has the value 1+1j Objects with indeterminate values are rarely a good idea. IMHO it's perfectly consistent with int() 0 long() 0L float() 0.0 complex() complex() 0j but extending complex with default angle=0 A better way would be for complex numbers to take a constructor that can take arguments in either Cartesian or polar form. So, hypothetically, the following would all be equivalent: 1+1j complex(1,1) complex(real=1, img=1) complex(len=2**0.5, theta=pi/2) ack but after the creation of complex number one will have to do all the transformations in another coord. system manually Another alternative would be a function to construct polar form complex numbers. It could be a plain function or a static method: cmath.polar(2**0.5, pi/2) = 1+1j complex.polar(2**0.5, pi/2) = 1+1j maybe adding c=complex.from_polar((length,angle)) d=complex.to_polar(c) d == (length, angle) True would be sufficient, but I would prefer the other version Regards -- http://mail.python.org/mailman/listinfo/python-list
Re: Inter-module globals
Anton81 wrote: Hi, I want to use globals that are immediately visible in all modules. My attempts to use global haven't worked. Suggestions? Anton I think a dictionary would work here as well as list but not strings and int's # module1 settings = { release : 1.0, blabla : None, } # module2 import module1 as settings print settings.settings[release] settings.settings[blabla] = True # module3 import module1 as settings settings.settings[blabla] = False Regards -- http://mail.python.org/mailman/listinfo/python-list
Re: A better RE?
Magnus Lycka wrote: I want an re that matches strings like 21MAR06 31APR06 1236, where the last part is day numbers (1-7), i.e it can contain the numbers 1-7, in order, only one of each, and at least one digit. I want it as three groups. I was thinking of r(\d\d[A-Z]\d\d) (\d\d[A-Z]\d\d) (1?2?3?4?5?6?7?) but that will match even if the third group is empty, right? Does anyone have good and not overly complex RE for this? P.S. I know the now you have two problems reply... txt = 21MAR06 31APR06 1236 m = '(?:JAN|FEB|MAR|APR|MAI|JUN|JUL|AUG|SEP|OCT|NOV|DEZ)' # non capturing group (:?) p = re.compile(r(\d\d%s\d\d) (\d\d%s\d\d) (?=[1234567])(1?2?3?4?5?6?7?) % (m,m)) p.match(txt).group(1) '21MAR06' p.match(txt).group(2) '31APR06' p.match(txt).group(3) 1236 -- http://mail.python.org/mailman/listinfo/python-list
Re: output formatting for classes
Russ wrote: I'd like to get output formatting for my own classes that mimics the built-in output formatting. For example, x = 4.54 print %4.2f % x 4.54 In other words, if I substitute a class instance for x above, I'd like to make the format string apply to an element or elements of the instance. Can I somehow overload the % operator for that? Thanks. On an unrelated matter, I think the complex class in Python is too complex, so I plan to clean it up and implement it right. (just kidding, folks!) yeah, i miss some things in complex implementation for example c=complex() c.abs = 2**0.5 c.angle = pi/2 should result in 1+1j :) or c=complex(1,1) print c.abs # should print 2**0.5 print c.angle # should print pi%2 i think one can implement it with properties but to your question ... class X(object): ... def __float__(self): ... return 1.0 ... def __long__(self): ... return 10l ... def __int__(self): ... return 20 ... def __repr__(self): ... return i am ... def __str__(self): ... return I AM ... def __complex__(self): ... return 1+1j ... x=X() int(x) 20 long(x) 10L float(x) 1.0 str(x) 'I AM' repr(x) 'i am' print %s -- %r % (x,x) I AM -- i am complex(x) (1+1j) -- http://mail.python.org/mailman/listinfo/python-list
[exec cmd for cmd in cmds]
Hello all, p = z%i = complex(1-1e-%i, 1-1e-%i) lst = [p % (i,i,i) for i in range(10, 30)] for item in lst: ... exec item ... p = z%i = complex(1-1e-%i, 1-1e-%i) lst = [p % (i,i,i) for i in range(10, 30)] [exec item for item in lst] File stdin, line 1 [exec item for item in lst] ^ SyntaxError: invalid syntax is this prohibited for some reasons or is this just happens to be disallowed? this is one more cool way p = z%i = complex(1-1e-%i, 1-1e-%i); c = reduce(lambda x,y: x+y, [p % (i,i,i) for i in range(20,30)]) exec c and one more :) p = z%i = complex(1-1e-%i, 1-1e-%i); c = .join([ p % (i,i,i) for i in range(20,30) ]) exec c Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: [exec cmd for cmd in cmds]
[...] If you think so :) Ususally people go for dictionaries in such cases. you are right, I didn't think about dictionaries p = complex(1-1e-%i, 1-1e-%i) d={} [d.update({i:eval(p % (i,i))}) for i in range(20,30)] [None, None, None, None, None, None, None, None, None, None] so now the work is complete :) Regards -- http://mail.python.org/mailman/listinfo/python-list
deriving from complex
Hello I am trying to customize the handling of complex numbers what I am missing is a builtin possibility to create complex numbers in polar coordinates so first I wrote a standalone function def polar(r,arg): ... re, im = r*cos(arg), r*sin(arg) ... return re + im*1j then I tried to extend this to a class from math import * class Complex(complex): ... def __init__(self,x,y,polar=False): ... if not polar: ... self.re, self.im = x,y ... else: ... self.re, self.im = x*cos(y), x*sin(y) ... c=Complex(1,1) c (1+1j) p=Complex(10,45.0/360*2*pi,True) Traceback (most recent call last): File stdin, line 1, in ? TypeError: complex() takes at most 2 arguments (3 given) and got stuck with this error it seems that last argument is rejected because complex wants to have 2 arguments but this works well .. class X(object): ... def __init__(self,a): ... self.a = a ... class Y(X): ... def __init__(self,a,b): ... self.a = a ... self.b = b ... y=Y(1,2) what's causing the above exception? one more question class Complex(complex): ... def __init__(self,x,y): ... self.real = x ... self.imag = y ... c=Complex(1,1) Traceback (most recent call last): File stdin, line 1, in ? File stdin, line 3, in __init__ TypeError: readonly attribute how can I work around this problem? Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: deriving from complex
what do you think of this design? def polar(x,y=None): ... if type(x) in (list,tuple) and len(x) == 2 and y is None: ... return complex(x[0]*cos(x[1]), x[0]*sin(x[1])) ... if type(x) is complex and y is None: ... return (abs(x), atan2(x.imag,x.real)) ... if type(x) in (float, int, long) and type(y) in (float, int, long): ... return complex(x*cos(y), x*sin(y)) ... polar(2**0.5, 45.0/360*2*pi) (1.0002+1j) polar((2**0.5, 45.0/360*2*pi)) (1.0002+1j) polar([2**0.5, 45.0/360*2*pi]) (1.0002+1j) polar(1+1j) (1.4142135623730951, 0.78539816339744828) btw I like how Ruby handles the creation of complex numbers c = Complex(1,1) p = Complex.polar(1,45.0/360*2*PI) Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: deriving from complex
thank you I will have to take a closer look on __new__ Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: Why I chose Python over Ruby
Hi Alex [...] The trick about distinguishing a name's exact nature based on whether the compiler sees an assignment to that name in some part of code is found in both languages, albeit in different ways. In Ruby, as you've pointed out, it's the heuristic used to disambiguate local variable access from zero-argument method calls, and the part of code is the function up to the point of access. In Python, it's used to disambiguate local from global or free variables, and the part of code is the body of the whole function (Ruby does not need to make this latter distinction because it strops global names with a leading sigil -- $a is always the global variable a, just like @a is always the instance attribute a, which we'd write self.a in Python). Another subtle case in Ruby is whether an assignment such as a=23 _within a block_ is meant to be local to the block or meant to rebind local name 'a' within the enclosing function; again, the heuristic is similar, depending only on whether the compiler had seen another assignment to a before it saw the block (Python forbids the rebinding of variables coming from an enclosing but non-global scope, to avoid facing this issue). I am not sure what you mean here can you elaborate on this please def a(): ... q = [] ... def b(x): ... def c(y): ... def d(z): ... q.append(x) ... q.append(y) ... q.append(z) ... d(1) ... c(2) ... b(3) ... return q ... a() [3, 2, 1] As far as I know this snippet would work only from version 2.2 maybe you are talking about older versions of Python Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: Adding method at runtime - problem with self
[EMAIL PROTECTED] wrote: First of all, please don't flame me immediately. I did browse archives and didn't see any solution to my problem. Assume I want to add a method to an object at runtime. Yes, to an object, not a class - because changing a class would have global effects and I want to alter a particular object only. The following approach fails: class kla: x = 1 def foo(self): print self.x k = kla() k.foo = foo k.foo() I know where the problem is. The method shouldn't have 'self' parameter. But how do I access object's attributes without it? Best regards, Marek k.foo(k) would work -- http://mail.python.org/mailman/listinfo/python-list
Re: how to break a for loop?
Gregory Petrosyan wrote: Hello! It's 1:56 o'clock in St.-Petersburg now, and I am still coding... maybe that's why I encountered stupid problem: I need to remove zeros from the begining of list, but I can't :-(. I use for i,coef in enumerate(coefs): if coef == 0: del coefs[i] else: break but it removes ALL zeros from list. What's up? I don't know how enumerate is implemented, but I would suspect that modifying the list object in the loop through del is asking for trouble try for i,coef in enumerate(coefs[:]): instead P.S. I feel SO stupid asking this quastion... ;-) uda4i hth, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: Does python have an internal data structure with functions imported from a module?
in case you are trying it in the python shell def foo():return test ... import __main__ __main__.__dict__[foo] function foo at 0x40420c6c __main__.__dict__[foo]() 'test' otherwise build your own dict with string-function mapping op = { plus : lambda x,y:x+y, minus : lambda x,y:x-y, power : lambda x,y:x**y, } op[power](2,8) hth, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: is there a better way?
[...] What not for x in list: if x == O: break storage.append(x) i think this may take too long better aproach would be to test for zero from the end Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: is there a better way?
[...] I have been using something like this: _ while list[0] != O: storage.append(list[0]) list.pop(0) if len(list) == 0: break _ But this seems ugly to me, and using while give me the heebies. Is there a better approach? lst = [1,2,3,4,5,0,0,0,0] del lst[lst.index(0):] lst [1, 2, 3, 4, 5] Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: is there a better way?
Lonnie Princehouse wrote: everybody is making this way more complicated than it needs to be. storage = list[:list.index(O)] the question is whether the old list is needed in the future or not if not then it would be easer/mor efficient to use del lst[lst.index(0):] Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: is there a better way?
I don't want to hijack the thread I was thinking whether something like lst.remove(item = 0, all = True) would be worth adding to Python? it could have this signature def remove(item, nItems = 1, all = False) ... return how_many_deleted lst.remove(item = 0, nItems = 1) lst.remove(item = 0, nItems = 2) lst.remove(item = 0, all = True) in last case nItems is ignored Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: arrays in python
I want to write a program in python using integer arrays. you can :) I wish to calculate formulas using 200 digit integers. no problem I could not find any documentation in python manual about declaring arrays. I searched the internet read here http://diveintopython.org/native_data_types/lists.html maybe list are what you are looking for and found an example that said I must declare from Numeric import * yes, one can use Numeric for this taks too and I downloaded a numerical python extension, but still have not found a way to declare an array of given length. The zeros function always gives me an error message. import Numeric as N, random as rand nums = [33 ** rand.randint(10,100) for i in range(200)] len(nums) 200 nums[0] 1666465812864030391541732975677083441749008906546726522024522041932256405404932170047036994592860856233379702595619607481259213235163454890913L a = N.array(nums) len(a) 200 a[0] 1666465812864030391541732975677083441749008906546726522024522041932256405404932170047036994592860856233379702595619607481259213235163454890913L by the way, you know you can use interactive Python iterpreter and there is dir and help function dir(a) ['__copy__', '__deepcopy__', 'astype', 'byteswapped', 'copy', 'iscontiguous', 'itemsize', 'resize', 'savespace', 'spacesaver', 'tolist', 'toscalar', 'tostring', 'typecode'] dir(nums) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__str__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: UnboundMethodType and MethodType
[...] It's the same function, whether it's bound or not. Thus, it should always have the same type. No, it's not the same function. You got the same id because you didn't bind B.bar and b.bar to anything so the id was reused. thank you for the explanation it's indeed tricky with reusing the id are there some pages on the net to read more about it? class Q: ... def __init__(self,val): ... self.val = val ... def bar(self): ... print self.val ... x = Q.bar y = Q(test).bar x unbound method Q.bar y bound method Q.bar of __main__.Q instance at 0x40427a6c y() test id(x) 1078081812 id(y) 1078082492 the same id-value would enforce two objects to be of the same type (trivial case) the reverse is not necessarily true in this case x.bar and y.bar are of the same type UnboundMethodType is still not very suitable name for Q().bar :-/ Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: how to copy a Python object
[EMAIL PROTECTED] wrote: Already thanks for the reply, but how to write your own copy operator? Won't you always be passing referrences to new_obj? for example this would work class X(object): ... def __init__(self,lst): ... self.lst = lst ... def copy(self): ... return X(self.lst[:]) ... def __str__(self): ... return lst has id %i % id(self.lst) ... x=X([1,2,3]) y=x.copy() print x lst has id 1078097132 print y lst has id 1078097228 but I don't like that in this case self.lst must be passed through __init__ I can think of another variant class Y(object): ... def fill(self): ... self.lst = [randint(i*10,(i+1)*10) for i in xrange(5)] ... def __repr__(self): ... return lst has id = %i % id(self.lst) ... def copy(self): ... ret = Y() ... ret.lst = self.lst[:] ... return ret ... from random import randint y=Y() y.fill() y lst has id = 1078097452 print y lst has id = 1078097452 x=y.copy() x lst has id = 1078097004 ... anyone? are there better approaches? Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: * 'struct-like' list *
Ernesto wrote: Thanks for the approach. I decided to use regular expressions. I'm going by the code you posted (below). I replaced the line re.findall line with my file handle read( ) like this: print re.findall(pattern, myFileHandle.read()) This prints out only brackets []. Is a 're.compile' perhaps necessary ? if you see [] that means findall didn't find anything that would match your pattern if you re.compile your pattern beforehand that would not make findall find the matched text it's only there for the optimization consider lines = [line for line in file(foo.txt).readlines() if re.match(r\d+,line)] in this case it's better to pre-compile regexp one and use it to match all lines number = re.compile(r\d+) lines = [line for line in file(foo.txt).readlines() if number.match(line)] fire interactive python and play with re and patterns speaking from own experience ... the propability is against you that you will make pattern right on first time Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
UnboundMethodType and MethodType
Hello all, class Q: ... def bar(self): ... pass ... import types types.UnboundMethodType is types.MethodType True type(Q.bar) type 'instancemethod' q = Q() type(q.bar) type 'instancemethod' type(q.bar) is types.UnboundMethodType True q.bar bound method Q.bar of __main__.Q instance at 0x4042756c I think is not very consistent notice q.bar is bounded although type(q.bar) says it's types.UnboundedMethodType what do you think? Regard, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: read file problem
if you want the numbers you can combine it into one-liner nums = file(rC:\folder\myFile.txt).read().split(;) the numbers are in string representation in the list you can no do nums = [float(num) for num in nums] Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: Size of list
lst = [1,2,3] len(lst) 3 lst.__len__() 3 in genereal all objects which implements __len__ can be passed to built-in function len len built-in function len just to give one example how this can be used class X(object): ... def __len__(self): ... print this instance has __len__ ... return 100 ... x=X() len(x) this instance has __len__ 100 x.__len__() this instance has __len__ 100 hth, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: * 'struct-like' list *
I would like to have an array of structs. Each struct has struct Person{ string Name; int Age; int Birhtday; int SS; } the easiest way would be class Person: pass john = Person() david = Person() john.name = John Brown john.age = 35 etc think of john as namespace .. with attributes (we call them so) added on runtime better approch would be to make real class with constructor class Person(object): def __init__(self, name, age): self.name = name self.age = age def __str__(self): return person name = %s and age = %i % (self.name, self.age) john = Person(john brown, 35) print john # this calls __str__ I want to go through the file, filling up my list of structs. My problems are: 1. How to search for the keywords Name:, Age:, etc. in the file... 2. How to implement some organized list of lists for the data this depend on the structure of the file consider this format New Name: John Age: 35 Id: 23242 New Name: xxx Age Id: 43324 OtherInfo: foo New here you could read all as string and split it on New here small example txt = fooXbarXfoobar txt.split(X) ['foo', 'bar', 'foobar'] in more complicated case I would use regexp but I doubt this is neccessary in your case Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: Numeric and matlab
Hello, [...] I'm sure there are more, but these jump out at me as I'm going. It seems as if the idx=find() stuff can be done with Numeric.nonzeros(), but you can't index with that, like a=Numeric.arange(1,11,1) idx=Numeric.nonzeros(a) import Numeric as N N.nonzero without s :) a=a[idx] % doesn't work i don't know whether arange object overloads __getitem__ like class X(object): ... def __getitem__(self,i): ... return self.lst[i] ... def __init__(self): ... self.lst = [7,5,3,1] ... x=X() x[0] 7 x[1] 5 or consider class List(list): ... def __getitem__(self,idx): ... if type(idx) is list: ... ret = [] ... lst = list(self) ... return [lst[i] for i in range(len(lst)) if i in idx] ... lst=List([1,2,3,4,5]) lst [1, 2, 3, 4, 5] lst[[0,2]] [1, 3] if it would overload this would be possible, the normal python list takes slices range(0,100)[1:10:2] s = slice(1,10,2) range(0,100)[s] here some ideas for what you tring to do nums # normal python list [0, 1, 2, 1, 0, 0, 0, 3, 4, 0] filter(lambda x: x!=0, nums) [1, 2, 1, 3, 4] [item for item in nums if item !=0 ] [1, 2, 1, 3, 4] a=N.arange(0,11,.5) filter(lambda x: x!=0, a) [0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5, 10.0, 10.5] [item for item in a if item !=0 ] [0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5, 10.0, 10.5] Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
backreference in regexp
X-Enigmail-Version: 0.76.5.0 X-Enigmail-Supports: pgp-inline, pgp-mime Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit Hello @all, p = re.compile(r(\d+) = \1 + 0) p.search(123 = 123 + 0) 'search' returns None but I would expect it to find 123 in group(1) Am I using something that is not supported by Python RegExp engine or what is the problem with my regexp? Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: backreference in regexp
thank you, I completely forgot that + is one of metacharacters Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
rational numbers
Hello NG, recently I was using Scheme and Ruby and was really nicely surprised to find there support for the computing with rational numbers for example this how it works in Ruby mond:/pool/PROG/ruby # irb irb(main):001:0 irb(main):002:0* require mathn = true irb(main):003:0 r = Rational(1,3) = 1/3 irb(main):004:0 p = Rational(1,5) = 1/5 irb(main):005:0 r+p = 8/15 irb(main):007:0 (r+p)**2 = 64/225 irb(main):008:0 does anybody know modules which make rational numbers available? and are there considerations to add them to the core, like complex numbers (maybe in Python 3) Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
decorator question
hello NG, consider this code def timelogger(f): ... def wrapper(*a,**kw): ... print started at %s % time.ctime() ... t0 = time.time() ... f(*a, **kw) ... t1 = time.time() ... print ended at %s % time.ctime() ... print diff = , t1-t0, sec ... return wrapper ... import time @timelogger ... def loops(a,b,c): ... sum = 0 ... for i in range(a): ... for j in range(b): ... for k in range(c): ... sum += 1 ... loops function wrapper at 0x402eec34 loops(10,10,10) started at Sun Jan 8 23:19:19 2006 ended at Sun Jan 8 23:19:19 2006 diff = 0.000367164611816 sec the code above works fine but I am wondering wheather it's possible to write something like this def timelogger(f, logfile=sys.stdout): ... def wrapper(*a,**kw): ... logfile.write(started at %s % time.ctime()) ... t0 = time.time() ... f(*a, **kw) ... t1 = time.time() ... logfile.write(ended at %s % time.ctime()) ... logfile.write(diff = %f %s % (t1-t0, sec)) ... return wrapper import time @timelogger(file(hierher, a)) ### (1) ... def loops(a,b,c): ... sum = 0 ... for i in range(a): ... for j in range(b): ... for k in range(c): ... sum += 1 ... (1) fails to compile is it possible to pass parameters to a decorator function? Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: decorator question
thx to all now I understand how it works and why it should be done in this way so it's possible to write more than only one declarator def foo(f): ... l = [1] ... def method(*a,**kw): ... f(l, *a, **kw) ... return method ... def bar(f): ... l = [2] ... def method(*a,**kw): ... f(l, *a, **kw) ... return method ... @foo ... @bar ... def foobar(x,y,z): ... print x ... print y ... print z ... foobar(1) [2] [1] 1 x and y are already binded by the way .. to l's lists are considered to be in closure? Or what is the right denotation for them? Can someone give me some pointers to the metaprogramming in Python? links etc Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: Copy an Object (Again?)
KraftDiner wrote: I'm having trouble getting a copy of and object... (a deep copy) I'm writing a method that creates a mirror image of an object (on screen) In order to do this i need to get a copy of the object and then modify some of its attributes. I tried: objs = myListOfObjects for obj in objs: if obj.flag: newObject = copy.deepcopy(obj) newObject.mirror() myListOfObjects.append(newObject) That doesn't seem to work.. the new object seems to disapear from existance. I'm wondering if its a bug in my application or if this is my shallow understanding of the language. TIA B. I think you should provide more code, eg what attributes does your object have? imagine the situation like this import copy class A: ... lst=[1, 2, 3] ... a=A() b=copy.deepcopy(a) a __main__.A instance at 0x403e3c8c a.lst [1, 2, 3] b.lst [1, 2, 3] b.lst.append(4) b.lst [1, 2, 3, 4] a.lst [1, 2, 3, 4] or even if you could copy instances class X: def __init__(self, filename = /path/file) self.file = file(filename, w+) def modifyByteAt(offset): self.file.tell(offset) self.file.write(X) this is untested pseudocode, it should only give you an idea hth, Daniel ps: question to all what is a general approach to copy class instances? write own method or is there some __magic__ attribute or should one use pickle.dump? Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: Copy an Object (Again?)
I was not very clear about it or even if you could copy instances class X: def __init__(self, filename = /path/file) self.file = file(filename, w+) def modifyByteAt(offset): self.file.tell(offset) self.file.write(X) this is untested pseudocode, it should only give you an idea even when x=X() and y=copyItSomehowFrom(x) what is supposed to be copied? the whole file? but where? in your case .. what is supposed to happen with the mirrored image? should it be mirrored inplace if I recall properly in import PIL.Image as image if you image.open an image and want to mirror it you can create a real copy and then save as it into a file my 2 cents -- http://mail.python.org/mailman/listinfo/python-list