Re: Spliting a string on non alpha characters

2006-09-23 Thread bearophileHUGS
stdazi: The RE-based solutions look good. Here is a pair of alternative solutions: s1 = 'foo bar- blah/hm.lala' r1 = ['foo', 'bar', 'blah', 'hm', 'lala'] s2 = 'foobbbar.. xyz' r2 = ['foo', 'bbbar', 'xyz'] table = "".join((c if c.isalpha() else " " for c) in map(chr, range(256))) #table = ""

Re: newbie IronPython compiled scripts speed question

2006-09-24 Thread bearophileHUGS
dtlog: > So the question is, should I switch to IronPython and compile > my scripts, or learn to use something like pyinline or Psyco? Learning to use Psyco is very easy, for a basic usage you just have to put in your code: import psyco psyco.full() For a better usage you can do: psyco.bind(funct

Ordered dicts

2006-09-26 Thread bearophileHUGS
I have found that in certain situations ordered dicts are useful. I use an Odict class written in Python by ROwen that I have improved and updated some for personal use. So I'm thinking about a possible C version of Odict (maybe fit for the collections module). On a 32 bit Win Python 2.5 requires

Re: Ordered dicts

2006-09-26 Thread bearophileHUGS
Thank to Neil Cerutti and Duncan Booth for the answers. I have not tried that C AVL implementation yet. Duncan Booth: > but for your ordered dictionary if you did that you would have > to fix up the linked list. To fix the list in constant time you probably need a doubly-linked list, this requir

Re: Ordered dicts

2006-09-27 Thread bearophileHUGS
Steve Holden: I forgot a detail: in the Python version of Odict I use element deletion is O(n). You need a second dict to improve that (or a duble linked list of hashing operations, see below). > FYI there was a *long* discussion around the need for Speed sprint about > implementing ordered dicts

Re: Questions on Using Python to Teach Data Structures and Algorithms

2006-09-27 Thread bearophileHUGS
efrat: >1. What exactly is a Python list? A dynamic array that can grow geometrically on the right. >If one writes a[n], then is the complexity Theta(n)? If this is O(1),< It is O(1). >then why was the name "list" chosen? I'd too love to know why the wrong "list" name was chosen for them, i

Re: Can string formatting be used to convert an integer to its binary form ?

2006-09-28 Thread bearophileHUGS
Mirco Wahab: > But where is the %b in Python? Python doesn't have that. You can convert the number to a hex, and then map the hex digitds to binary strings using a dictionary, like this: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440528 Bye, bearophile -- http://mail.python.org/mai

Re: Can string formatting be used to convert an integer to its binary form ?

2006-09-28 Thread bearophileHUGS
Frederic Rentsch: > Good idea, but shorter with -> > >>> SE.SE ('se_definition_files/int_to_binary.se') ('%X' % 987654321) > '0011101011000110100010110001' Note that your version keeps the leading zeros. Have you tested the relative speeds too? (I'll probably have to learn to use SE.) Bye, b

Re: builtin regular expressions?

2006-09-30 Thread bearophileHUGS
Thorsten Kampe: > And the simple reason why Regular Expressions are not a part of the > core Python language is that Regular Expressions are overrated. They > are simply not the preferred tool for every kind of text manipulation > and extraction. And their syntax is ugly and low level, they are di

Re: builtin regular expressions?

2006-10-01 Thread bearophileHUGS
Jorgen Grahn: > However, there is a set of common problems which would be hell to solve > without regexes. I agree, and I think no one is thinking about dropping REs from Python stdlib. Here people are mostly talking about what's better between having them in the stdlibs instead of inside the core

Re: __init__ style questions

2006-10-02 Thread bearophileHUGS
Will McGugan: > I am writting a Vector3D class as a teaching aid (not for me, for > others), and I find myself pondering over the __init__ function. I want > it to be as easy to use as possible (speed is a secondary > consideration). If optimizations are less important, then don't use __slots__, i

Re: How to coerce a list of vars into a new type?

2006-10-02 Thread bearophileHUGS
Matthew Wilson wrote: > I want to verify that three parameters can all be converted into > integers, but I don't want to modify the parameters themselves. To do what you need you can try this: def f(a, b, c): map(int, [a, b, c]) ...code... Bye, bearophile -- http://mail.python.org/mail

Re: Sort by domain name?

2006-10-02 Thread bearophileHUGS
Tim Chase: > to give you a sorting function. It assumes http rather than > having mixed url-types, such as ftp or mailto. They're easy > enough to strip off as well, but putting them back on becomes a > little more exercise. With a modern Python you don't need to do all that work, you can do: s

Re: Sort by domain name?

2006-10-02 Thread bearophileHUGS
js: > All I want to do is to sort out a list of url by companyname, > like oreilly, ask, skype, amazon, google and so on, to find out > how many company's url the list contain. Then if you can define a good enough list of such company names, you can just do a search of such names inside each url.

Re: How to coerce a list of vars into a new type?

2006-10-02 Thread bearophileHUGS
Me: > > def f(a, b, c): > > map(int, [a, b, c]) > > ...code... Robert Kern: > That won't do anything since the names a, b, and c are never rebound. I think you are wrong. Try to give a "35.0" or a "hello" to that function f, and see the results. What it does is to: "verify that three par

Re: How to coerce a list of vars into a new type?

2006-10-02 Thread bearophileHUGS
Björn Lindström: > I would probably put that map in an assert statement, to make the > intention clearer. Isn't putting an explanation comment before that line enough? Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: zeta function for complex argument

2006-10-02 Thread bearophileHUGS
[EMAIL PROTECTED] wrote: > Quick question: I'm wondering if there is, Somewhere Out There, a > Python implementation of the Riemann zeta function for complex > argument...? It seems that Scipy contaisn zeta too: http://www.rexx.com/~dkuhlman/scipy_course_01.html#special Search for "Other Special

Re: php and python: how to unpickle using PHP?

2006-10-02 Thread bearophileHUGS
Ted Zeng: > I store some test results into a database after I use python > To pickle them (say, misfiles=['file1','file2']) > Now I want to display the result on a web page which uses PHP. > How could the web page unpickle the results and display them? > Is there a PHP routine that can do unpickle

Re: text file parsing (awk -> python)

2006-11-22 Thread bearophileHUGS
Peter Otten, your solution is very nice, it uses groupby splitting on empty lines, so it doesn't need to read the whole files into memory. But Daniel Nogradi says: > But the names of the fields (node, x, y) keeps changing from file to > file, even their number is not fixed, sometimes it is (node,

Re: regex problem

2006-11-22 Thread bearophileHUGS
> > line is am trying to match is > > 1959400|Q2BYK3|Q2BYK3_9GAMM Hypothetical outer membra29.90.00011 1 > > > > regex i have written is > > re.compile > > (r'(\d+?)\|((P|O|Q)\w{5})\|\w{3,6}\_\w{3,5}\s+?.{25}\s{3}(\d+?\.\d)\s+?(\d\.\d+?)') > > > > I am trying to extract 0.0011 value from

Abelson and Python

2006-11-22 Thread bearophileHUGS
While studying the SICP video lectures I have to twist my mind some to completely understand the lessons. I implement the programs shown there in both Python and Scheme, and I find the Python implementations simpler to write (but it's not a fair comparison because I know very little Scheme still).

Re: Abelson and Python

2006-11-22 Thread bearophileHUGS
[EMAIL PROTECTED]: > No surprise to anyone who's ever tried to use MIT Scheme. Be careful, such assertions are often flamebait. I am using DrPython (I think they were using it at MIT too lately), and it is very very good IDE, it produces executables on the fly, it has a visual debugger with some

Re: AVL Balancing

2006-11-22 Thread bearophileHUGS
scbauer wrote: > This is one of the errors that im getting > Traceback (most recent call last): > File "", line 1, in > t.insert(5) > File "/Users/stevenbauer/Desktop/AVL.py", line 68, in insert > stack.append(current) > NameError: global name 'stack' is not defined def __init__(s

Re: Abelson and Python

2006-11-22 Thread bearophileHUGS
[EMAIL PROTECTED]: > Haven't heard of that one, although I've got DrScheme. Right, sorry, I meant that one :-) > I find that hierarchy extremely annoying. I don't see the need for it. > I never use OOP in Python yet there's no need for me to have a > stripped down version, I just don't use it.

Re: Abelson and Python

2006-11-22 Thread bearophileHUGS
markscottwright: > I love Python as much as the next guy, but I > just don't see how SICP can be done in Python. The contents of the course are probably different, they work on robotics... Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: changing list items

2006-11-22 Thread bearophileHUGS
A possibile first solution: >>> alist = ['a','b','c','e','d','f'] >>> inf, sup = 2, 4 >>> alist[inf:sup] = ["t"] * (sup - inf) >>> alist ['a', 'b', 't', 't', 'd', 'f'] Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Abelson and Python

2006-11-22 Thread bearophileHUGS
Paddy: > Is the MIT course syndicated to Universities around America or something? > (Is your name pronounced Beer-owe-file, or Bear-oh-fi-lee, I don't know. > I too have heard about the MIT course changing to Python elsewhere and > wanted to know why it was talked about so much? I don't know w

Re: python gaining popularity according to a study

2006-11-23 Thread bearophileHUGS
[EMAIL PROTECTED]: > Python is the 7th most commonly used language, up from 8th. > The only one gaining ground besides VB in the top 10. It also shows that Ruby is gaining even more, and D is (gladly) growing too. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Graph Data Structures

2006-11-25 Thread bearophileHUGS
Szabolcs Nagy: > i haven't read your code, but there are many graph implementations in > python. > in case you haven't found these yet: > http://wiki.python.org/moin/PythonGraphApi > > if you only want to do some analysis i think you need this one (as it's > pretty complete and simple): > https://n

Re: problem about list indexing

2006-11-26 Thread bearophileHUGS
hollowspook: > how about indexing 1-7, 10 > [range(1:8),10] will generate [[1, 2, 3, 4, 5, 6, 7], 10], instead of > [1, 2, 3, 4, 5, 6, 7, 10] (Note that range(1:8) is a syntax error). You can join and extend lists as you like: >>> range(1, 8) + [10] [1, 2, 3, 4, 5, 6, 7, 10] See also the list.a

Re: Modifying every alternate element of a sequence

2006-11-28 Thread bearophileHUGS
Leo Kislov: > input[1::2] = [-item for item in input[1::2]] > If you don't want to do it in-place, just make a copy: > wanted = input[:] > wanted[1::2] = [-item for item in wanted[1::2]] Very nice solution. I have tried few versions like: from itertools import imap, islice from operator import neg

Re: Remarkable results with psyco and sieve of Eratosthenes

2006-11-30 Thread bearophileHUGS
George Sakkis: > You can also save an attribute lookup for append; just add > append = primes.append > outside of the loop and replace primes.append(x) with append(x) > That should cut down a few fractions of second. We were talking about Psyco, and I think with Psyco (just released for Py 2.5, BT

Re: best way to align words?

2006-11-30 Thread bearophileHUGS
Robert R.: > i would like to write a piece of code to help me to align some sequence > of words and suggest me the ordered common subwords of them [...] > a trouble i have if when having many different strings my results tend > to be nothing while i still would like to have one of the, or maybe, >

Re: best way to align words?

2006-11-30 Thread bearophileHUGS
> This is my first solution try, surely there are faster, shorter, better > solutions... > It creates a graph with the paths of words, then sorts the graph > topologically, Beside possible inefficiencies, this "solution" breaks if words aren't in the correct order, the topological sort can't work.

Re: Factory pattern implementation in Python

2006-12-04 Thread bearophileHUGS
Dennis Lee Bieber: > Presuming the is a type code I'd just set up a list of functions: > Then create a dictionary of them, keyed by the code > processors = { "1" : process_1, > "2" : process_2, > > "x" : process_x } Jus

Re: merits of Lisp vs Python

2006-12-08 Thread bearophileHUGS
[EMAIL PROTECTED]: > Sorry, I missed something here. Why do you need a release to have these > sorts of things? Can't you just expand the language via macros to > create whatever facility of this sort you need... Oh, sorry. You CAN'T > expand the language Too bad. I guess waiting for Guido to f

Re: merits of Lisp vs Python

2006-12-08 Thread bearophileHUGS
[EMAIL PROTECTED]: > Sorry, I missed something here. Why do you need a release to have these > sorts of things? Can't you just expand the language via macros to > create whatever facility of this sort you need... Oh, sorry. You CAN'T > expand the language Too bad. I guess waiting for Guido to f

Re: merits of Lisp vs Python

2006-12-09 Thread bearophileHUGS
Andrea Griffini>Is this worth investigation or it has already been suggested/tried ?< Recently some people around the net have discussed about similar ideas as a possible way to speed up Ruby interpreters a lot. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: len() and PEP 3000

2006-12-09 Thread bearophileHUGS
Colin J. Williams: > Why not replace the __len__ method with a len property for strings, > lists, tuples, dictionaries etc. __len__ is not very special and the > property len eliminates the redundant parentheses. You mean something like: >>> "ab".len, [1, 2, 3].len (2, 3) In the given page Guido

Re: speed of python vs matlab.

2006-12-14 Thread bearophileHUGS
Chao, you can also try Psyco, applied on functions, and when necessary using its metaclass too. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: automatically grading small programming assignments

2006-12-14 Thread bearophileHUGS
Brian Blais, just an idea. Create an online form to upload the tiny program(s). Such programs can be one for file. Then on your PC you can run a script that loads each of such programs, and runs a good series of tests, to test their quality... Such tests can be about all things, speed, coding quali

Re: Writing and reading variables to/from flat file

2006-12-15 Thread bearophileHUGS
Geoffrey Clements: > readfile = open('prefs').readlines() > for line in readfile: > print line > eval(line) > print Basic Instead of using eval, using a plain dict may be a better solution. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: AI library

2006-12-15 Thread bearophileHUGS
Gabriel Genellina: > This is more stylish, but I prefer to use isxxx() or hasxxx() for > functions that return booleans. Lisp-like languages allow the ending ? or !, I think Ruby allows the ending ? too (allowing it with Python may be positive). Mathematica usually uses an ending uppercase Q, like

Re: Shed Skin - Does it break any Python assumptions?

2006-12-18 Thread bearophileHUGS
Jean-Paul Calderone: > So yes, it seems that what ShedSkin supports is pretty distant from what > a seasoned Python developer might expect, aside from syntactic constructs. At the moment SS doesn't allow to change the type of a variable during its lifetime, but SS is a moving target, maybe in the

array, a better shell

2006-12-20 Thread bearophileHUGS
For array.array "B" means unsigned char, and such arrays accept to be initialized from (str) strings too, this is quite useful: >>> from array import array >>> a = array("B", "hello") But it seems such capability isn't shared with the append: >>> a.extend("hello") Traceback (most recent call las

Re: array, a better shell

2006-12-20 Thread bearophileHUGS
Steven D'Aprano: > No you're not. You're describing a quite complicated shell. You're > describing a hypothetical shell with features other actual shells don't > have, so therefore it can't possibly be as simple as possible. You are right, it's not really simple, but: - It has just the basic funct

Re: array, a better shell

2006-12-20 Thread bearophileHUGS
Duncan Booth: > Later you can click on them and bring them back > to the bottom of the input buffer for further editing (so no confusing > output appearing out of order), I think that's worse, not better. You end with a messy final "document" (log), so finding things into it (during the editing to

Re: Decorator for Enforcing Argument Types

2006-12-21 Thread bearophileHUGS
Chris wrote: > I'm not sure if this has been done before, I think this is the best implementation: http://oakwinter.com/code/typecheck/ I have never used it, but it seems well done. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Multi-line docstrings

2006-12-23 Thread bearophileHUGS
Duncan Booth: > Not spuriously included: included by design, but sometimes annoying. Then it's a design decision I don't understand... Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: some OT: how to solve this kind of problem in our program?

2006-12-24 Thread bearophileHUGS
Paul McGuire: > This little framework takes about 4.5 seconds, but with > psyco, cuts down to about 1.3 seconds. > > st = time.time() > result = [] > for p in permutations(range(1,10)): > aresult = func(p) > if aresult is not None and aresult not in result: > result.append(aresult)

Re: some OT: how to solve this kind of problem in our program?

2006-12-24 Thread bearophileHUGS
Using Psyco this version is much faster, you can test it on your PC compared to the other one (the whole running time, Psyco compilation too): Psyco is unable to speed up generator functions, so you have to return true lists. Giving the func to the permutation function, you can avoid lot of list co

Re: some OT: how to solve this kind of problem in our program?

2006-12-26 Thread bearophileHUGS
For people that will read the posts in the future, there is a little bug (it doesn't change the output of this program): items = alist[:] Has to be: alist = alist[:] Sorry, bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: loose methods : Smalltalk asPython

2006-12-27 Thread bearophileHUGS
Steven D'Aprano: > You can't modify the built-in classes. I'm not sure that it is a good idea > to allow built-ins to be modified. When I see an int, I like the fact that > I know what the int can do, and I don't have to worry about whether it has > been modified by some piece of code elsewhere. I

Re: Scaling pictures

2006-12-28 Thread bearophileHUGS
Kajsa Anka: > I found the Python Imaging Library but before I dive into that I would like > to know if there is a better way of doing this. PIL is very fit for that. Note that it creates thumbnails already by itself, you can use that for bigger images too. Bye, bearophile -- http://mail.python.

Re: answers.py v0.0.1 - source

2006-12-28 Thread bearophileHUGS
Marc 'BlackJack' Rintsch: You give lot of comments and I agree with most of them. > One idiom to solve this is: > def __init__(self, answers=None): > self.answers = answers or dict() I suggest to avoid such usage of or/and (expecially for newbies), that is triky and can produce bugs,

__getattr__ possible loop

2006-12-28 Thread bearophileHUGS
I have tried this, with Psyco it segfaults, and with Python 2.5 (on Win) hangs the interpreter, is it possible to improve the situation? class T(object): def __getattr__(self, x): dir(self) #import psyco #psyco.full() T().method() (Probably dir calls __getattr__). Bye, bearophile -- http://m

Re: __getattr__ possible loop

2006-12-28 Thread bearophileHUGS
Maksim Kasimov: > how to improve the situation depends on what do you expect to get by calling > "T().method()" You are right, sorry for being cryptic. I think that's a kind of bug of Python (produced maybe by an infinite loop), so an improvement can be a traceback or some automatic breaking of t

Re: Writing more efficient code

2007-01-01 Thread bearophileHUGS
Jon Harrop: > OCaml's pattern matcher is very sophisticated and very fast. You'll probably > shrink your code by several fold whilst also having it run a few orders of > magnitude faster and having it statically checked, so it will be more > reliable. You seem to forget some months of time to lear

Re: Writing more efficient code

2007-01-01 Thread bearophileHUGS
Jon Harrop: > I think most people could pick up the core ideas in a day and start writing > working programs. Probably I am not that intelligent, I probably need some months :-) But that language has many good sides, and one day I'll probably try to learn it a bit. > Mathematica is expensive but

Re: Writing more efficient code

2007-01-02 Thread bearophileHUGS
Jon Harrop: > I think this sort of functionality would be a welcome addition to Python. I don't know. > Perhaps it can be written in Python? Pyparsing and beautifulsoup show that practically useful parsing modules can be done using Python alone too. Set module of Python 2.3, translated to C in

Re: Iterate through list two items at a time

2007-01-02 Thread bearophileHUGS
Few alternative solutions (other are possible), I usually use a variant of the first version, inside a partition function, the second variant is shorter when you don't have a handy partition() function and you don't want to import modules, and the forth one needs less memory when the data is very l

Re: Sorting on multiple values, some ascending, some descending

2007-01-03 Thread bearophileHUGS
Raymond Hettinger: > The simplest way is to take advantage of sort-stability and do > successive sorts. For example, to sort by a primary key ascending and > a secondary key decending: >L.sort(key=lambda r: r.secondary, reverse=True) >L.sort(key=lambda r: r.primary) That's probably the fa

Re: static object

2007-01-03 Thread bearophileHUGS
That looks like some kind of singleton. Why don't you use a module instead of a class? Another solution is to define your data as class attributes. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Sorting on multiple values, some ascending, some descending

2007-01-03 Thread bearophileHUGS
dwelden wrote: > >L.sort(key=lambda r: r.secondary, reverse=True) > >L.sort(key=lambda r: r.primary) > Excellent! That looks just like what I needed. Note that there is the (probably little used) operator.attrgetter() too, with that you can avoid the possibly slow lambda: L.sort(key=attrge

Re: code optimization (calc PI) / Full Code of PI calc in Python and C.

2007-01-03 Thread bearophileHUGS
Michael M.: > * The C is very fast, Python not. > * Target: Do optimization, that Python runs nearly like C. Python can't be fast as C for that kind of programs. Note that your original C program gives less digits than the Python program. Your original takes about ~15.2 s on my PC. The following v

Re: Why less emphasis on private data?

2007-01-07 Thread bearophileHUGS
Paul Rubin: > Python certainly makes you spend more of your attention worrying > about possible attribute name collisions between classes and their > superclasses. And Python's name mangling scheme is leaky and > bug-prone if you ever re-use class names. > Trouble with this is you can have two cla

Re: I want to learn

2007-01-07 Thread bearophileHUGS
[EMAIL PROTECTED]: > I am looking for a python guru who has instant messenger or gtalk or > whatever who can meet me > online in the mornings, give me some direction for the day and then > answer some questions here and there online throughout the day. Maybe a Python gury isn't necessary, maybe a

Re: recursive function

2007-01-08 Thread bearophileHUGS
First possible solution: def rloop(seqin, comb): # xcross product recipe 302478 by David Klaffenbach if seqin: for item in seqin[0]: newcomb = comb + [item] for item in rloop(seqin[1:], newcomb): yield item else: yield comb data

isplit

2006-01-26 Thread bearophileHUGS
I have a file of lines that contains some extraneous chars, this the basic version of code to process it: IDtable = "".join(map(chr, xrange(256))) text = file("...", "rb").read().translate(IDtable, toRemove) for raw_line in file(file_name): line = raw_line.translate(IDtable, toRemove) ... A

Re: Efficient Find and Replace

2006-01-27 Thread bearophileHUGS
>Because L.index() and L[x:x] both take O(N) time in the worst case. Why do you think L[x:x] can be O(N)? This looks O-linear enough to me: >>> from random import choice >>> L = [choice("ab") for i in xrange(10)] >>> L ['b', 'b', 'b', 'a', 'b', 'a', 'b', 'a', 'a', 'a'] >>> for x in xrange(len(L)

Re: Efficient Find and Replace

2006-01-27 Thread bearophileHUGS
>But how is L[x] = Y an O(1) operation. Given x finding L[x] would require to >traverse x nodes in the list. Python list is a deceptive name, because they are 1D arrays of pointers. Maybe they are called lists because array(...) is shorter than list(...). Bye, bearophile -- http://mail.python.

Re: Question about idioms for clearing a list

2006-01-31 Thread bearophileHUGS
Diez B. Roggisch: > The reason is that l = [] just rebinds a new object (a list, but it could be > anything) to a name, while l[:] = [] will alter the object _referred_ to by > l. That is a HUGE difference! In my programs I have seen that there is another practical difference between version 1 and

Re: A class with built-in doctest feature ?

2006-02-02 Thread bearophileHUGS
The idea looks interesting, but you can also design a couple of functions that scan the docstrings of a given class and its methods to produce what you need: doctestAll(C) toHtml(C) This is probably simpler and gives similar results. Bye, bearophile -- http://mail.python.org/mailman/listinfo/p

Re: python's library support

2006-02-04 Thread bearophileHUGS
Robert Kern>And several others if you google a bit. Yes: http://sourceforge.net/projects/pynetwork/ Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

To paletted image

2006-02-10 Thread bearophileHUGS
Hello, this time I have a question about PIL usage, maybe if Lundh has some time he can answer me. I am experimenting different color quantization algorithms, so having computed the palette with a clustering function, I use the code below to quantize the original image to produce an image without d

Re: Create dict from two lists

2006-02-10 Thread bearophileHUGS
py: > Thanks, itertools.izip and just zip work great. However, I should have > mentioned this, is that I need to keep the new dictionary sorted. A Python dictionary is an unsorted data structure, so you cannot have it sorted as you please. (I have seen that lot of people ask for a sorted dictiona

Re: Shortest prime number program

2006-02-11 Thread bearophileHUGS
This is a little shorter :-) [2]+[x for x in range(2,99)if 2**x%x==2] Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Is python very slow compared to C

2006-02-11 Thread bearophileHUGS
Yes this language is very slow, but frequently this isn't a problem, because you are using fast functions/libraries written in C, or you are doing I/O bound operations. And Psyco, numeric/numarray, ShedSkin can help in some other cases (Pyrex and other solutions allow you to mix in lower level lang

Re: Is python very slow compared to C

2006-02-12 Thread bearophileHUGS
Steven D'Aprano>Very slow to do what, compared to what? The decay time of the tau meson?< Probably every answer I can give you is wrong for you, so answering is almost useless... In this thread we have already given the most pertinent answers to the original question from Diffuse. I can show you t

Re: processing limitation in Python

2006-02-14 Thread bearophileHUGS
Using CPython or GMPY with a smarter algorithm in acceptable time you can find that: 12345678987654 == 2 * 3 * 2057613164609 It's a very big number to factorize with that naive algorithm, so the program hangs... (I have used an online factoring service). Bye, bearophile -- http://mail.python.o

Re: how to write a C-style for loop?

2006-02-15 Thread bearophileHUGS
Steven D'Aprano>That's a completely different question, so of course it has a completely different answer. Here is one way:< Other versions without the creation of a list: for i in (2**n for n in xrange(6)): do_something(i) for i in (1

Re: define loop statement?

2006-02-17 Thread bearophileHUGS
David Isaac: > I would like to be able to define a loop statement > (nevermind why) so that I can write something like > > loop 10: > do_something > > instead of > > for i in range(10): > do_something > > Possible? If so, how? It seems that you are looking for macros; maybe Logix "languag

Re: Python vs. Lisp -- please explain

2006-02-19 Thread bearophileHUGS
The question about the speed is interesting. Generally the more dynamic and flexible your language is, the slower are the programs it produces. Lisp is almost unique in such matters (and in this regard it's maybe better than CPython) because it allows the programmer to mix and blend different level

Re: Python vs. Lisp -- please explain

2006-02-19 Thread bearophileHUGS
Luis M. González>[Shed-Skin] ... but so far it looks great (only one developer though..).< Two developers, I am there too :-) I think people aren't much interested so far because there aren't good ways to link/join/use SSPython compied code from CPython code. A good solution is probably to: - Dev

Re: deriving from float or int

2006-02-21 Thread bearophileHUGS
Probably this is interesting for you: http://home.tiscali.be/be052320/Unum.html I think its API can be improved, but it can be used. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: how to break a for loop?

2006-02-21 Thread bearophileHUGS
This time it seems that using itertools gives slower results, this is the test code: import itertools as it from operator import __not__ def trim_leading_zeros(seq): if not seq: return seq for pos, el in enumerate(seq): if el != 0: break if seq[pos] == 0:

With pyMinGW

2006-02-21 Thread bearophileHUGS
To use Pyrex, SWIG and the like on a Win2K I have followed this way: http://jove.prohosting.com/iwave/ipython/pyMinGW.html I already had MinGW 3.4.2, so I have decompressed the Python 2.4.2 sources, I have merged in the pyMinGW patch, and I have run the global compilation with: make -f python24.

Re: With pyMinGW

2006-02-22 Thread bearophileHUGS
Thank you for your answers, Khalid. > It seems you may be using an old version of pyMinGW, I have downloaded it yesterday from your site. > the relevant part dealing with include directories in zlib.mak > should read now as follows: I have checked, and that relevant part is the same in my zlib

Re: Python vs. Lisp -- please explain

2006-02-22 Thread bearophileHUGS
Carl Friedrich Bolz: > Indeed, there are similarities to pyrex. Of course in pyrex you have to > give the types yourself, but since the type inference engine of PyPy can > sometimes be hard to understand this is maybe not the worst trade-off. > A nice advantage of the PyPy approach would be that yo

Re: What's up with this code?

2006-02-22 Thread bearophileHUGS
Gregory Petrosyan: > coefs.extend(it.chain(rcoefs1, rcoefs2)) #? -- here is magic Can't you just do a couple of extend? Something like: coefs.extend(rcoefs1) coefs.extend(rcoefs2) This looks simpler and probably faster too. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-lis

Re: Pythonic gui format?

2006-02-22 Thread bearophileHUGS
Sorry for the late reply, I have some ideas about a possible GUI toolkit design (that works with one already done like GTK), I'll probably show them here. In the meantime I can show this one: http://thinlet.sourceforge.net/home.html I like it because the way GUIs are defined is quite short. bye,

Re: make a class instance from a string ?

2006-02-23 Thread bearophileHUGS
Bo Yang: > to get an instance of the class 'classname' from a > string , in python , how do I do that ? This is a possibile way: class C: pass c = locals()["C"]() print c Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Pure python implementation of string-like class

2006-02-24 Thread bearophileHUGS
Maybe you can create your class using an array of 'L' with the array standard module. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: Path (graph) shower utility

2006-02-25 Thread bearophileHUGS
Thank you Jorgen, now I understand the question, and the answer isn't difficult :-) Graphviz is good enough for this purpose. >but IIRC there are Python bindings for it as well.< Durumdara can use an email module to extract data, then a graph library to create the graph, and then save the result

Re: sort one list using the values from another list

2006-02-26 Thread bearophileHUGS
Your solution Steven Bethard looks very intelligent, here is a small speed test, because sorting a list according another one is a quite common operation. (Not all solutions are really the same, as Alex has shown). from itertools import izip, imap from operator import itemgetter from random impor

Re: An isalpha() that accepts underscores as well

2006-02-26 Thread bearophileHUGS
This is probably faster: def alfa_(w): return w.replace("_", "a").isalpha() This is another solution, but it's probably slower, you can time it: from string import letters _setalpha = set(letters + "_") def alfa_2(w): return not (set(w) - _setalpha) Bye, bearophile -- http://mail.py

Re: sort one list using the values from another list

2006-02-26 Thread bearophileHUGS
>It's faster on my system because d.keys() is already sorted. But that may not >be the case on other versions of python.< In my version it's a little slower. But what system are you using where keys is already sorted? IronPython maybe? Bye, bearophile -- http://mail.python.org/mailman/listinf

Re: how do I factor a number down to one digit?

2006-02-27 Thread bearophileHUGS
Allan>I hope this isn't too stupid of a question. It's a simple problem, but it's not a stupid question, this is a possible solution: data = "myname" radix = str(sum(ord(c)-96 for c in data)) while len(radix) > 1: radix = str(sum(int(c) for c in radix)) print "The radix of:\n", data, "\n\nIs:

Re: how do I factor a number down to one digit?

2006-02-27 Thread bearophileHUGS
>Sounds like homework to me. Sorry Steven, you may be right, next time I'll be more careful. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list

Re: sort one list using the values from another list

2006-02-27 Thread bearophileHUGS
Following Ron Adam solution (and using [] instead of list() in the last line), this may be a possible solution of the problem, that is often quite fast: def psort16(s1, s2): try: d = dict(izip(s2, s1)) except TypeError: _indices = range(len(s1)) _indices.sort(key=s2

<    1   2   3   4   5   6   7   8   9   10   >