package search

2006-06-11 Thread boris
I have two directories, lib1 and lib2, that both contain the package
foo, one with the submodule mod1
and the other with the submodule mod2:

$ ls lib*/foo/
lib1/foo/:
__init__.py  __init__.pyc mod1.py  mod1.pyc

lib2/foo/:
__init__.py  __init__.pyc mod2.py  mod2.pyc
$

Now this script:

import sys
sys.path.append("lib1")
sys.path.append("lib2")
import foo.mod1

will find the module foo.mod1, while the same script with the two
append-lines interchanged will not:

import sys
sys.path.append("lib2")
sys.path.append("lib1")
import foo.mod1

The error is:

import foo.mod1
ImportError: No module named mod1

So I guess that when Python finds the package foo, it will not look for
it again using the rest of
the search path, even if at that first place the module could not be
found.

Other languages like e.g. Java would find the module mod1 in the second
case too (if Java doesn't
find it in the first place, it will also look for it in the second
place).

This behaviour of Python is very unfortunate, because you always have
to merge your package
trees. In my cvs I have several packages, each in its own cvs module,
all starting with
de.science_computing. Now if I need two of them in a new project, I
will have two package trees
in my cvs sandbox, both starting with de.science_computing. Leaving the
sandbox that way, cvs
will work but Python imports will fail while if I merge all the package
trees, Python will work but cvs
won't.

My questions:
- Have I done anything wrong?
- If not, is this behaviour of Python a bug or intentional?
- If it it intentional, what is the intent?

Thank you for your help
Boris

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: package search

2006-06-11 Thread boris

Sybren Stuvel wrote:
> Simplicity and explicitness. You have two packages 'foo', and it
> simply loads the first one it finds.

Yes, here you are right. It is indeed simple.

Boris

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: package search

2006-06-11 Thread boris

imho wrote:
>
> You just have to put in "__init__.py" in "lib2" (the package directory
> you are "extending"), the following lines:
>
> from pkgutil import extend_path
> __path__ = extend_path(__path__, __name__)
>
> "__path__", in each __init__ module, is a list initialized with the
> module's path, but you can extend it by appending paths where you want
> the interpreter to look for further modules.
> pkgutil.extend_path automatically appends to __path__ all subdirectories
> of directories on sys.path named after the package.
>
> HTH :-)
>
> Diego.

COOL! You just saved me an awful lot of work.

Thanks, Diego!

Boris

-- 
http://mail.python.org/mailman/listinfo/python-list


newbie:this program stops responding after pressing quit button

2007-12-04 Thread Boris
I am using windows vista and python 2.5 .This program stops responding
after pressing quit button. I am not able to figure the problem out.
please help.

from Tkinter import *

def greeting( ):
print 'Hello stdout world!...'

win = Frame(
 )
win.pack( )
Label(win,  text='Hello container world').pack(side=TOP)
Button(win, text='Hello', command=greeting).pack(side=LEFT)
Button(win, text='Quit',  command=win.quit).pack(side=RIGHT)

win.mainloop( )

-- 
http://mail.python.org/mailman/listinfo/python-list


Using utidylib, empty string returned in some cases

2008-01-22 Thread Boris
Hello

I'm using debian linux, Python 2.4.4, and utidylib (http://
utidylib.berlios.de/). I wrote simple functions to get a web page,
convert it from windows-1251 to utf8 and then I'd like to clean html
with it.

Here is two pages I use to check my program:
http://www.ya.ru/ (in this case everything works ok)
http://www.yellow-pages.ru/rus/nd2/qu5/ru15632 (in this case tidy did
not return me anything just empty string)


code:

--

# coding: utf-8
import urllib, urllib2, tidy

def get_page(url):
  user_agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT
5.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727)'
  headers = { 'User-Agent' : user_agent }
  data= {}

  req = urllib2.Request(url, data, headers)
  responce = urllib2.urlopen(req)
  page = responce.read()

  return page

def convert_1251(page):
  p = page.decode('windows-1251')
  u = p.encode('utf-8')
  return u

def clean_html(page):
  tidy_options = { 'output_xhtml' : 1,
   'add_xml_decl' : 1,
   'indent' : 1,
   'input-encoding' : 'utf8',
   'output-encoding' : 'utf8',
   'tidy_mark' : 1,
 }
  cleaned_page = tidy.parseString(page, **tidy_options)
  return cleaned_page

test_url = 'http://www.yellow-pages.ru/rus/nd2/qu5/ru15632'
#test_url = 'http://www.ya.ru/'

#f = open('yp.html', 'r')
#p = f.read()

print clean_html(convert_1251(get_page(test_url)))

--

What am I doing wrong? Can anyone help, please?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Testing against multiple versions of Python

2012-10-19 Thread Boris FELD
Did you take a look at https://www.shiningpanda-ci.com/?

2012/10/19 andrea crotti :
> 2012/10/19 Michele Simionato :
>> Yesterday I released a new version of the decorator module. It should run 
>> under Python 2.4, 2.5, 2.6, 2.7, 3.0, 3.1, 3.2, 3.3. I did not have the will 
>> to install on my machine 8 different versions of Python, so I just tested it 
>> with Python 2.7 and 3.3. But I do not feel happy with that. Is there any 
>> kind of service where a package author can send a pre-release version of her 
>> package and have its tests run againsts a set of different Python versions?
>> I seem to remember somebody talking about a service like that years ago but 
>> I don't remembers. I do not see anything on PyPI. Any advice is welcome!
>>
>>  Michele Simionato
>>
>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>
>
> Travis on github maybe is what you want?
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: open URL in the current tab

2012-12-10 Thread Boris FELD
Don't think that it's possible with webbrowser, you should try with Selenium.

For example with sst (Simple Selenium Test), it open url in current
tab or create a new one if no one exists:

from sst.actions import *
go_to('http://www.ubuntu.com/')

2012/12/10 Jabba Laci :
> Hi,
>
> With the webbrowser module you can open a URL in a new tab. But how
> could I tell Firefox from Python to open a URL in the _current_ tab?
>
> Thanks,
>
> Laszlo
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with unittest2

2012-12-13 Thread Boris FELD
How are you importing unittest2, do you have something like this ?

try:
  import unittest2 as unittest
except ImportError:
  import unittest

If it's the case, you are maybe using default unittest while you think
you are using unittest2.

2012/12/13 Daniel Laird :
> On Thursday, December 13, 2012 3:09:58 PM UTC, Miki Tebeka wrote:
>> On Thursday, December 13, 2012 7:03:27 AM UTC-8, Daniel Laird wrote:
>>
>> > I do am import unittest2 as unittest
>>
>> > NameError: global name 'assertListEqual' is not defined
>>
>> According to the docs 
>> (http://docs.python.org/2/library/unittest.html#unittest.TestCase.addTypeEqualityFunc)
>>  assertListEqual and friends was added in 2.7.
>>
>>
>>
>> You can use assertEuqal, or if you don't care about order 
>> assertEqual(sorted(a), sorted(b)).
>
> Thanks, however I thought by using unittest2 it added the new 2.7 features to 
> 2.6?
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: For Loop in List

2013-01-13 Thread Boris FELD
2013/1/13 Tim Chase :
> On 01/13/13 06:45, [email protected] wrote:
>
 SIZE = 3
 for i in range(len(list1)//SICE):
> ... print list1[i*SIZE:i*SIZE+SIZE]
> ...
> [1, 2, 3]
> [4, 5, 6]
> [7, 8, 9]
> [10, 11, 12]
>

A little shorter and simpler version:
>>> x = x[1:]
>>> for i in range(0,len(x),SIZE):
...  print x[i: i+SIZE]
...
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
[10, 11, 12]

Hope it helps

> Hope this helps,
>
> -tkc
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing Android application using GPS data with Python

2012-04-15 Thread Boris FELD
You can try appaccelerator, it seems to support python and you should be
able to access geolocalisation (according to wikipedia:
https://en.wikipedia.org/wiki/Appcelerator_Titanium)

Le 15 avril 2012 16:44, Noam Peled  a écrit :

> I want to write an Android application using Python. I've found 2 options
> for that: kivy and SL4A. In kivy, at least for now, I can't use the GPS
> data. Anyone knows if I can get the GPS data using SL4A with Python? As I
> understood, one can write commercial apps using kivy. On the other hand,
> with SL4A you must install first SL4A and python on your Android device, so
> I'm not sure it's suitable for commercial apps. And last one, can I use
> funf with python?
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (*args **kwargs) how do I use' em?

2011-06-11 Thread FELD Boris
 A good tutorial will surely help : 
http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/

The idea between *args and *kwargs is to create function (callables) which 
accepts an arbitrary number of anonymous and/or keyword arguments.

It's useful when you want to create a function that will call an another one 
(inheritances or decorators).

Hope this helps,
-- 
Envoyé avec Sparrow (http://www.sparrowmailapp.com/?sig)

Le samedi 11 juin 2011 à 07:01, TheSaint a écrit :

> Hello,
> I'm seldomly writng python code, nothing but a beginner code.
> 
> I wrote these lines >>
> 
> =
> _log_in= mhandler.ConnectHandler(lmbox, _logger, accs)
> multhr= sttng['multithread']
> if multhr:
>  _log_in= mhandler.mThreadSession(lmbox, _logger, accs)
> 
> for svr in servrs:
>  nmsvr, user, pwd, ptcl = servrs[svr]
>  al, dn= sttng['Cfilter']; er= sttng['filter']
>  try:
>  rx.append( _log_in.connect((nmsvr, user, pwd, ptcl, (al, dn, er
>  except ProtocolError:
>  print(svr+ errors['SerProb'])
>  except KeyboardInterrupt:
>  raise SystemExit(errors['YouStop'])
> if multhr:
>  for s in rx:
>  try: s.start()
>  except (ProtocolError, AttributeError):
>  print(svr+ errors['SerProb'])
>  except KeyboardInterrupt:
>  raise SystemExit(errors['YouStop'])
>  for s in rx:
>  try: s.join() # waiting all threads to finish
>  except (ProtocolError, AttributeError):
>  print(svr+ errors['SerProb'])
>  except KeyboardInterrupt:
>  raise SystemExit(errors['YouStop'])
> 
> =
> 
> Surely ugly and I believe that would be a better way to pass the arguments 
> as I mention on the subject.
> Then it should give a dictionary of keywords and some function or a 
> callable. I don't know how to put down these code lines.
> I think I should restructure many points of my data.
> 
> Any suggestion will make me happier :)
> 
> 
> -- 
> goto /dev/null
> -- 
> http://mail.python.org/mailman/listinfo/python-list

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [OSX] side by side python

2011-03-21 Thread FELD Boris
Yes, no problem. Follow the installation normally; if you want to change your 
default python version to a new one, you need to launch "Update Shell 
Profile.command" in your installation path (/Applications/Python X.X/) or 
choose the "Update Shell Profile" during the installation.

No specific problem, i use these Python versions without any problem on mac os 
x : 2.5, 2.6, 2.7, 3.0, 3.1, 3.2.

-- 
FELD Boris
Sent with Sparrow
On lundi 21 mars 2011 at 13:31, Robert wrote: 
> Can I install Python 2.7 and 3.2 (from python.org) side by side on OSX
> without them stepping all over each other?
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: side by side python

2011-03-21 Thread FELD Boris
Yes, i did not mention this solution, using virtualenv is a very good practice, 
but before create a virtualenv with a specific version of python, you must have 
installed it globally, isn't it ?

Regards,
-- 
FELD Boris
Sent with Sparrow
On lundi 21 mars 2011 at 14:45, macm wrote: 
> On Mar 21, 9:31 am, Robert  wrote:
> > Can I install Python 2.7 and 3.2 (from python.org) side by side on OSX
> > without them stepping all over each other?
> 
> Yes, sure! Look for "python environment"
> 
> http://pypi.python.org/pypi/virtualenv
> 
> Regards
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threading with Socket Server

2011-03-23 Thread Boris FELD
I'm not sure to understand what you want. Is it your server process
that will read the shelve file ? You may give more informations about
your problem, but i can give you some hints.

In order to create a TCP server, you can use SocketServer which is in
the builtin library
(http://docs.python.org/library/socketserver.html). I'm not sure about
how shelve manage concurrency, but in my opinion, you'll need to
create a single process or thread which manage read and write
operation in order to avoiding race conditions.

Cheers,
Feld Boris

2011/3/23 T :
> Hello all, I am writing a Windows service that needs to 1) Act as a
> server (TCP), and write to a shelve file, and 2) Read that same shelve
> file every x number of seconds.  My thought is to create 2 separate
> classes (1 for the socket server and writing to the shelve file, and
> another to read the file and perform other requested actions) -
> however, I need to make sure they are both running concurrently.   I'm
> sure threading is involved, but my experience with it has been
> minimal, so any help to steer me in the right direction is greatly
> appreciated.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Validating Command Line Options

2011-03-23 Thread Boris FELD
If you're using argparse, you have a method for that named
"add_mutually_exclusive_group". Tutorial :
http://www.doughellmann.com/PyMOTW/argparse/#mutually-exclusive-options

Cheers,
Feld Boris

2011/3/23 T :
> For a Python script with multiple command line options, what is the
> best way to go about validating that only certain options are used
> together?  For example, say -s, -t, and -v are all valid options, but
> should never be used together (i.e. -s -t would be invalid).  Thanks
> in advance.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dump interpreter history?

2011-03-25 Thread FELD Boris
Take a look at : 
http://ipython.scipy.org/doc/manual/html/interactive/tutorial.html#use-your-input-history

Cheers,
FELD Boris

-- 
FELD Boris
Sent with Sparrow
On vendredi 25 mars 2011 at 22:03, Ken D'Ambrosio wrote: 
> Hey, all. A co-worker asked me a question, and I've got no idea how (or
> if) it can be done. Bottom line: he'd like to save off the text from an
> interpreter session, his thinking being that you've already tried to get
> what you want, and now you just need to gussy it up in an editor.
> 
> Can this be done?
> 
> Thanks!
> 
> -Ken
> 
> 
> 
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python benefits over Cobra

2011-04-05 Thread Boris FELD
Cobra seems interessant, open-source, but the dependance on Mono and
.Net annoy me a bit.

Otherwise, cobra have good ideas, a syntax similar to python.

One thing i really love is the "How-To" and the "Samples" pages on
it's website, i think it's a very good thing for beginners.

FELD Boris

2011/4/5 Colin J. Williams :
> On 05-Apr-11 06:22 AM, Brendan Simon (eTRIX) wrote:
>>
>> I just came across the Cobra language, which appears to be heavily
>> influenced by Python (and other languages). The pitch sounds great. It's
>> supposed to have:
>>
>>   1. Quick, expressive coding
>>   2. Fast execution
>>   3. Static and dynamic binding
>>   4. Language level support for quality
>>
>>
>> http://cobra-language.com/docs/why/
>>
>> http://cobra-language.com/docs/python/
>>
>> I was wondering what advantages Python has over Cobra. I know it's
>> probably a difficult question to answer and depends on specific
>> requirements. All I can think of is:
>>
>>    * Maturity of language
>>          o Robust and tested.
>>          o availability of modules (standard and built-in).
>>          o large community support (commercial and non-commercial).
>>    * No dependence of .NET/Mono
>>          o I don't know if this is an pro or con as I don't know .NET.
>>
>>
>> Presumably the maturity argument would be less significant over time.
>>
>> I'm not sure about the .NET/Mono framework, whether that is good or bad.
>> Sounds good in some situations at least.
>>
>> Any other arguments where Python has benefits over Cobra ??
>>
>> Cheers, Brendan.
>>
> Two questions:
>   1. Is Cobra Open Source?
>   2. The blog ended on October, did he run out of steam?
>
> I liked the '.', in place of '.self', but that's been rejected for Python.
>
> Colin W.
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: learnpython.org - an online interactive Python tutorial

2011-04-20 Thread FELD Boris
Excellent idea,

I've some ideas on specific subjects misunderstood by beginners.

One idea for facilitating the contribution, create a mercurial repository (or a 
git), everyone has not a google account and your contributors will be 
developers so they should use a SCM.

Once again, it's an excellent idea and, when the tutorials were expanded 
enough, i should be good to integrate it with python.org website (but it's more 
a dream than something else...)

One question, if i want to write a tutorial about import mechanism, how can i 
manage the file system ?

Nice work !
-- 
FELD Boris
Sent with Sparrow
On mercredi 20 avril 2011 at 19:57, Matty Sarro wrote: 
> Awesome project, I really like it. I'll see if I can't help adding
> some material that's missing when I get on the train.
> Keep up the great work!
> 
> On Wed, Apr 20, 2011 at 1:15 PM, Ron  wrote:
> > Hey everyone.
> > 
> > I've written an online interactive Python tutorial atop Google App Engine: 
> > http://www.learnpython.org.
> > 
> > All you need to do is log in using your Google account and edit the wiki to 
> > add your tutorials.
> > 
> > Read more on the website.
> > 
> > Thanks for your help, and I would appreciate if you help me spread the 
> > word, and give me feedback on the website.
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: on slices, negative indices, which are the equivalent procedures?

2021-08-06 Thread Boris Dorestand
Jach Feng  writes:

>> > s = "Jack Brandom" 
>> > s[3 : -13 : -1] 
>> >> 'kcaJ' 
>> >> I have no idea how to replace that -13 with a positive index. Is it 
>> >> possible at all? 
> That's not possible because a positive index is relative to the leftmost item > 0

And the middle index is always exclusive, so we can't go to the left of
0 and remain positive.  Okay, I think that answers it.  It's not
possible at all.

> Below is some rules of slice usage which I collected sometimes ago.
> -
> slice s[i:j:k]
>  The result is from start index i to stop index j (excluded) in step k 
> (default is 1).  i, j, k can be positive or negative. For example:  s = [1,  
> 2,  3,  4,  5]
> 1. Positive index is relative to the leftmost item (0), negative index is 
> relative to the rightmost item (-1). Note: out-of-range index is valid.
>s[-4:5] == s[1:5] == [2,3,4,5]  # index 5 is out-of-range
>s[4:-6:-1] == [5,4,3,2,1]  # index -6 is out-of-range
> 2. The default index of i and j (When index is omitted) was decided by the 
> sign of k. 
> For positive k, the start index is 0 (the leftmost item) and the stop 
> index is the one after the rightmost item.
>s[:3] == s[0:3] == [1,2,3]
>s[1:] == s[1:5] == [2,3,4,5]
>For negative k, the start index is -1 (the rightmost item) and the stop 
> index is one ahead of the leftmost item 
>s[:2:-1] == s[-1:2:-1] == [5,4]
>s[3::-1] == s[3:-6:-1] == [4,3,2,1]
> 3. The items pick-up order was decided by the sign of k. For positive k, the 
> direction is toward the right. For negative k, it is toward the left.
> s[1:4] == [2,3,4]
> s[3:0:-1] == [4,3,2]
> 4. Invalid slice will return an empty []
> s[2:0] == []

Thank you.  This helped a bit more.  So now I propose the following
simulation.  Can anyone simplify this?  Thanks!

--8<---cut here---start->8---
def mySlice(it, beg, end, step = 1):
  """Simulates Python slices."""
  if step is None: 
step = 1
  assert step != 0, "step = 0 not allowed"
  ret = []
  cur = beg
  if step > 0:
return mySlicePositiveStep(it, beg, end, step)
  else:
return mySliceNegativeStep(it, beg, end, step)

def mySliceNegativeStep(it, beg, end, step = -1):
  """Assume STEP is always negative.  The difference between positive
and neative step is that it reverts the orientation of the loop, but the
loop always begins at BEG, never at END.
  """
  ret = []
  if beg == None:
beg = -1
  if end == None:
end = -len(it) - 1
  if beg >= 0: # how to translate positive indices to negative ones
beg = -len(it) + beg
  if end >= 0:
end = -len(it) + end
  cur = beg # begin here
  while cur > end: # stop as soon as you arrive at END
ret.append(it[cur])
cur += step
  return ret

def mySlicePositiveStep(it, beg, end, step = 1):
  """Assume STEP is always positive.  But if BEG or END are
negative, we apply the equivalence rule BEG == LEN(IT) + BEG.  
For example, if BEG is -1 and LEN(IT) == 10, then BEG is
equivalent to 9 == 10 + -1.  (Similarly for END.)
  """
  ret = []
  if beg == None:
beg = 0
  if end == None:
end = len(it)
  if beg < 0:
beg = len(it) + beg
  if end < 0:
end = len(it) + end
  cur = beg
  while cur < end:
ret.append(it[cur])
cur += step
  return ret
--8<---cut here---end--->8---
-- 
https://mail.python.org/mailman/listinfo/python-list


how to let argument be optional falling back to certain integer

2020-06-20 Thread Boris Dorestand
I just wrote

def f(y, N, k = None):
  k = k or (N - 1)
  return k

I was surprised to find out that 0 == False, so f(7, 31, 0) produces 31.

I'd like 0 to be a valid choice for k.  

How do you guys let k be an optional argument such that it defaults to 
N - 1?  

Thank you.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how to let argument be optional falling back to certain integer

2020-06-20 Thread Boris Dorestand
Chris Angelico  writes:

> On Sun, Jun 21, 2020 at 2:02 AM Boris Dorestand  
> wrote:
>>
>> I just wrote
>>
>> def f(y, N, k = None):
>>   k = k or (N - 1)
>>   return k
>>
>> I was surprised to find out that 0 == False, so f(7, 31, 0) produces 31.
>>
>> I'd like 0 to be a valid choice for k.
>>
>> How do you guys let k be an optional argument such that it defaults to
>> N - 1?
>>
>
> The easiest way is to explicitly check for None.
>
> if k is None: k = N - 1

Got it.  That's clear code.

> Zero being false shouldn't be a surprise. If None can count as false,
> then so should other "emptiness" values. (Remember, the canonical
> falseness value is False, not None.)

This is true.  I have written 0 as false in C so many times.  But
clearly for me times have changed...  I now look at numbers as a thing
in their own special class not to be confused as truth-values.  (So much
so that I fell for this.)  But I confess I still think of numbers as all
TRUE.  (Even zero!)

Anyway, I kind of replied just to thank you all for the great group this
is.  ChrisA, I don't know how can keep up with this newsgroup, but you
do.  This is crazy.  Years go by and when I come back, there you are
still.  You're priceless.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how to let argument be optional falling back to certain integer

2020-06-21 Thread Boris Dorestand
Chris Angelico  writes:

[...]

>> Anyway, I kind of replied just to thank you all for the great group this
>> is.  ChrisA, I don't know how can keep up with this newsgroup, but you
>> do.  This is crazy.  Years go by and when I come back, there you are
>> still.  You're priceless.
>
> You're most welcome! I hang out here a lot because the people here are
> awesome. I've learned a lot, helped a lot of people, the language has
> shifted, it's been great.
>
> I like to think of myself as an empowerer - I help YOU to be able to
> do amazing things. It's you who are the awesome creative person who's
> making code do magic, and I'm just removing barriers from your way :)

I appreciate that a lot!  But of course if that's your view of things,
then you are the great one here.  No doubt about it.  Have a great day!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how to let argument be optional falling back to certain integer

2020-06-22 Thread Boris Dorestand
David Raymond  writes:

>> This is true.  I have written 0 as false in C so many times.  But
>> clearly for me times have changed...  I now look at numbers as a thing
>> in their own special class not to be confused as truth-values.  (So much
>> so that I fell for this.)  But I confess I still think of numbers as all
>> TRUE.  (Even zero!)
>
> Also remember that in Python bool is a subclass of int:
 isinstance(False, int)
> True
 0 == False
> True
 1 == True
> True
 ["A", "B"][False]
> 'A'
 ["A", "B"][True]
> 'B'
>
> So if you're trying to do something slightly different based on the
> type of the input you might fall into this trap
>
> if isinstance(foo, float):
> do float stuff
> elif isinstance(foo, int):
> do int stuff
> elif isinstance(foo, bool):
> this line will never run because it would have triggered the int line

In my case I was only interested in ints, so I actually did try
isinstance(k, int) and it seemed to work because I didn't try 

  k = False 

I settled for the explicit check done by Chris Angelico.
-- 
https://mail.python.org/mailman/listinfo/python-list


on generating combinations among a variable list of lists

2020-06-28 Thread Boris Dorestand
Say we have [1,3,5,7], [2,3], [1,10].  I'd like to generate

  [1,2,1]
  [1,2,10]
  [1,3,1]
  [1,3,10]
  [3,2,1]
  [3,2,10]
  [3,3,1]
  [3,3,10]
  [5, ...]
  ... 
  [7,3,10]

The number of input lists is variable.  The example shows three lists,
but there could be only one or ten lists or any other number of lists.

I looked at itertools.  There doesn't seem to be any procedure ready for
this.  I might have to combine some of them but I'm not yet sure how.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: on generating combinations among a variable list of lists

2020-06-28 Thread Boris Dorestand
Peter Otten <[email protected]> writes:

> Boris Dorestand wrote:
>
>> Say we have [1,3,5,7], [2,3], [1,10].  I'd like to generate
>> 
>>   [1,2,1]
>>   [1,2,10]
>>   [1,3,1]
>>   [1,3,10]
>>   [3,2,1]
>>   [3,2,10]
>>   [3,3,1]
>>   [3,3,10]
>>   [5, ...]
>>   ...
>>   [7,3,10]
>> 
>> The number of input lists is variable.  The example shows three lists,
>> but there could be only one or ten lists or any other number of lists.
>> 
>> I looked at itertools.  There doesn't seem to be any procedure ready for
>> this.  I might have to combine some of them but I'm not yet sure how.
>
> itertools.product() seems to do what you want:
>
>>>> for t  in itertools.product([1,3,5,7], [2,3], [1,10]):
> ...print(t)
> ... 
> (1, 2, 1)
> (1, 2, 10)
> (1, 3, 1)
> (1, 3, 10)
> (3, 2, 1)
> (3, 2, 10)
> (3, 3, 1)
> (3, 3, 10)
> (5, 2, 1)
> (5, 2, 10)
> (5, 3, 1)
> (5, 3, 10)
> (7, 2, 1)
> (7, 2, 10)
> (7, 3, 1)
> (7, 3, 10)

That's precisely it.  I missed product.  Thanks!

> If you need lists instead of tuples convert them
>
>>>> list(t)
> [7, 3, 10]
>
> To pass a varying number of lists use a list of lists and a star argument:
>
>>>> lists = [[[1, 2], [3, 4]], [[10, 20, 30], [40, 50]]]
>>>> for item in lists:
> ... print(list(itertools.product(*item)))
> ... 
> [(1, 3), (1, 4), (2, 3), (2, 4)]
> [(10, 40), (10, 50), (20, 40), (20, 50), (30, 40), (30, 50)]

The star-syntax I didn't even know.  And it was very useful.  Thank you!
-- 
https://mail.python.org/mailman/listinfo/python-list


how to plot the FFT of a list of values

2020-12-05 Thread Boris Dorestand
I have 16 values of the period sequence 1, 2, 4, 8, 1, 2, 4, 8, ...  I
compute its fourier transform using

>>> from scipy import fft, ifft
>>> x = [1,2,4,8,1,2,4,8]
>>> fft(x)
array([ 30. +0.j,   0. +0.j,  -6.+12.j,   0. +0.j, -10. +0.j,   0. +0.j,
-6.-12.j,   0. +0.j])

Now how can I plot these values?  I would like to plot 16 values.  What
do I need to do here?  Can you show an example?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how to make ["a","b",["c","d"],"e"] into ['a', 'b', 'c', 'd', 'e'] ?

2014-04-10 Thread Boris Borcic

Rustom Mody wrote:

def fl1(l): return [y for x in l for y in x]



# recursive flatten

def fr(l):

...   if not isinstance(l,list): return [l]
...   return fl1([fr(x) for x in l])


For a short non-recursive procedure - not a function, modifies L in-place but 
none of its sublists.

>>> def flatten(L) :
for k,_ in enumerate(L) :
while isinstance(L[k],list) :
L[k:k+1]=L[k]

flattens L to any depth, eg

>>> L=[1,[2,[3,4]],5,6,[[7],8]]
>>> flatten(L)
>>> L
[1, 2, 3, 4, 5, 6, 7, 8]


---
Ce courrier électronique ne contient aucun virus ou logiciel malveillant parce 
que la protection avast! Antivirus est active.
http://www.avast.com


--
https://mail.python.org/mailman/listinfo/python-list


Re: how to make ["a","b",["c","d"],"e"] into ['a', 'b', 'c', 'd', 'e'] ?

2014-04-10 Thread Boris Borcic

Boris Borcic wrote:

Rustom Mody wrote:

def fl1(l): return [y for x in l for y in x]



# recursive flatten

def fr(l):

...   if not isinstance(l,list): return [l]
...   return fl1([fr(x) for x in l])


For a short non-recursive procedure - not a function, modifies L in-place but 
none of its sublists.

 >>> def flatten(L) :
for k,_ in enumerate(L) :
while isinstance(L[k],list) :
L[k:k+1]=L[k]

flattens L to any depth, eg

 >>> L=[1,[2,[3,4]],5,6,[[7],8]]
 >>> flatten(L)
 >>> L
[1, 2, 3, 4, 5, 6, 7, 8]


Mh, this will fail though if the last item (of the last item (of the...)) is an empty list, eg L=[[]]. If you 
want to cover this case you can wrap the inside of the proc with a try except IndexError: pass, in which case 
you can also simplify the enumerate(L) to an indefinite counter. Or insert a dummy value before starting and 
pop it off at the end.




---
Ce courrier électronique ne contient aucun virus ou logiciel malveillant parce 
que la protection avast! Antivirus est active.
http://www.avast.com


--
https://mail.python.org/mailman/listinfo/python-list


Re: How can i create a random array of floats from 0 to 5 in python

2013-03-12 Thread Boris FELD
You can use [random.random() * 5 for x in range(100)] but works only
on range [0, 5). If you want to include 5, you will need more code.

Cheers,
FELD Boris

2013/3/12 Norah Jones :
> I want to create a random float array of size 100, with the values in the
> array ranging from 0 to 5. I have tried random.sample(range(5),100) but that
> does not work. How can i get what i want to achieve?
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: More than you ever wanted to know about objects

2006-01-16 Thread Boris Borcic
Mike Meyer wrote :
> 
> For even more fun, consider 1.0 == 1 == decimal.Decimal('1.0').
> 

Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on 
win32
Type "copyright", "credits" or "license()" for more information.
 >>> import decimal
 >>> 1 == 1.0 == decimal.Decimal('1.0')
False
 >>> decimal.Decimal('1.0') == 1 == 1.0
True

MM, painful
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: More than you ever wanted to know about objects [was: Is everything a refrence or isn't it]

2006-01-16 Thread Boris Borcic
Tim Peters a écrit :
> [Alex Martelli]
> ...
>>> In mathematics, 1 is not "the same" as 1.0 -- there exists a natural
>>> morphism of integers into reals that _maps_ 1 to 1.0, but they're still
>>> NOT "the same" thing.  And similarly for the real-vs-complex case.

- but does there exists any sense of "mathematics object identity" 
that's not built out of similar maps ? IOW, if - abstracting from your 
example - I admit as a rule that is sufficient to deny identity, to 
point out that two objects are "merely" related by a natural map, isn't 
it then the case that I can display an infinite quantity of *distinct* 
clones of any mathematical object or structure that I can think of ?

Smallscale python illustration :

 >>> 2<<100
2535301200456458802993406410752L
 >>> 2<<100 is 2<<100
False

> [Xavier Morel]
>> I disagree here, 1 and 1.0 are the same mathematical object e.g. 1 (and
>> the same as "1+0i"), the difference due to notation only makes sense in
>> computer science where integers, real and complex ensembles are disjoin.
>> In mathematics, Z is included in IR which is included in C (note: this
>> is not mathspeak, but I have no idea how to say it in english), and this
>> notation -- at best -- merely determines the ensemble you're currently
>> considering.
>>
>> There is no "natural morphism" of integers into reals because there is
>> no mathematical difference between integers and reals, the real ensemble
>> is merely a superset of the integers one.

Well, how do you know there should be a difference between
(a) "(there exists) a natural morphism from A to B"
(b) "A is a subset of B"
? To paraphrase you : "the 'natural morphism' ensemble is merely a 
superset of the 'subset/superset' one"

More to the point, where you view really breaks is when two incompatible 
extensions of the number tower are possible, like what happens with 
complex numbers and surreal numbers, which are both rich extensions of 
real numbers. Or real numbers and transfinite cardinals, viewed both as 
extending natural numbers.

>>
>> Or so it was last time i got a math course.
> 
> This all depends on which math course you last took ;-)

I often wonder whether young and adventurous minds could be more 
efficiently seduced to mathematics by enlisting them to interstellar travel.

The idea goes thus. First note that by adjusting (natural) language 
courses one may end up with home-grown pupils equivalent to pupils taken 
from another continent; for instance you may teach arab to young 
americans and obtain something more in the likeness of an arab.

Then argue that by adjusting the mathematics curriculum, one may obtain 
similar effects, but with displacements on the scale of interstellar 
travel rather than intercontinental travel !

[Tim Peters]
> You have more a physicist's view here.  The simplest case is real versus 
> complex,
> where even a physicist  can accept that a complex number,
> formally, is an ordered pair of real numbers.

Well, I suppose you've heard of Paul Erdoes's notion of a "Supreme 
Fascist" dictator of mathematics who owns a Book of All the Best Proofs ?

It's easy to extend Him with a -WarpDrive- method of the form "Any 
teacher teaching A before B shall be sentenced to death".

The spacedrive effect would be obtained by an appropriate choices of A 
and B divergent from our current habits. Of course one could expect many 
choices to lead nowhere - or at least to rough rides. But, I surmise 
that a promising and most fascinating pick would be A=real, B=complex.

...
> in a computer all numerics suck,

Sets suck.

Cheers, BB
--
666 ?? -- 666 ~ .666 ~ 2/3 ~  1 - 1/3  ~ tertium non datur
   ~ the excluded middle
   ~ "either with us, or against us" !
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Recursive function returning a list

2006-07-18 Thread Boris Borcic
> Do you have any ideas?

you could use a recursive generator, like

def genAllChildren(self) :
 for child in self.children :
 yield child
 for childchild in child.genAllChildren() :
 yield childchild
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: array alice of [:-0] ??

2006-07-18 Thread Boris Borcic
guthrie wrote:
> Beginner question! :-)
> 
> x=[1,2,3,4]
> for i in range(len(x)):
>print x[:-i]
> 
>  >>> []
>  >>> [1,2,3]
>  >>> [1,2]
>  >>> [1]
> 
> 1) The x[:-0] result seems inconsistent to me;
> I get the idea that -0=0, so it is taken as x[:0] -> []

that's what you get.

> 2) how then should one do this basic left-recursive subsetting (easily).

I am not sure what you mean, but replacing x[:-i] by x[:len(x)-i] you will get 
continuous behavior at i==0.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Recursive function returning a list

2006-07-18 Thread Boris Borcic
Hello Bruno,

Bruno Desthuilliers wrote:
> Boris Borcic wrote:
>>> Do you have any ideas?
>>
>> you could use a recursive generator, like
>>
>> def genAllChildren(self) :
>> for child in self.children :
>> yield child
>> for childchild in child.genAllChildren() :
>> yield childchild
> 
> 
> Or how to *not* address the real problem...
> 
> Boris, using a generator may be a pretty good idea, but *not* as a way
> to solve a problem that happens to be a FAQ !-)
> 

Sorry, but I don't understand your reasoning. How can you exclude that the OP 
/may/ find that a generator neatly solves his problem ? The use of a default 
value was not an end in itself, was it ?- and the quirks of default values 
being 
FAQ stuff don't change that. Sure if nobody had covered that aspect, but a 
couple other posters did...

Mmmmhhh somehow it feels like if there is any issue here, it is about defending 
the credo "there ought to exist only one obvious way to do it" ?...

Cheers, BB
--
666 ?? - 666 ~ .666 ~ 2/3 ~ 1-1/3 ~ tertium non datur ~ the excluded middle
  ~ "either with us, or against us" !!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Coding style

2006-07-19 Thread Boris Borcic
PTY wrote:
> Which is better?
> 
> lst = [1,2,3,4,5]
> 
> while lst:
>   lst.pop()
> 
> OR
> 
> while len(lst) > 0:
>   lst.pop()
> 

allways that either-or stuff ! And why did you not consider

while len(lst) : list.pop()

a neat middle ground, wouldn't you say ?

Cheers, BB
--
666 ?? - 666 ~ .666 ~ 2/3 ~ 1-1/3 ~ tertium  non datur ~ the excluded middle
  ~ "either with us, or against us" !!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Coding style

2006-07-19 Thread Boris Borcic
Bruno Desthuilliers wrote:
> 
> empty_list = []
> bool(empty_list) is False
> => True

it's just a pity that the symmetric expression

list(False) is []

doesn't hold.

I guess the problem is that if list(False) was thus defined, it would be 
difficult not to define list(True). And then the zen of Python clashes

"In the presence of ambiguity, refuse the temptation to guess".

OTOH, my favorite there would be

list(True) is [None]

together with

list(n) == n*[None] for all positive integers n

Cheers, BB
--
666 ?? - 666 ~ .666 ~ 2/3 ~ 1-1/3 ~ tertium  non datur ~ the excluded middle
  ~ "either with us, or against us" !!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Coding style

2006-07-19 Thread Boris Borcic
Marc 'BlackJack' Rintsch wrote:
> In <[EMAIL PROTECTED]>, Boris Borcic wrote:
> 
>> Bruno Desthuilliers wrote:
>>> empty_list = []
>>> bool(empty_list) is False
>>> => True
>> it's just a pity that the symmetric expression
>>
>> list(False) is []
>>
>> doesn't hold.
> 
> You want the empty list to be a singleton!?

Oops,

list(False) == [], then.

BTW, be careful with 'singleton' when applying to aggregates - it took me a 
while to figure out you did not mean an obj X s.t. len(X)==1.


>  And I don't find
> `list(False)` to return an empty list be very obvious.

What would be your choice ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Recursive function returning a list

2006-07-19 Thread Boris Borcic
Bruno Desthuilliers wrote:
> Boris Borcic a écrit :
>> Hello Bruno,
>>
>> Bruno Desthuilliers wrote:
>>
>>> Boris Borcic wrote:
>>>
>>>>> Do you have any ideas?
>>>>
>>>>
>>>> you could use a recursive generator, like
>>>>
>>>> def genAllChildren(self) :
>>>> for child in self.children :
>>>> yield child
>>>>     for childchild in child.genAllChildren() :
>>>> yield childchild
>>>
>>>
>>>
>>> Or how to *not* address the real problem...
>>>
>>> Boris, using a generator may be a pretty good idea, but *not* as a way
>>> to solve a problem that happens to be a FAQ !-)
>>>
>>
>> Sorry, but I don't understand your reasoning.
> 
> It's quite simple. The OP's problem is well-known (it's a FAQ),

This is really an oversimplification. What's the case is that his showstopper 
was covered by the FAQ list. The OP's "problem" is actually a stack of 
problems/subproblems and was presented as such.

> and easy 
> to solve.

I did consider a couple distinct ways to solve "it" while passing lists around 
- 
did you notice that the OP's code made no clear choice as to whether it wanted 
to pass them by reference or as return values ? That's how a generator struck 
me 
as most pythonic if you want ("In the face of ambiguity, refuse the temptation 
to guess").

> The righ answer to it is obviously to give a link to the FAQ 
> (or take time to re-explain it for the zillionth time), not to propose a 
> workaround.

Given your usage of code simplicity in another thread as (roughly) a measure of 
pythonic virtue, I feel it warranted to ask why should one recognize simpler 
code as "the workaround" (assuming it fits the bill) ?

Because it doesn't cross the FAQ, seems to be your answer...

> 
>> How can you exclude that the OP /may/ find that a generator neatly 
>> solves his problem ?
> 
> I don't exclude it, and explicitly mentioned in whole letters that, I 
> quote, it "may be a pretty good idea". And actually, the OP's problem is 
> really with default values evaluation scheme - something that every 
> Python programmer should know, because there are cases where you cannot 
> solve it with a generator-based solution !-)
...
 >> - and the quirks of default values being FAQ stuff don't change that.
 >> Sure if nobody had covered that aspect, but a couple other posters did...
 >
 > Yes, but you forgot to mention that - and I would not have post any
 > comment on your solution if you had explicitly mentioned the FAQ or
 > these other answers.

At this point I recognize that our difference may very well have deep roots 
relating to cognitive style, educational policy, etc. Generally speaking I 
welcome debate on such premisses as an occasion to learn more (not so much from 
my contradictor than from the debate itself), but a precondition is that the 
partner/contradictor understands my motive (what I can't count on since the 
idea 
of learning from the debate itself is pretty typical such cognitive style 
divides). Besides, I don't quite have the time right now.

The short form is : "I strongly disagree with you".

Best, BB
--
"On naît tous les mètres du même monde"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Augument assignment versus regular assignment

2006-07-19 Thread Boris Borcic
Antoon Pardon wrote:

> The language reference doesn't talk about objects. And IMO you
> should be carefull if you want to use the word "object" here.
> In the line: "foo += 1", you can't talk about the object foo,
> since foo will

possibly

> be bound to a different object after the assignment
> than it was bound to before.

witness

   >>> class Foo(list) :
  def __iadd__(self,other) :
  self.append(other)
  return self


   >>> bar = foo = Foo()
   >>> foo += 1
   >>> foo is bar
   True
   >>> foo
   [1]

while of course

   >>> bar = foo = 0
   >>> foo += 1
   >>> foo is bar
   False

Best, BB
--
"On naît tous les mètres du même monde"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Number combinations

2006-07-19 Thread Boris Borcic
Tim Chase wrote:
...

> If you need the individual digits for something, you can use
> 
> for i in xrange(0,1):
> d1,d2,d3,d4 = list("%04i" % i)

strings are sequences too, and you need only write

   d1,d2,d3,d4 = "%04i" % i
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Recursive function returning a list

2006-07-19 Thread Boris Borcic
Bruno Desthuilliers wrote:
> 
> Nope, it's about trying to make sure that anyone googling for a similar 
> problem will notice the canonical solution somehow.
> 

Hey, I challenge you to cook up a plausible query even loosely fitting your 
"googling for a similar problem" that would return my answer but not that of 
the 
other posters (nor the faq itself, oeuf corse).

Best, BB
--
"On naît tous les mètres du même monde"

-- 
http://mail.python.org/mailman/listinfo/python-list


random shuffles

2006-07-21 Thread Boris Borcic
does

x.sort(cmp = lambda x,y : cmp(random.random(),0.5))

pick a random shuffle of x with uniform distribution ?

Intuitively, assuming list.sort() does a minimal number of comparisons to 
achieve the sort, I'd say the answer is yes. But I don't feel quite confortable 
with the intuition... can anyone think of a more solid argumentation ?

- BB
--
"On naît tous les mètres du même monde"
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: random shuffles

2006-07-21 Thread Boris Borcic
Paul Rubin wrote:
> Boris Borcic <[EMAIL PROTECTED]> writes:
>> x.sort(cmp = lambda x,y : cmp(random.random(),0.5))
>> pick a random shuffle of x with uniform distribution ?
> 
> You really can't assume anything like that.  Sorting assumes an order
> relation on the items being sorted, which means if a < b and b < c,
> then a < c.  If your comparison operation doesn't preserve that
> property then the sort algorithm could do anything, including looping
> forever or crashing.

Not if it does the minimum number of comparisons to achieve the sort, in which 
case it won't ever call cmp() if the result is pre-determined by the order 
relation and previous comparisons, so that it will never get from this 
comparison function a system of answers that's not consistent with an order 
relation. That's obvious at least in the case where random.random() == 0.5 
never 
occurs (and at first sight even the latter case shouldn't change it).

Best, BB
--
"On naît tous les mètres du même monde"



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: random shuffles

2006-07-21 Thread Boris Borcic
Thanks for these details. BB

Tim Peters wrote:
> [ Boris Borcic]
>> x.sort(cmp = lambda x,y : cmp(random.random(),0.5))
>>
>> pick a random shuffle of x with uniform distribution ?
> 
> Say len(x) == N.  With Python's current sort, the conjecture is true
> if and only if N <= 2.
> 
>> Intuitively, assuming list.sort() does a minimal number of comparisons to
>> achieve the sort,
> 
> No idea what that could mean in a rigorous, algorithm-independent way.
> 
>> I'd say the answer is yes. But I don't feel quite confortable
>> with the intuition... can anyone think of a more solid argumentation ?
> 
> If a list is already sorted, or reverse-sorted, the minimum number of
> comparisons needed to determine that is N-1, and Python's current sort
> achieves that.  It first looks for the longest ascending or descending
> run.  If comparison outcomes are random, it will decide "yes, already
> sorted" with probability 1/2**(N-1), and likewise for reverse-sorted.
> When N > 2, those are larger than the "correct" probabilities 1/(N!).
> So., e.g., when N=3, the sort will leave the list alone 1/4th of the
> time (and will reverse the list in-place another 1/4th).  That makes
> the identity and reversal permutations much more likely than "they
> should be", and the bias is worse as N increases.
> 
> Of course random.shuffle(x) is the intended way to effect a
> permutation uniformly at random.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: random shuffles

2006-07-21 Thread Boris Borcic
Boris Borcic wrote:
> Paul Rubin wrote:
>> Boris Borcic <[EMAIL PROTECTED]> writes:
>>> x.sort(cmp = lambda x,y : cmp(random.random(),0.5))
>>> pick a random shuffle of x with uniform distribution ?
>>
>> You really can't assume anything like that.  Sorting assumes an order
>> relation on the items being sorted, which means if a < b and b < c,
>> then a < c.  If your comparison operation doesn't preserve that
>> property then the sort algorithm could do anything, including looping
>> forever or crashing.
> 
> Not if it does the minimum number of comparisons to achieve the sort, in 
> which case it won't ever call cmp() if the result is pre-determined by 
> the order relation and previous comparisons, so that it will never get 

read "by /the assumption of an order relation/ and previous comparisons"

> from this comparison function a system of answers that's not consistent 
> with an order relation. That's obvious at least in the case where 
> random.random() == 0.5 never occurs (and at first sight even the latter 
> case shouldn't change it).

- this - the idea that /if/ the algorithm was optimal it would only sample the 
random comparison function up to a system of answers consistent with an order 
relation - is actually what prompted my question,
iow "is it good for anything ?"

Best, BB
--
"On naît tous les mètres du même monde"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: random shuffles

2006-07-21 Thread Boris Borcic
Boris Borcic wrote:
> Paul Rubin wrote:
>> Boris Borcic <[EMAIL PROTECTED]> writes:
>>> x.sort(cmp = lambda x,y : cmp(random.random(),0.5))
>>> pick a random shuffle of x with uniform distribution ?
>>
>> You really can't assume anything like that.  Sorting assumes an order
>> relation on the items being sorted, which means if a < b and b < c,
>> then a < c.  If your comparison operation doesn't preserve that
>> property then the sort algorithm could do anything, including looping
>> forever or crashing.
> 
> Not if it does the minimum number of comparisons to achieve the sort, in 
> which case it won't ever call cmp() if the result is pre-determined by 
> the order relation and previous comparisons, so that it will never get 
> from this comparison function a system of answers that's not consistent 
> with an order relation. That's obvious at least in the case where 
> random.random() == 0.5 never occurs (and at first sight even the latter 
> case shouldn't change it).

To be more convincing... assume the algorithm is optimal and calls
cmp(x,y). Either the previous calls (+ assuming order relation) give no 
conclusion as to the possible result of the call, in which case the result 
can't 
contradict an order relation; or the previous calls (+assumption) provide only 
partial information; iow the algorithm knows for example x<=y and needs to 
determine which of xy".

But is it possible for a sort algorithm assuming an order relation to attain eg 
x<=y but neither xhttp://mail.python.org/mailman/listinfo/python-list


Re: random shuffles

2006-07-24 Thread Boris Borcic
Paul Rubin wrote:
> Boris Borcic <[EMAIL PROTECTED]> writes:
>> To be more convincing... assume the algorithm is optimal and calls
> 
> That assumption is not even slightly realistic.  Real-world sorting
> algorithms almost never do a precisely minimal amount of comparison.

'optimal' or 'minimal amount of comparisons' does not mean here to make just 
the 
right n-1 comparisons between successive items to verify the order of n items, 
but rather that no strict subset of the comparisons made to sort some data is 
sufficient to sort that data.

IOW "minimal" in "minimal amount of comparisons" refers not to the total 
ordering by size of the sets of comparisons made, but to the partial ordering 
by 
set inclusion of these sets.

And in this sense, it is clear that quicksort for instance is optimal*

It is easy to see, when you detail this algorithm, that never during its run is 
the result of a comparison it makes, preordained by comparisons already made; 
iow : it doesn't make superfluous or redundant comparisons.

Do you mean quicksort-like algorithms aren't real-world ?

Best, BB
--

*assuming a variant, like the following for illustration, that doesn't waste 
info on equal items.

def qsort(items,cmp) :
 if len(items)<2 : return items
 pivot = items[0]
 divide = [[pivot],[],[]]
 for item in items[1:] :
 divide[cmp(item,pivot)].append(item)
 return qsort(divide[-1],cmp)+divide[0]+qsort(divide[1],cmp)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: random shuffles

2006-07-26 Thread Boris Borcic
I wrote :
> 
> ...in this sense, it is clear that quicksort for instance is optimal*
> 
> It is easy to see, when you detail this algorithm, that never during its 
> run is the result of a comparison it makes, preordained by comparisons 
> already made; iow : it doesn't make superfluous or redundant comparisons.

The above is true, but...

While an algorithm may never call for a comparison that has a result 
predetermined by previous comparisons, it doesn't follow that the property 
would 
hold true for the exact same comparisons done in a different order.

In particular, any sort algorithm must have compared successive items to be 
able 
to conclude to their order, so that any system of comparisons that allows to 
sort a dataset of n items, must contain the strictly minimal system of n-1 
comparisons of successive items.

This doesn't change the conclusion that an algorithm that never does a 
comparison with a result that could be deduced from previous comparisons, will 
only sample a random comparison function up to a system of comparisons that's 
consistent with an order relation between the items.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: cleaner way to write this try/except statement?

2006-08-01 Thread Boris Borcic
John Salerno wrote:
> The code to look at is the try statement in the NumbersValidator class, 
> just a few lines down. Is this a clean way to write it? i.e. is it okay 
> to have all those return statements? Is this a good use of try? Etc.
> 
> Thanks.
> 
> 
> 
> import wx
> 
> 
> class NumbersValidator(wx.PyValidator):
> 
> def __init__(self):
> wx.PyValidator.__init__(self)
> 
> def Clone(self):
> return NumbersValidator()
> 
> def Validate(self, parent):
> text_ctrl = self.GetWindow()
> text = text_ctrl.GetValue()
> 
> try:
> if not text or int(text) <= 0:
> wx.MessageBox('Enter a valid time.', 'Invalid time
>   entered', wx.OK | wx.ICON_ERROR)
> return False
> else:
> return True
> except ValueError, error:
> wx.MessageBox('Enter a valid time.', 'Invalid time entered',
>   wx.OK | wx.ICON_ERROR)
> return False

well, assuming you are unsatisfied with the above, you could try to assert the 
validation condition and catch together all failures, eg :

def Validate(self, parent):
 text_ctrl = self.GetWindow()
 text = text_ctrl.GetValue()
 try :
 assert int(text)>0
 return True
 except (ValueError,AssertionError) :
 wx.MessageBox('Enter a valid time.', 'Invalid time entered',
   wx.OK | wx.ICON_ERROR)
 return False

hth, BB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: cleaner way to write this try/except statement?

2006-08-03 Thread Boris Borcic
Simon Forman wrote:
> Boris Borcic wrote:
>> John Salerno wrote:
>>> The code to look at is the try statement in the NumbersValidator class,
>>> just a few lines down. Is this a clean way to write it? i.e. is it okay
>>> to have all those return statements? Is this a good use of try? Etc.
>>>
>>> Thanks.
>>>
>>> 
>>>
>>> import wx
>>>
>>>
>>> class NumbersValidator(wx.PyValidator):
>>>
>>> def __init__(self):
>>> wx.PyValidator.__init__(self)
>>>
>>> def Clone(self):
>>> return NumbersValidator()
>>>
>>> def Validate(self, parent):
>>> text_ctrl = self.GetWindow()
>>> text = text_ctrl.GetValue()
>>>
>>> try:
>>> if not text or int(text) <= 0:
>>> wx.MessageBox('Enter a valid time.', 'Invalid time
>>>   entered', wx.OK | wx.ICON_ERROR)
>>> return False
>>> else:
>>> return True
>>> except ValueError, error:
>>> wx.MessageBox('Enter a valid time.', 'Invalid time entered',
>>>   wx.OK | wx.ICON_ERROR)
>>> return False
>> well, assuming you are unsatisfied with the above, you could try to assert 
>> the
>> validation condition and catch together all failures, eg :
>>
>> def Validate(self, parent):
>>  text_ctrl = self.GetWindow()
>>  text = text_ctrl.GetValue()
>>  try :
>>  assert int(text)>0
>>  return True
>>  except (ValueError,AssertionError) :
>>  wx.MessageBox('Enter a valid time.', 'Invalid time entered',
>>wx.OK | wx.ICON_ERROR)
>>  return False
>>
>> hth, BB
> 
> Assertion statements "go away" when you run python with the '-O' or
> '-OO' options.  

Makes me wonder how many use those options. I never do, this explains that.

 > They're only meant for debugging and shouldn't be used
 > as part of your actual program logic.

That's too bad, and bound to evolve if the logic object space of Pypy gains 
users.

> 
> You run the risk of introducing hard-to-find bugs if you use them like
> this and somebody, somewhere, sometime runs your code in "optimized"
> mode.

Well, I wouldn't formulate it quite like that, but, as you say,...

> 
> Peace,
> ~Simon
> 

Well, in that case let's just define

def fail(exc) : raise exc

and replace

assert int(text)>0

by

int(text)>0 or fail(ValueError)

cheers, BB
--
"On naît tous les mètres du même monde"

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to reverse tuples in a list?

2006-08-09 Thread Boris Borcic
Applying the perl motto (there is more than one way to do it) sure enough leads 
to a perlish solution... as measured by line noise.

 >>> t = [('a', 11,1.0), ('b',22,2.0),('c',33,3.0)]
 >>> zip(*zip(*t)[::-1])
[(1.0, 11, 'a'), (2.0, 22, 'b'), (3.0, 33, 'c')]

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: converting a nested try/except statement into try/except/else

2006-08-10 Thread Boris Borcic
Slawomir Nowaczyk wrote:
> 
> try:
> if int(text) > 0:
>return True
> except ValueError:
> pass
> self.error_message()
> return False
> 

Nicely DRY. To make it even more compact, it may be noticed that the default 
return value None is false in a boolean context - so that the last line is 
superfluous if the return value is only wanted to test it in such a context.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: converting a nested try/except statement into try/except/else

2006-08-10 Thread Boris Borcic
Bruno Desthuilliers wrote:
> Boris Borcic a écrit :
>> Slawomir Nowaczyk wrote:
>>
>>>
>>> try:
>>> if int(text) > 0:
>>>return True
>>> except ValueError:
>>> pass
>>> self.error_message()
>>> return False
>>>
>>
>> Nicely DRY. To make it even more compact, it may be noticed that the 
>> default return value None is false in a boolean context - so that the 
>> last line is superfluous if the return value is only wanted to test it 
>> in such a context.
> 
> While it's technically true - and I while I have a taste for compactness 
> - skipping the explicit 'return False' somehow hurts my sense of 
> esthethic... Unless you propose to return object or type  instead of 
> True - but then it begins to look very strange !-)

so what about simplifying your solution 1 to

try :
 return int(text)>0 or int('garbage')
except ValueError :
 self.error_message()


it still returns True on success, but hides it well :) and while perhaps a bit 
too clever I feel it competes well on readability, precisely because it is 
compact and because int('garbage') mimics int(text) while standing just before 
'except ValueError'. That mimicry kind of encapsulates your and infidel's 
answer 
to the OP's objection to raising ValueError if int(text)<=0.

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: converting a nested try/except statement into try/except/else

2006-08-10 Thread Boris Borcic
John Salerno wrote:
> In this case the method must return False, because it's a wxPython 
> method that needs a True or False value. If it doesn't, the program will 
> continue even after the error message.

Just as it should do if the method returns True and no error message is 
produced 
if I understand you well... Are you sure ? I don't know wxPython, but this 
strikes me as surprisingly unpythonic behavior.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: converting a nested try/except statement into try/except/else

2006-08-10 Thread Boris Borcic
Boris Borcic wrote:
> John Salerno wrote:
>> In this case the method must return False, because it's a wxPython 
>> method that needs a True or False value. If it doesn't, the program 
>> will continue even after the error message.
> 
> Just as it should do if the method returns True and no error message is 
> produced if I understand you well... Are you sure ? I don't know 
> wxPython, but this strikes me as surprisingly unpythonic behavior.

I just verified on the wxWindows demo I had somehow installed on my box, that 
indeed returning None appears to produce the same behavior as returning True, 
distinct from the behavior obtained by returning False. Ugh...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: swapping numeric items in a list

2006-08-23 Thread Boris Borcic
Jiang Nutao wrote:
> Hi,
> 
> I simplify my problem like below
> 
> To convert list
> aa = [0x12, 0x34, 0x56, 0x78]
> into
> [0x34, 0x12, 0x78, 0x56]
> 
> How to do it fast? My real list is huge.

Mark Rintsch's suggestion appears best if applicable, but just to cite yet 
other 
ways to do it :

list(aa[j+(-1)**j] for j in range(len(aa)))

or

sum(reversed(zip(*[reversed(aa)]*2)),())

or (py 2.5)

from itertools import izip
ab = iter(aa)
list((yield y) or x for x,y in izip(ab,ab))

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Logic Programming

2006-10-10 Thread Boris Borcic

I believe some work has been down in pypy to bring logic programming to python.
You might ask pypy-dev

Google leads to 
http://codespeak.net/pypy/dist/pypy/doc/howto-logicobjspace-0.9.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionaries

2006-10-18 Thread Boris Borcic

dict(a.items() + b.items())

Lad wrote:
> How can I add two dictionaries into one?
> E.g.
> a={'a:1}
> b={'b':2}
> 
> I need
> 
> the result {'a':1,'b':2}.
> 
> Is it possible?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is x.f() <==>MyClass.f(x) a kind of algebraic structure?

2006-10-21 Thread Boris Borcic
steve wrote:
> What can we think that?

When much stretch definitions
-- 
http://mail.python.org/mailman/listinfo/python-list


extract text from a string

2006-11-09 Thread boris . smirnov
Hallo all,

I have tried for a couple of hours to solve my problem with re but I
have no success.

I have a string containing: "+abc_cde.fgh_jkl\n" and what I need to
become is "abc_cde.fgh_jkl".  Could anybody be so kind and write me a
code of how to extract this text from that string?

thank you very much in advance
regards,
boris

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: extract text from a string

2006-11-09 Thread boris . smirnov
Thank you very much.
I needed this kick. :)
Rg,
Boris


Grant Edwards napísal(a):
> On 2006-11-09, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> > Hallo all,
> >
> > I have tried for a couple of hours to solve my problem with re but I
> > have no success.
> >
> > I have a string containing: "+abc_cde.fgh_jkl\n" and what I need to
> > become is "abc_cde.fgh_jkl".  Could anybody be so kind and write me a
> > code of how to extract this text from that string?
>
> >>> s = "+abc_cde.fgh_jkl\n"
> >>> s[1:-1]
> 'abc_cde.fgh_jkl'
>
> --
> Grant Edwards   grante Yow!  ... I think I'm
>   at   having an overnight
>visi.comsensation right now!!

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: how is python not the same as java?

2006-11-10 Thread Boris Borcic
Jorge Vargas wrote:
> can you open a commandline and start writting java code? 

beanshell, iirc
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Will GPL Java eat into Python marketshare?

2006-11-16 Thread Boris Borcic
John Bokma wrote:

>> Seriously though, there is no contradiction between the idea of
>> "people use Python instead of Java because they prefer to avoid pain"
> 
> It sounds like a typical fanboy statement to me, since it implies that 
> Java is always a pain, and Python is perfect. 

That inference requires as preliminary convention, some clear contrafactual 
like 
"everybody uses Python and nobody uses Java".

IMO, this is a form of assumption that is only legitimate in the purpose of 
reaching agreement; while the OP's statement can be read as "those people who 
use Python instead of Java do it because..." without recourse to a similar 
assumption - what escapes your criticism.

Cheers, BB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: John Bokma harassment

2006-05-29 Thread Boris Borcic
[EMAIL PROTECTED] wrote:
> We seem to have strayed a long way from Voltaire's
> "I do not agree with what you say, but I will defend to the death your
> right to say it.",
> but that was of course the age of enlightenment.

Obviously this wisdom is getting stale and should be updated to something
like "There is so much noise we can't hear each other, but I will defend
to the death a chance to get heard for whatever you might have to say that's
intelligent (while not necessarily from your own mouth)".

Besides, it is not clear that Voltaire really said that.

Cheers, BB
--
python >>> filter(lambda W : W not in 'ILLITERATE','BULLSHIT')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ricerca Programmatore Python

2006-05-29 Thread Boris Borcic
Nic wrote:
> Please accept my apologies for the use of the Italian language.

accepted
-- 
http://mail.python.org/mailman/listinfo/python-list


numpy bug

2006-06-01 Thread Boris Borcic
after a while trying to find the legal manner to file numpy bug reports,
since it's a simple one, I thought maybe a first step is to describe the bug 
here. Then maybe someone will direct me to the right channel.

So, numpy appears not to correctly compute bitwise_and.reduce and 
bitwise_or.reduce : instead of reducing over the complete axis, these methods 
only take the extremities into account. Illustration :

 >>> from numpy import *
 >>> bitwise_or.reduce(array([8,256,32,8]))
8
 >>> import numpy
 >>> numpy.__version__
'0.9.8'
 >>>

Platform : Win XP SP2, Python 2.4.2

HTH, bb
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python language problem

2006-06-07 Thread Boris Borcic
[EMAIL PROTECTED] wrote:
 class A:
> ...   pass
> ...
 a = A()
 b = a
 del b
 a
> <__main__.A instance at 0x00B91BC0>
> I want to delete 'a' through 'b', why It does't? 
> How can I do that?

del a,b

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to generate k+1 length strings from a list of k length strings?

2006-06-08 Thread Boris Borcic
Girish Sahani wrote:
>  I have a list of strings all of length k. For every pair of k length
> strings which have k-1 characters in common, i want to generate a k+1
> length string(the k-1 common characters + 2 not common characters).
> e.g i want to join 'abcd' with bcde' to get 'abcde' but i dont want to
> join 'abcd' with 'cdef'
>  Currently i'm joining every 2 strings, then removing duplicate characters
> from every joined string and finally removing all those strings whose
> length != k+1.

Hum, since your code is not syntactically correct, anything will run faster :)
I'd favor the following, that I find most readable

sets = map(set,list_of_strings)
res = set(''.join(sorted(s1|s2)) for s1 in sets for s2 in sets if len(s1^s2)==2)

unless performance is really an issue

Here's the code i've written:
> 
>   for i in range(0,len(prunedK) - 1,1):
> if k in range(1,len(prunedK),1) & i+k <= len(prunedK) -1:
> colocn = prunedK[i] + prunedK[i+k]
> prunedNew1.append(colocn)
> continue
> for string in prunedNew1:
> stringNew = withoutDup(string)
> prunedNew.append(stringNew)
> continue
> 
> But this one is quite bad in the time aspect :(

how do you know ?

> Thanks in advance,
> girish

you should do your own homework
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to generate k+1 length strings from a list of k length strings?

2006-06-08 Thread Boris Borcic
[EMAIL PROTECTED] wrote:
> Boris Borcic:
>> I'd favor the following, that I find most readable
>> sets = map(set,list_of_strings)
>> res = set(''.join(sorted(s1|s2)) for s1 in sets for s2 in sets if 
>> len(s1^s2)==2)
> 
> I think there can be written more readable code.

readability, of course, is in the eye of the beholder... and I find this code 
*much* easier to recognize as a realisation of the description made by the OP, 
than the code he himself offered - if you care to take a look at both.

For my programs I
> usually prefer simpler code, 

I challenge you to write simpler code to do the equivalent.

 > that (if possible) even a children can
 > understand.

what child ? one that is trained just like *you* think children should start, I 
guess.

 > So I can debug, modify and improve it better & faster.

Sure, but the case is we each were *distinct* children.

> 
> Bye,
> bearophile
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to generate k+1 length strings from a list of k length strings?

2006-06-09 Thread Boris Borcic
[EMAIL PROTECTED] wrote:
> Boris Borcic:
> 
>> I challenge you to write simpler code to do the equivalent.

context ?

> 
> I don't do challenges.

Pfff... and you don't do real debates either.

> I too have written the code to solve that
> problem,

Why ? When ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to generate k+1 length strings from a list of k length strings?

2006-06-09 Thread Boris Borcic
[EMAIL PROTECTED] wrote:
> Boris Borcic:
>>> I don't do challenges.
>> Pfff... and you don't do real debates either.
> 
> Different nations have different values and different cultures, in mine
> challenges are often seen as things for children, and a waste of time
> for adults (probably in USA challenges are appreciated more).

(1) This is becoming very ridiculous. What do the USA have to do with it ?

(2) Different nations have different languages, and a good rule of thumb when 
debating with someone of unknown linguistic origins is not to focus on the 
connotations you percieve to a single word you abstract from its context.

(3) Different intellectual communities have different values, in mine it is the 
rule not to make abstract claims if not ready to put them to experimental test 
- 
and it's less a matter of (passing or failing) tests than a matter of making 
clear the rule of translation between one's own abstract language and objective 
facts. And by these means, ultimately, to measure the divergence in languages.

(4) As concerns the matter of the case, you made broad and abstract claims 
while 
implicitely referring to some doctrine(s), and I concisely formulated the 
demand 
that you back them up with (according to you) observable facts. I note that 
instead you chose to articulate your doctrine while avoiding an occasion to 
probe its adequacy.

(5) I find your systematic enrollment of children to your cause quite 
inappropriate.

> 
> Bye,
> bearophile
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to generate k+1 length strings from a list of k length strings?

2006-06-09 Thread Boris Borcic
[EMAIL PROTECTED] wrote:

> It's not that difficult to improve the readability of a quite long
> line, you can start splitting it.

The point is that it is observer and context dependent whether

res = set(''.join(sorted(X|Y))
  for X in sets
  for Y in sets
  if len(X^Y)==2)

is measurably easier to read than

res = set(''.join(sorted(X|Y)) for X in sets for Y in sets if len(X^Y)==2)

*and* that I acknowledged it by writing "I find most readable"
while you denied it by speaking of "the readability" - and similar language.


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to generate k+1 length strings from a list of k length strings?

2006-06-09 Thread Boris Borcic
> Hum, since your code is not syntactically correct, anything will run 
> faster :)

in fact it parses, I was fooled by this line

>> if k in range(1,len(prunedK),1) & i+k <= len(prunedK) -1:


I was fooled because the form "k in range(" tends to imply a for statement ;
  in the case of an if statement, one usually uses chained comparisons instead.

If you know i>=0 and i,k are integers (as is implied by context), you could 
simply write something like:

if 0 < k < i+k < len(prunedK) :


in the contrary case,
assuming your line does what you want, you should really write it as

if 1 <= k < len(prunedK) and i+k <= len(prunedK)-1 :

or more concisely

if 1 <= k < len(prunedK) >= i+k+1 :

or even

if i+k < len(prunedK) > k > 0 :
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Error in Chain of Function calls

2006-06-09 Thread Boris Borcic
Girish Sahani wrote:
> 
> Also,i am getting a ValueError in the code below:
> 
>   for s in prunedNew:
> substrings = [s[:i]+s[i+1:] for i in range(len(s))]
> for string in substrings:
> if string not in prunedK:
> prunedNew.remove(s)
> continue
> continue
> 
> The error is:
> prunedNew.remove(s)
> ValueError: list.remove(x): x not in list
> 
> Could anyone enlighten me as to why i'm getting these two errors??

Why don't you use sets instead of lists ? It would make your life much easier.

Specifically here, the problem seems to be that for some s there is more than 
one substring of it that fails to be in prunedK, so that the failing line is 
called more than once for a single s.

The simplest modification is to replace your first 'continue' by a 'break' (and 
remove the second 'continue' which serves no purpose).

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [noob question] References and copying

2006-06-09 Thread Boris Borcic
zefciu wrote:
> Hello!
> 
> Where can I find a good explanation when does an interpreter copy the
> value, and when does it create the reference.  I thought I understand
> it, but I have just typed in following commands:
> 
 a=[[1,2],[3,4]]
 b=a[1]
 b=[5,6]
 a
> [[1, 2], [3, 4]]
 b
> [5, 6]
> 
> And I don't understand it.  I thought, that b will be a reference to a,
> so changing b should change a as well.

It would if you had written "b[:]=[5,6]"

> What do I do wrong.  And a
> second question - can I create a reference to element of a list of
> floating points and use this reference to change that element?

not like that.

> 
> Greets to all PyFans
> zefciu
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Error in Chain of Function calls (Code Attached)

2006-06-09 Thread Boris Borcic
Girish Sahani wrote:

>>> However i am getting an error at the line marked with ***.

>> Which error ? How do you hope us to be of any help here if you don't *at
>> least* provide the full traceback ? FWIW, the canonical way to do things
>> is to:
>> - provide minimal *runnable* code exposing the problem
>> - explain what you hoped to get
>> - explain what you got instead (including full traceback)
>>
>> As a matter of fact, it's often the case that one solves the problem
>> when working on the first point !-)
>>
>> (snip)
> Ohh...I was thinking that posting the whole code would not be a good idea.

And what changed your mind ? Please note the word "minimal" in bruno's sentence 
about submitting your code. And also the request for explanations.

> The error i get above is:
> line 266, in colocationMiner
> prunedNew = genColocations(prunedK)

OTOH, bruno asked for the full traceback, that's not it - that's not "the 
error" 
in any constructive sense, neither its type nor its real location.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Function to remove elements from a list not working (corrected)

2006-06-12 Thread Boris Borcic
Girish Sahani wrote:
> Hi,
>  I am trying to modify a list of pairs (l4) by removing those
> pairs which are not present in a third list called pairList.
>  The following is a simplified part of the routine i have written. However
> it does not give the correct output. Please help!
>  Its possible i have made a trivial mistke since i am a newbie.
> 
> def getl5():
> l5 = []
> pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]]
> l4 = [[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]]
> for pair in l4:
> if pair not in pairList:
> l4.remove(pair)
> print "l4 is",l4
> 
> The output given is:
> l4 is [[4, 7], [4, 12], [9, 7], [9, 12], [11, 7]]

use sets

def gets5() :
 pairSet = set([(1,2),(3,4),(3,5),(3,6),(9,7),(8,9),(8,7),(7,9),(11,10)])
 s4= 
set([(4,2),(4,7),(4,10),(4,12),(9,2),(9,7),(9,10),(9,12),(11,2),(11,7)])
 s4 &= pairSet
 print "s4 is",s4

the output is

s4 is set([(9, 7)])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Python-Dev] The baby and the bathwater (Re: Scoping, augmented assignment, 'fast locals' - conclusion)

2006-06-16 Thread Boris Borcic
believe that people can and will make mistakes.  I
> further believe that if I manage to make a particular mistake, that
> someone else has, because while I'm not the most brilliant programmer
> out there, I'm also certainly not the worst, and I would guess that I
> lack the creativity to generate a completely new class of mistakes.

Whatever, programming or not, I believe the most dangerous (in the sense of 
most 
difficult to rectify) class of mistakes is the class of diagnostic errors - 
meta-errors, so to say; because of that, I believe a danger with mistakes or 
errors is to anticipate too much on them, and, given their diversity, to 
overestimate the scope of the lessons learned from the sample of them that most 
caught our attention (usually because of their painful consequences).

Besides, I think there are subtle issues with taking errors as building 
material 
for policies destined to public consomption by new generations. It is vital to 
find a self-standing positive goal to substitute to the negative goal of 
avoiding the repetition of the error, etc.

Btw, how you dealt with my case tells me you don't particularly fear diagnostic 
errors, but your way of presenting closures and classes in Python tells me that 
you probably agree with my later remark.

> 
> You talk about "Designing for assumed chronic lusers",

Again, this has lost its proper context.

> I'm talking about
> designing for human beings, some of whom are new to the language.

This starts resembling the disputes I had with my wife over the education of 
our 
child. Total divergence as to the adequacy of trying to control the child's POV.

> 
> 
>  - Josiah
> 

Boris
--
"on naît tous les mètres du même monde"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Python-Dev] The baby and the bathwater (Re: Scoping, augmented assignment, 'fast locals' - conclusion)

2006-06-19 Thread Boris Borcic
Hello, just a couple points

On 6/17/06, Josiah Carlson <[EMAIL PROTECTED]> wrote:

[errors involving the shadowing of a variable by another]

 > > Of course everybody makes errors, but it doesn't follow from this, that
 > > all make the same errors, or should.
 >
 > If I implied that everyone has made this particular mistake, I'm sorry.
 > I was trying to say that I made error X, and that I don't believe that
 > I'm a unique butterfly to have made error X.

Well, don't be so certain you aren't the exceptional butterfly as regards the 
general issue - if not the error itself, perhaps the onlook. It deemed on me 
over the week-end that all three of me, you, and Guido indeed, have been acting 
out our own names in some way. Guido van Rossum's case is most direct : "The 
guide by red lights". Me, well, the issue of comparing slightly different 
versions is kind of written in the relationship of my first name and my family 
name. As for you, your name is exceptional in that it makes your initials 
shadow 
those of Jesus-Christ (a "builtin" if any); and if you go to the bottom of it, 
that collision of identifiers goes slightly further than just the initials.

Is the idea that people may get subtly influenced by their own names, new to 
you 
? One's name is to language and thought as one's home is to space...

"Bill Gates" has always struck me as an injunction...

...
 > One consequence of either a fixed or variable set of non-shadowables is
 > that you would need to use arbitrarily unique names for lexically nested
 > for loops, and/or specify that such variables are not referencing parent
 > scopes.
 >
 > def foo(...):
 > for i in ...:
 > ...
 > def bar(...):
 > ...
 > for i in ...: #unallowed
 > ...
 > ...
 >
 > You can replace the 'i' with a name of your choosing.  Is such
 > desireable?  I would say no for the same reasons why I said no in
 > regards to being able to explicitly name variables in different levels
 > within lexically nested scopes: I would argue that one shouldn't be
 > using closures in the first place, so encouraging its use with a syntax
 > is right out the door.  But that's my opinion, and not really relevant
 > to the current discussion.

I am surprised you would count the obligation of picking distinct names as an 
encouragement to use lexically nested scopes; compared to the current 
situation, 
it is in fact more -restrictive- and should thus count as -discouraging-. And 
imo picking different names for loop variables in such a case is rather a good 
thing. But, again, "more good ain't more ease".

Nit : retrospectively I believe I let you push me into equating "closures" with 
"lexically nested function scopes", but am I right in believing "closures" in 
fact implies functions defined with nested scopes be exported/returned outside 
of the parent scope ?

...
 > I don't believe that Guido is the end-all-be-all of language
 > design, but I do find that I agree with him more often than not (though
 > perhaps not vv), and at least in regards to this particular
 > functionality, I side with the 'status quo' end of things.

I dont understand the "(though perhaps not vv)". Is the "vv" intended to stand 
for "you" (eg, myself) ? I've always liked Guido's Python a lot, and part of it 
has to do with the ante-Bill-Gates "magic of programming". For a looong while, 
my consistent experience with  the "Where do you want to go today ?" MS slogan 
- 
as illustrated by MS products - has been that whenever you tried to find 
imaginative programming solutions (as opposed to "obeying the designer's 
obvious 
expectation despite his claim he lets you free") you would collide with glass 
walls... or end up at a "billing gate" (=some commercial extension product). 
I've had slightly better experience in later years.

Python always had a completely different feel, more like the restitution of the 
old magic to new generations. (btw, Prolog is the language that most gave me 
that feeling of "allowing spectacular escapes from the designer's obvious 
expectations", so it is not a matter of constraints - prolog is quite 
constraining. I think it has to do with consistency and humbleness of a design 
that is not trying to out-think its users).

As concerns the case in point, I think it was unfortunate that you would not 
let 
come into the open that the (risk of) inadvertent capture of builtins by 
un-nested function scopes was critical to the shape of the "feature". Indeed, 
speaking of "status quo ante" : augmented assignments arrived with Python 2.0, 
while nested scopes where 

Re: [OT] code is data

2006-06-20 Thread Boris Borcic
bruno at modulix wrote:
> Anton Vredegoor wrote:
>> bruno at modulix wrote:
>>
>>> I still don't get the point.
>>
>> Well, I've got to be careful here, lest I'd be associated with the
>> terr.., eh, the childp..., eh the macro-enablers.
>>
>> The idea is to have a way to transform a Python (.py) module into XML
>> and then do source code manipulations in XML-space using ElementTree.
> 
> My my my... I'm not against the idea of dynamic source code
> transformation, but for heaven's sake, *why* would one put XML in the
> mix ???

If a good transform could "reveal" xml as "python's s-expression syntax", not 
only would source2source transform using xml t2t transform tools be 
facilitated, 
but generally speaking it would be easier for "xml retro-coded" python source 
to 
find its way through xml-enabled tools&chains. And incite developpers of such 
tools to consider python a better candidate (eg than it currently is) whenever 
the matter of scripting the tool comes up.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to generate all permutations of a string?

2006-06-23 Thread Boris Borcic
Another generator solution, based on computing a permutation from its rank 
according to some natural order. Written for strings.

def perms(s) :
 def nth(n,L,k=1) :
 if k>len(L) :
 if n :
 raise StopIteration
 return ''
 return nth(n/k,L,k+1)+L.pop(n%k)
 for n in xrange(1<<30) :
 yield nth(n,list(s))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to generate all permutations of a string?

2006-06-26 Thread Boris Borcic
I wrote:
> Another generator solution, based on computing a permutation from its 
> rank according to some natural order. Written for strings.
> 
> def perms(s) :
> def nth(n,L,k=1) :
> if k>len(L) :
> if n :
> raise StopIteration
> return ''
> return nth(n/k,L,k+1)+L.pop(n%k)
> for n in xrange(1<<30) :
> yield nth(n,list(s))

Same principle, simpler (no recursion, no helper func, less tokens, easier to 
read) :

def perms(s) :
 for n in xrange(1<<30) :
 R,L = [],list(s)
 while L :
 n,k = divmod(n,len(L))
 R.append(L.pop(k))
 if n : break
 yield ''.join(R)

Or if you *really* prefer lisp-style recursions, here is the solution as a 
single lambda that returns a tuple of strings (not a generator as above)

perms = lambda *S : \
 (len(S)>=len(S[0]) and S[0]==S[-1]) \
 and S[min(1,len(S)-1):] \
 or perms(''.join(L.pop(k)
  for n,L in [[len(S),list(S[-1])]]
  for _ in S[0]
  for n,k in [divmod(n,len(L))]
  )
  ,*S)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python SOAP and XML-RPC performance extremely low?

2006-07-06 Thread Boris Borcic
Jack wrote:
> When I try TooFPy with the SOAP and XML-RPC sample client code
> provided in TooFPy tutorials, a log entry shows up quickly on web server
> log window, but it takes a long time (5 seconds or longer) for the client
> to output a "Hello you." It seems like the web server is fast because the 
> log
> entry shows immieidately on web server console. But it takes Python XML/SOAP 
> parser a long time to parse the extremely simple result. If so, wouldn't 
> this
> render Python SOAP and XMP-RPC implementation useless in real life? 


5 secs looks really huge to just parse an "extremely simple" message. I'd 
rather 
suspect some sort of timeout delay.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: iterator question

2006-09-26 Thread Boris Borcic
Neal Becker wrote:
> Any suggestions for transforming the sequence:
> 
> [1, 2, 3, 4...]
> Where 1,2,3.. are it the ith item in an arbitrary sequence
> 
> into a succession of tuples:
> 
> [(1, 2), (3, 4)...]
> 
> In other words, given a seq and an integer that specifies the size of tuple
> to return, then for example:

 >>> trf = lambda iterable,n : zip(*[iter(iterable)]*n)
 >>> trf(range(15),3)
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11), (12, 13, 14)]


note though that it will silently drop any remainder.

hth, bb
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Will GPL Java eat into Python marketshare?

2006-11-17 Thread Boris Borcic
Harry George wrote:
> 
> Personally, I've never gotten jpype to work.  Is it just me, or is it
> a troublesome install?
> 

It worked for my purpose (connecting to a 4D database via JDBC over Open4D, as 
the ODBC driver for that db is really horrible) until I tried to use this setup 
together with cherrypy, what crashed loudly and consistently for reasons I 
failed to discern. Some initial [class]path issues, as well.

Cheers, BB
-- 
http://mail.python.org/mailman/listinfo/python-list


psyco-simplified idioms ?

2006-11-23 Thread Boris Borcic
I am curious about idioms instinctively avoided by experienced programmers 
because of inefficiencies that psyco eliminates. IOW, are there any 
identifiable 
ways in which the backing of psyco promotes simpler code by eliminating 
efficiency concerns ?

Best, BB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Routine for prefixing '>' before every line of a string

2006-12-14 Thread Boris Borcic
Sanjay wrote:
> Hi All,
> 
> Is somewhere a routine useful to convert a string to lines of maxsize,
> each prefixed with a '>'. This is a typical requirement for 'keeping
> existing text while replying to a post in a forum'.
> 
> It can be developed, but if something obvious is already there(I being
> new to python might not be aware), than it would be great just to reuse
> it!
> 
> thanks
> sanjay
> 

def fixlines(stuff) :
for line in stuff.split(line_separator) :
for chunkstart in range(0,len(line),maxsize) :
yield prefix + line[chunkstart:chunkstart+maxsize]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Xah's Edu Corner: Introduction to 3D Graphics Programing

2006-12-23 Thread Boris Borcic
Xah Lee wrote:
> Of Interest:

to which of comp.lang.perl.misc, comp.lang.python, comp.lang.lisp, 
comp.lang.java.programmer, comp.lang.functional ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pow() works but sqrt() not!?

2007-01-04 Thread Boris Borcic
siggi wrote:
> Hi all,
> 
> this is a newbie question on :
> Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on
> win32
> PC with WinXP
> 
> In
> http://www.python.org/doc/2.3.5/lib/module-math.html
> I read:
> 
> "sqrt( x) Return the square root of x."
> 
> Now the test for module math with function pow():
> ---
 pow(9,9)
> 387420489
> 
>  Fine, but sqrt() fails:
> ---

BTW note that (of course) you can write pow(x,.5) or x**.5 for sqrt(x)
without any preliminary import statement
-- 
http://mail.python.org/mailman/listinfo/python-list


AIML, Python, Java

2007-07-04 Thread Boris Ozegovic
Hi

I have a chatterbot written in AIML.  I am using PyAIML, and HTTP server as
a mediator between user and PyAIML.  Server calls PyAIML, and sends the
result string to the sensor network which is written in Java; and in the
end, server returns value from Java method.  Can I somehow call Java
methods inside Python code, or I must use Jython?  Can I use PyAIML in
Jython?  

-- 
Ne dajte da nas lažljivac Bandić truje:
http://cnn.blog.hr/arhiva-2007-06.html#1622776372
-- 
http://mail.python.org/mailman/listinfo/python-list


httplib module

2007-07-07 Thread Boris Ozegovic
Why do I get double new lines when geting data from server?  Example:

I have a following file:
--start-


Ovo je testni primjerak


--end---

And the code is:
conn = httplib.HTTPConnection("localhost:8000")
conn.request("GET", "/folder/index.html")
response = conn.getresponse()
reply = response.read()

print reply
\n\n\n\nOvo je testni primjerak\n\n\n\n\n\n

-- 
Ne dajte da nas lažljivac Bandić truje:
http://cnn.blog.hr/arhiva-2007-06.html#1622776372
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: httplib module

2007-07-07 Thread Boris Ozegovic
Boris Ozegovic wrote:

> Why do I get double new lines when geting data from server?  Example:

Fixed.

-- 
Ne dajte da nas lažljivac Bandić truje:
http://cnn.blog.hr/arhiva-2007-06.html#1622776372
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: httplib module

2007-07-08 Thread Boris Ozegovic
Steve Holden wrote:

>>> Why do I get double new lines when geting data from server?  Example:
> How? It's customary to include details when you've solved your own 
> problem in case someone else gets the same issue.

Ok.  In do_GET I had this two lines:

for line in file:
print line 

As you can see, print inserted another \n.  :-)

Correct code is:

for line in file:
print line, 

-- 
Ne dajte da nas lažljivac Bandić truje:
http://cnn.blog.hr/arhiva-2007-06.html#1622776372
-- 
http://mail.python.org/mailman/listinfo/python-list


Significance of "start" parameter to string method "endswith"

2007-04-19 Thread Boris Dušek
Hello,

what is the use-case of parameter "start" in string's "endswith"
method? Consider the following minimal example:

a = "testing"
suffix="ing"
a.endswith(suffix, 2)

Significance of "end" is obvious. But not so for "start".

Let's assume the "end" parameter is not used - then the function
should simple check that the last "len(suffix)" characters of "a" are
equal to "ing", no matter where we start (the function does not *scan*
the string from the "start", does it?)
Only case where it would make difference is if we had start +
len(suffix) < len(a) (excuse possible "of-by-one" error :-)
Then the function would never return True. But is there a real use
case when we would test for endswith like this? (knowing that it must
return false?)

Thanks for any ideas/experience.
Boris

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Significance of "start" parameter to string method "endswith"

2007-04-19 Thread Boris Dušek
On Apr 19, 10:36 pm, subscriber123 <[EMAIL PROTECTED]> wrote:
> On Apr 19, 3:58 pm, Boris Dušek <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hello,
>
> > what is the use-case of parameter "start" in string's "endswith"
> > method?

> def foo(function,instance,param):
> if function(instance,param,2,4):
> return True
> else: return False
>
> The function must work whether you pass it
> foo(str.endswith,"blaahh","ahh"), or
> foo(str.startswith,"blaahh","aah"). This is a really bad example, but
> it gets the point across that similar functions must have similar
> parameters in order to be Pythonic.

Thanks for explanation, this point makes sense. And I agree that I can
hardly imagine any use of both parameters :-).

-- 
http://mail.python.org/mailman/listinfo/python-list

lambda generator - curious behavior in 2.5

2007-04-21 Thread Boris Borcic
 >>> x = (lambda : ((yield 666),(yield 777),(yield 888)))()
 >>> x.next()
666
 >>> x.next()
777
 >>> x.next()
888
 >>> x.next()
(None, None, None)
 >>> x = (lambda : ((yield 666),(yield 777),(yield 888)) and None)()
 >>> x.next()
666
 >>> x.next()
777
 >>> x.next()
888
 >>> x.next()

Traceback (most recent call last):
   File "", line 1, in 
 x.next()
StopIteration
 >>>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: File record separators.

2007-05-15 Thread Boris Borcic
HMS Surprise wrote:
> Thanks folks. Was unaware of enumerate , still have a lot to learn
> about python.
> 
> Sorry for the poorly phrased request, but you gathered the gist of it.
> My wonderment is how to write the following 2 lines and make sure they
> are saved as separate records or lines so that I pull in only one at a
> time with readline(?).
> 
> ['a', 'b'], ['c','d']]
> [['a', 'b'], ['c','d'], ['e','f']]
> 
> Would like to use pickle but it is apparently unavailable in the
> package I am using, Jython 2.2.

I am pretty sure some version of pickle or cPickle is available in Jython 2.1, 
though. I'd take a second look, to be sure.

-- 
http://mail.python.org/mailman/listinfo/python-list


Base class for file-like objects? (a.k.a "Stream" in Java)

2007-07-24 Thread Boris Dušek
Hello,

(sorry to begin with Java in a Python list ;-)
in Java, when I want to pass input to a function, I pass
"InputStream", which is a base class of any input stream.

In Python, I found that "file" objects exist. While specifying
argument types in Python is not possible as in Java, it is possible to
check whether an object is an instance of some class and that's what I
need - I need to check if an argument is a "file"-like object, and if
yes, behave accordingly, if not, treat the argument as string with
URL.

But I am afraid there is no such a base class - I tried the following:

>>> import urllib
>>>
>>> f = open("test.txt", "r")
>>> g = urllib.urlopen("http://www.google.com/";)
>>>
>>> isinstance(f, file)
True
>>> isinstance(f, file)
False
...

Is there some base class to "file"-like (or "stream"-like) objects in
Python? And if not, is it at least planned for Python 3.0?

Thanks for any suggestions,
Boris Dušek

P.S.: The code should finally look in esence something like this:

if isinstance(f, file):
   pass
elif isinstance(f, string):
   f = urllib.urlopen(f)
else:
   raise "..."
process_stream(f)

-- 
http://mail.python.org/mailman/listinfo/python-list

cookielib

2007-08-10 Thread Boris Ozegovic
Hi

I have HTTP client which accepts cookies.  If client allready has cookie,
but that cookie has expired, server sends him new cookie, and in response
object Set-Cookie: header everything is fine, but if I reload request,
client sends expired cookie, and not the new one.  In cookiejar there is
only new and valid cookie, and if I use regular browser everything is fine.
The code is following:

urlopen = urllib2.urlopen
Request = urllib2.Request
cj = cookielib.LWPCookieJar()
COOKIEFILE = 'cookies.lwp'

if os.path.isfile(COOKIEFILE):
# if we have a cookie file already saved
# then load the cookies into the Cookie Jar
cj.load(COOKIEFILE)

opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)
url = "http://localhost:8000/files/index.html";
params = {'question':question}
data = urllib.urlencode(params)
Request(url, data)
try:
response = urlopen(Request)
etc.

Only if I create new request object the new cookie is send, but I don't
want to create new object.  And idea?

-- 
Ne dajte da nas lažljivac Bandić truje:
http://cnn.blog.hr/arhiva-2007-06.html#1622776372
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: make images with python

2007-08-15 Thread Boris Borcic
Lawrence Oluyede wrote:
> stefano <[EMAIL PROTECTED]> wrote:
>> I need make some images using python but i'm lost :P
> 
> 
> 

If you want to do antialiased drawings into images,
you might rather want to look for pil at

http://effbot.org/downloads/

and grab PIL together with the aggdraw extension
(while "core" PIL includes some drawing primitives,
last time I tried they weren't antialiased).

Best, BB

-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >