Re: Idea for key parameter in all() builting, would it be feasible?
> If you're getting this via the mailing list, just hit Reply, and then > > change the To: address to python-list@python.org - that's the simplest > > (assuming you don't have a Reply To List feature, but you wouldn't be > > saying the above if you had one). That way, you get a citation line, > > quoted text is marked, and it's taken a minimum of effort. I guess it was pretty late last night but I didn't notice the huge post reply button *palmface*. > Awesome! Hey, if you *can* switch to Py3, do try to. It has heaps of > > improvements, and it has a future. :) > > > > ChrisA Also I realized that aside from using map or the better alternative imap, an even better way to go might be a generator expression. Completely forgot about those. So with a slightly less trivial example than the first >>> all(map(lambda x: n%x, xrange(2, n))) could be better written as >>> all(n%x for n in xrange(2, n)) which is roughly 10 times faster and memory efficient, plus syntax is cleaner. And roughly 1.5 times faster than imap which isn't much but prevents having to import itertools. But I discovered a new itertools tool and my sieve was successful. def primeset(upper): return set([2]+range(3,upper,2)).difference(set.union(*[set(xrange(p+p,upper,p)) for p in [n for n in xrange(3,int(pow(upper, 0.5)+1)) if all(n%x for x in xrange(2, int(pow(n, 0.5)+1)))]])) Here is the more sane version of the one-liner above. def primeset(upper): def isprime(n): # brute force trial division for d in xrange(2, int(pow(n, 0.5)+1)): if n%d == 0: return False return True # Initial set of only odd numbers except for 2 numbers = set([2]+range(3, upper, 2)) # List of prime numbers up to square root of upper using brute force. primes = [n for n in xrange(2, int(pow(upper,0.5)+1)) if isprime(n)] # Multiples of all the prime numbers in the list above. all_multiples = (set(xrange(p+p,upper,p)) for p in primes) # This was allot faster than reduce(set.union, all_multiples) multiples = set.union(*all_multiples) # And the sieving action. return numbers.difference(multiples) Rough benchmarks: >>> timer(primeset, 10**6) 1.0981476384030202 >>> # straight forward Eratosthenes sieve >>> timer(primes, 10**6) 0.5887037628822327 -- http://mail.python.org/mailman/listinfo/python-list
Re: Idea for key parameter in all() builting, would it be feasible?
On Thursday, June 20, 2013 12:45:27 PM UTC+2, Antoon Pardon wrote: > Op 19-06-13 18:14, russ.po...@gmail.com schreef: > > > > > all(map(lambda x: bool(x), xrange(10**9))) > > > > Since you already have your answer, I just like to get your attention > > to the fact the the lambda is superfluous here. Your expression > > above is equivallent to > > > > all(map(bool, xrange(10**9))) That's true, I didn't notice that. Although it was a trivial example I was setting up from the actual code and couldn't think of what to shove inside lambda so bool got the short straw. The latest example I showed was actually. >>> all(map(lambda x: n%x, xrange(2, n))) -- http://mail.python.org/mailman/listinfo/python-list
Re: FACTS: WHY THE PYTHON LANGUAGE FAILS.
On Thursday, June 27, 2013 6:19:18 AM UTC+2, Thrinaxodon wrote: > = > > >MESSAGE FROM COMPUTER GEEK. > > = > > > > > THRINAXODON HAS RECENTLY RECEIVED THIS MESSAGE FROM THE PYTHON FOUNDER: > > > > Oh my God! It's hard to program with, it`s troubling for so many people! > > I call for the cancellation of the Python programming language. > > > > > THRINAXODON: Wow! I had much trouble, myself. In fact; the makers of the > > Python language watch every move o, it, therefore violating privacy. > > > > > FOUNDER: It`s weird...I have 5,000 pieces of info. on every person that > > uses it. That`s the real reason... > > > > > THRINAXODON: I used it! > > > > > FOUNDER: It`s really hard to use. It requires 20 books just to know how > > to code with it. > > > > > THRINAXODON: Time to announce the cancellation at comp.lang.python! > > > > > === > > THRINAXODON IS NOW ON TWITTER. I was hoping to have a good laugh. :| Although I wouldn't call it hostile. -- http://mail.python.org/mailman/listinfo/python-list
What is the purpose of type() and the types module and what is a type?
The type() builtin according to python docs, returns a "type object". http://docs.python.org/2/library/types.html And in this module is bunch of what I assume are "type objects". Is this correct? http://docs.python.org/2/library/functions.html#type And type(), aside from being used in as an alternative to a class statement to create a new type, really just returns the object class, doesn't it? >>> import types >>> a = type(1) >>> b = (1).__class__ >>> c = int >>> d = types.IntType >>> a is b is c is d True >>> If type() didn't exist would it be much more of a matter than the following?: def type(x): return x.__class__ What is the purpose of type()? What exactly is a "type object"? Is it a "class"? What is the purpose of the types module? I understand the purpose of isinstance and why it's recommended over something like (type(1) is int). Because isinstance will also return True if the object is an instance of a subclass. >>> class xint(int): def __init__(self): pass >>> x = xint() >>> type(x) is int False >>> isinstance(x, int) True >>> -- http://mail.python.org/mailman/listinfo/python-list
Re: Stupid ways to spell simple code
On Sunday, June 30, 2013 8:06:35 AM UTC+2, Chris Angelico wrote: > There's a bit of a discussion on python-ideas that includes a function > > that raises StopIteration. It inspired me to do something stupid, just > > to see how easily I could do it... > > > > On Sun, Jun 30, 2013 at 3:45 PM, Nick Coghlan wrote: > > Re: [Python-ideas] "Iteration stopping" syntax > > def stop(): > > > ... raise StopIteration > > > > Here's a much more insane way to spell that: > > > > stop = (lambda: 0 and (yield 1))().__next__ > > > > So, here's a challenge: Come up with something really simple, and > > write an insanely complicated - yet perfectly valid - way to achieve > > the same thing. Bonus points for horribly abusing Python's clean > > syntax in the process. > > > > Go on, do your worst! > > > > ChrisA Here's a way to count items in a string. def count(string, x): return len(''.join(string)) - len(''.join(string).replace(x, '')) / len(x) -- http://mail.python.org/mailman/listinfo/python-list
Simple recursive sum function | what's the cause of the weird behaviour?
I know this is simple but I've been starring at it for half an hour and trying all sorts of things in the interpreter but I just can't see where it's wrong. def supersum(sequence, start=0): result = start for item in sequence: try: result += supersum(item, start) except: result += item return result It's supposed to work like the builtin sum, but on multidimensional lists and also with the optional start parameter accepting something like an empty list and so would also works as a robust list flattener. It's just for kicks, I'm not actually going to use it for anything. This works: - - - - - - >>> x = [[1], [2], [3]] >>> supersum(x) 6 >>> supersum(x, []) [1, 2, 3] >>> This does not: - - - - - - - >>> x = [[[1], [2]], [3]] >>> supersum(x, []) [1, 2, 1, 2, 3] >>> -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple recursive sum function | what's the cause of the weird behaviour?
Nevermind! Stupid of me to forget that lists or mutable so result and start both point to the same list. -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple recursive sum function | what's the cause of the weird behaviour?
Since I've already wasted a thread I might as well... Does this serve as an acceptable solution? def supersum(sequence, start=0): result = type(start)() for item in sequence: try: result += supersum(item, start) except: result += item return result -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple recursive sum function | what's the cause of the weird behaviour?
I read through all of the posts and thanks for helping. What was supposed to be simple a (recursively) straightforward, turned out to be quite tricky. I've set up a small testing bench and tried all of the proposed solutions including my own but none pass. I'll post it below. I've also discovered something about lists that explains the very first "weird" result I was observing, which I realized was because lists are mutable etc, but more specifically: This >>> a = [1, 2] >>> a += [3] is equivalent to, AFAIK, this >>> a = [1, 2] >>> a.extend([3]) So to overcome that you just have to do >>> a = [1, 2] >>> a = a + [3] Which creates a new list. So any variables which were pointing to the same list as a, are unaffected. Summary - - - - >>> # --- Bad --- >>> a = [1, 2] >>> b = a >>> a += [3] >>> print a [1, 2, 3] >>> print b [1, 2, 3] >>> # --- Good --- >>> a = [1, 2] >>> b = a >>> a = a + [3] >>> print a [1, 2, 3] >>> print b [1, 2] And as for the testbench: def supersum(seq, start=0): return # Testing > testcases = [ # (seq, start, result) # arithmetic sums ([],0, 0), ([[], []], 0, 0), ([[], [[],[]]], 0, 0), ([1], 0, 1), ([[], [1]], 0, 1), ([[], [[],[1, 1]]], 0, 2), ([[1], [1]],0, 2), ([[1], [[1],[1, 1]]], 0, 4), ([[1], [[1],[1, 1]]], 1, 5), # list flattening ([],[], []), ([[], []], [], []), ([[], [[],[]]], [], []), ([],[1],[1]), ([[], []], [1],[1]), ([[], [[],[]]], [1],[1]), ([1], [1],[1, 1]), ([[1], [1]],[1],[1, 1]), ([[1], [[1],[1]]], [1],[1, 1, 1, 1]), ] for seq, start, result in testcases: try: assert supersum(seq, start) == result except Exception as er: print "seq:%s\t start:%s" % (seq, start) if type(er) is AssertionError: print "expected:", result print "got: ", supersum(seq, start) else: print repr(er) print '' -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple recursive sum function | what's the cause of the weird behaviour?
I got it! One of the testcases was wrong, ([[1], [1]],[1],[1, 1]), should be ([[1], [1]],[1],[1, 1, 1]), And the working solution. def supersum(sequence, start=0): result = start start = type(start)() for item in sequence: try: item = supersum(item, start) except TypeError: pass try: result = result + item except TypeError: return result + sequence return result I couldn't yet get around doing type(start)() and it's pretty messy, but anyways... -- http://mail.python.org/mailman/listinfo/python-list
Recursive class | can you modify self directly?
Sorry for the vague title. Probably best to just show you the code that explains it better. This is a simplified example of what I want to do: # THIS DOESN'T WORK from random import choice class Expr(object): """ Expr(expr, op, val) -> an expression object. """ def __init__(self, expr, op='', val=''): self.expr = expr # can be another instance of Expression. self.op = op self.val = val def __str__(self): return ("%s %s %s" % (self.expr, self.op, self.val)).strip() def expand(self): self = Expr(self, choice('+-*/'), choice('12345')) Then I tried messing around with Expr.__new__() and Expr.__init__() but that didn't work. The only way I've got it to work is by doing the expanding part outside of the object, by a method of some other class. But I want the Expr class to be responsible for itself. How can I do this and why doesn't the above work? -- http://mail.python.org/mailman/listinfo/python-list
Re: Recursive class | can you modify self directly?
I didn't do a good job of explaining it cos I didn't want it to be a TLDR; but I could've added a little more. To clarify: Expr is just a way to represent simple arithmetic expressions for a calculator. Because the expression has to be modified and built over time, and evaluated from left to right and not by operator precedence, I thought it would be simpler to do it this way. Say the calculation in the calculator is currently at: 1 + 2 * 3 Now lets expand it out to see how it gets to this point. dial 1: (1) >>> x = Expr(1) # the base case dial +: ((1) + )>>> x = Expr(x, '+') dial 2: ((1) + 2) >>> x.val = 2 dial *: (((1) + 2) + ) >>> x = Expr(x, '+') dial 3: (((1) + 2) + 3) >>> x.val = 3 I think it's called 'binary tree' but not entirely sure if that's correct. So I think understand what you guys are saying now. There is the name x and the class instance (the object) which exists somewhere in memory that x points to. self is just another name that points to the same object (not self in general but the argument passed to the self parameter when a method is called). However if the code inside the method reassigns self to some other object, it doesn't change the fact that x still refers to the original object. So self is just a local variable (an argument). The name self has no relevance to to the name x other than the fact that they point to the same object. So reassigning self has no effect on x. But modifying the object that self points to, does affect x because it points to the same object. Is this correct? So when you call x.somemethod() it's not passing x as the self argument, it's actually passing the object that x points to as the self argument. And that object has know knowledge of the fact that x points to it, or does it? -- http://mail.python.org/mailman/listinfo/python-list
Re: Recursive class | can you modify self directly?
On Wednesday, July 10, 2013 12:20:47 AM UTC+2, Ian wrote: > On Tue, Jul 9, 2013 at 4:18 PM, Ian Kelly wrote: > > > If you actually want to modify the current object, you would need to > > > do something like: > > > > > > def expand(self): > > > import copy > > > self.expr = Expr(self.expr, self.op, self.val) > > > self.op = choice('+-*/') > > > self.val = choice('12345') > > > > Minus the "import copy". I modified the code before sending and > > forgot to remove that. Yes! This is exactly it. Thanks :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Recursive class | can you modify self directly?
On Wednesday, July 10, 2013 9:33:25 PM UTC+2, Terry Reedy wrote: > On 7/10/2013 4:58 AM, Russel Walker wrote: > > > > > There is the name x and the class instance (the object) which exists > > > somewhere in memory that x points to. self is just another name that > > > points to the same object (not self in general but the argument > > > passed to the self parameter when a method is called). However if the > > > code inside the method reassigns self to some other object, it > > > doesn't change the fact that x still refers to the original object. > > > So self is just a local variable (an argument). > > > > Yes, parameters *names* are the initial local names of the function. > > Calling the first parameter of instancemethods 'self' is a convention, > > not a requirement. > > > > > The name self has no > > > relevance to to the name x other than the fact that they point to the > > > same object. So reassigning self has no effect on x. But modifying > > > the object that self points to, does affect x because it points to > > > the same object. Is this correct? > > > > Yes. Multiple names for one objects are 'aliases'. Being able to modify > > a object with multiple names in different namespaces is both a boon and > > bug bait. > > > > > So when you call x.somemethod() it's not passing x as the self > > > > Python does not pass'x': it is 'call-by-object', not 'call-by-name'. > > > > > argument, it's actually passing the object that x points to as the > > > self argument. And that object has know knowledge of the fact that x > > > points to it, or does it? > > > > Some objects (modules, classes, functions) have definition names > > (.__name__ attributes) that are used in their representations (as in > > tracebacks). But they have no knowledge of their namespace names. > > > > > > > > -- > > Terry Jan Reedy Thanks Terry, I did read all that twice just to make sure it sunk in and it was really clear and helpful. -- http://mail.python.org/mailman/listinfo/python-list
Re: Recursive class | can you modify self directly?
I've been mucking around with this silly class pretty much the whole day and my eyes are about closing now so this is the solution for now I think. Please feel free to drop any suggestions. I think I mostly just ended up shaving off allot of extraneous responsibility for the class, that and inheriting from list. I wanted to try it and it seems to fit (I think). Maybe tomorrow I'll try it inheriting from instead since that is immutable. Should've probably thought of that before right this moment, as I had quite a time with "maximum recursion depth exceeded". class LRExpression(list): """ Construct for 'left to right' algebraic expressions. """ def __init__(self, *args): list.__init__(self, args[:1]) for x in args[1:]: self.append(x) def __str__(self): return '(%s)' % ' '.join(map(str, self)) def evaluate(self): return eval(str(self)) def append(self, x): if len(self) < 3: list.append(self, x) else: oldself = LRExpression(*self) self.__init__(oldself) self.append(x) def test(): a = LRExpression(1) a.append('+') a.append(2) a.append('*') a.append(3) try: print 'repr:', repr(a) print 'str:', a print "should be 9:", a.evaluate() except Exception as er: print er -- http://mail.python.org/mailman/listinfo/python-list
Re: xslice idea | a generator slice
...oh and here is the class I made for it. class xslice(object): ''' xslice(seq, start, stop, step) -> generator slice ''' def __init__(self, seq, *stop): if len(stop) > 3: raise TypeError("xslice takes at most 4 arguments") elif len(stop) < 0: raise TypeError("xslice requires atleast 2 arguments") else: start, stop, step = (((0,) + stop[:2])[-2:] + # start, stop (stop[2:] + (1,))[:1])# step stop = min(stop, len(seq)) self._ind = iter(xrange(start, stop, step)) self._seq = seq def __iter__(self): return self def next(self): return self._seq[self._ind.next()] Although now that I think about it, it probably should've just been a simple generator function. -- http://mail.python.org/mailman/listinfo/python-list
xslice idea | a generator slice
Just some dribble, nothing major. I like using slices but I also noticed that a slice expression returns a new sequence. I sometimes find myself using them in a for loop like this: seq = range(10) for even in seq[::2]: print even (That's just for an example) But wouldn't it be a bit of a waste if the slice expression returns a whole new list just when all you want to do in this case is iterate over it once? I suppose you could get around that will a little more code like: seq = range(10) for x in xrange(0, len(seq), 2): print seq[x] But it would be nice there was a way to iterate over a 'slice' of sorts, that would act as a generator. So I tried my handle at a little class called xslice (the x from xrange to indicate its a generator (although I'm not sure if that's technically correct)). With it, instead of the above example you can do: seq = range(10) for even in xslice(seq, 0, len(seq), 2): print even It would be more or less like using xrange. I know the syntax is not that much of an improvement over just using exrange and retrieving items by index, but it's the concept I'm looking at. Do you think this or something like be a builtin in the future? -- http://mail.python.org/mailman/listinfo/python-list
Re: xslice idea | a generator slice
> > def __init__(self, seq, *stop): > > > > Wouldn't it be better if it has the same signature(s) as itertools.islice? That's actually what I was going for, except I was modeling it after range, but that was the only way I knew to implement it. > > if len(stop) > 3: > > > raise TypeError("xslice takes at most 4 arguments") > > > elif len(stop) < 0: > > > > How would len(stop) be negative? Yes, that should've been len(stop) < 1. > Or you can use itertools.imap: > > > > def xslice(sequence, start_or_stop, *args): > > indices = xrange(*slice(start_or_stop, *args).indices(len(sequence))) > > return imap(sequence.__getitem__, indices) > > > > > > Oscar I like the way you did that with imap, although I still like my parameter implementation. To confess, this is the second time I've made the mistake of trying to implement generator like functionality of a builtin when there already is on in itertools. Need to start studying that module abit more I think. I'm looking at the docs now and I see there are actually a couple of isomethings(). -- http://mail.python.org/mailman/listinfo/python-list