Re: Usenet vs. Mailing-list

2023-01-29 Thread Ben Bacarisse
Igor Berger  writes:

> On Saturday, January 28, 2023 at 10:02:57 PM UTC-5, Ben Bacarisse wrote:
>> Jon Ribbens  writes: 
>> 
>> > On 2023-01-29, Ben Bacarisse  wrote: 
>> >> "Peter J. Holzer"  writes: 
>> >> 
>> >>> On 2023-01-27 21:04:58 +, Ben Bacarisse wrote: 
>> >>>> mut...@dastardlyhq.com writes: 
>> >>>> 
>> >>>> > Hi 
>> >>>> 
>> >>>> It looks like you posted this question via Usenet. comp.lang.python is 
>> >>>> essentially dead as a Usenet group. It exists, and gets NNTP versions 
>> >>>> of mail sent to the mailing list, but nothing posted to the group via 
>> >>>> NNTP get send on the mailing list. 
>> >>> 
>> >>> This is wrong. I did get Muttley's any your postings via the 
>> >>> mailing-list. 
>> >> 
>> >> Ah, OK. I thought that was the case but I am obviously wrong. Has 
>> >> there been a change, or have I been wrong for a long time!? 
>> > 
>> > I'm not aware of any significant period in the last twenty-one years 
>> > that it hasn't been working. Although sometimes it does feel like it 
>> > isn't, in that I reply to a post with an answer and then several 
>> > other people reply significantly later with the same answer, as if 
>> > my one had never existed... but whenever I check into it, my message 
>> > has actually always made it to the list.
>>
>> I have had the same experience and, as a result, I rarely post. Maybe 
>> what I have to say is simply not interesting! 
>> 
>
> If I remember correctly, multiple regulars that use the mailing list
> mentioned that they "killfiled" posts originating from Google groups.
> This may contribute to such situations.

Ah, that may explain most of my confusion.  I know I stopped posting
because there didn't seem to be much engagement, but maybe it was just
many list members choosing not to see my posts rather than all list
members not being able to see my posts.

As I said, I did check to see if I could find a reply to a
Usenet-originated post from a list member but my not being able to find
one could just be down to many list members filtering Usenet posts.
It's clearly not universal.

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


Re: Usenet vs. Mailing-list

2023-01-28 Thread Ben Bacarisse
Jon Ribbens  writes:

> On 2023-01-29, Ben Bacarisse  wrote:
>> "Peter J. Holzer"  writes:
>>
>>> On 2023-01-27 21:04:58 +, Ben Bacarisse wrote:
>>>> mutt...@dastardlyhq.com writes:
>>>> 
>>>> > Hi
>>>> 
>>>> It looks like you posted this question via Usenet.  comp.lang.python is
>>>> essentially dead as a Usenet group.  It exists, and gets NNTP versions
>>>> of mail sent to the mailing list, but nothing posted to the group via
>>>> NNTP get send on the mailing list.
>>>
>>> This is wrong. I did get Muttley's any your postings via the
>>> mailing-list.
>>
>> Ah, OK.  I thought that was the case but I am obviously wrong.  Has
>> there been a change, or have I been wrong for a long time!?
>
> I'm not aware of any significant period in the last twenty-one years
> that it hasn't been working. Although sometimes it does feel like it
> isn't, in that I reply to a post with an answer and then several
> other people reply significantly later with the same answer, as if
> my one had never existed... but whenever I check into it, my message
> has actually always made it to the list.

I have had the same experience and, as a result, I rarely post.  Maybe
what I have to say is simply not interesting!

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


Re: Usenet vs. Mailing-list

2023-01-28 Thread Ben Bacarisse
"Peter J. Holzer"  writes:

> On 2023-01-27 21:04:58 +, Ben Bacarisse wrote:
>> mutt...@dastardlyhq.com writes:
>> 
>> > Hi
>> 
>> It looks like you posted this question via Usenet.  comp.lang.python is
>> essentially dead as a Usenet group.  It exists, and gets NNTP versions
>> of mail sent to the mailing list, but nothing posted to the group via
>> NNTP get send on the mailing list.
>
> This is wrong. I did get Muttley's any your postings via the
> mailing-list.

Ah, OK.  I thought that was the case but I am obviously wrong.  Has
there been a change, or have I been wrong for a long time!?

There may be a timing issue because I tried to find a reply a Usenet
injected post from a mailing-list user and, at the time I looked, I
could not find one.

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


Re: evaluation question

2023-01-27 Thread Ben Bacarisse
mutt...@dastardlyhq.com writes:

> Hi

It looks like you posted this question via Usenet.  comp.lang.python is
essentially dead as a Usenet group.  It exists, and gets NNTP versions
of mail sent to the mailing list, but nothing posted to the group via
NNTP get send on the mailing list.  I prefer Usenet and dislike mailing
lists but that just means I can't really contribute to this "group"

The "python-list" an an excellent resource (if you like the email
interface) and you can subscribe here:

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

> This is probably a dumb newbie question but I've just started to learn
> python3 and eval() isn't behaving as I'd expect in that it works for
> some things and not others. eg:
>
 eval("1+1")
> 2
 eval("print(123)")
> 123
 eval("for i in range(1,10): i")
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "", line 1
> for i in range(1,10): i
>   ^
> SyntaxError: invalid syntax
>
> Why did the 3rd one fail? Does it not handle complex expressions?

It handles only expressions, and "for i in range(1,10): i" is not an
expression.  You can use

>>> exec("for i in range(1,10): i")

or, to confirm that something is happening:

>>> exec("for i in range(1,10): print(i)")
1
2
3
4
5
6
7
8
9

See: https://docs.python.org/3/library/functions.html?highlight=eval#eval
and the immediately following entry.

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


Re: bool and int

2023-01-26 Thread Ben Bacarisse
Chris Angelico  writes:

> On Thu, 26 Jan 2023 at 08:19, Dino  wrote:
>>
>> On 1/23/2023 11:22 PM, Dino wrote:
>> >  >>> b = True
>> >  >>> isinstance(b,bool)
>> > True
>> >  >>> isinstance(b,int)
>> > True
>> >  >>>
>>
>> ok, I read everything you guys wrote. Everyone's got their reasons
>> obviously, but allow me to observe that there's also something called
>> "principle of least surprise".
>>
>> In my case, it took me some time to figure out where a nasty bug was
>> hidden. Letting a bool be a int is quite a gotcha, no matter how hard
>> the benevolent dictator tries to convince me otherwise!
>>
>
> Try this (or its equivalent) in as many languages as possible:
>
> x = (1 > 2)
> x == 0
>
> You'll find that x (which has effectively been set to False, or its
> equivalent in any language) will be equal to zero in a very large
> number of languages. Thus, to an experienced programmer, it would
> actually be quite the opposite: having it NOT be a number would be the
> surprising thing!

I think the programmer's experience would have to have been rather
narrow to be surprised by x not being treated as a number.  I started
with Fortran, Lisp, Pascal and two variants of Algol so I started out
un-surprised by Boolean being a non-arithmetic type.  To be surprised by
x (above) /not/ being treated as a number, an experienced programmer
would have had to have avoided a lot of strictly typed languages.

I've just tried Scheme, Haskell, Common Lisp, Ada, Algol-68, go, ML,
Rust, Ruby, Java, Lua, Prolog and Fortran and they all either say "no
way!" or give false for x == 0.  Of course these are not random choices,
but it shows that Python's design is very far from universal.

But then this is not a numbers game, anyway.  A programmer need only to
have used one or two languages that are rather more strict about types
to find such a thing unsurprising in future.

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


Re: Local variable definition in Python list comprehension

2022-09-01 Thread Ben Bacarisse
James Tsai  writes:

> I find it very useful if I am allowed to define new local variables in
> a list comprehension. For example, I wish to have something like
> [(x, y) for x in range(10) for y := x ** 2 if x + y < 80], or
> [(x, y) for x in range(10) with y := x ** 2 if x + y < 80].
>
> For now this functionality can be achieved by writing
> [(x, y) for x in range(10) for y in [x ** 2] if x + y < 80].

x and y are, to a first approximation, new local variables defined in a
list comprehension.  I think you need to restate what it is you want.

> Is it worthwhile to add a new feature like this in Python? If so, how
> can I propose this to PEP?

To make any sort of case you'd need to give an example that does not
have a clearer way to write it already.  Your working version is, to me,
clearer that the ones you want to be able to write.

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


Re: Unexpected behaviour of math.floor, round and int functions (rounding)

2021-11-20 Thread Ben Bacarisse
Grant Edwards  writes:

> On 2021-11-20, Ben Bacarisse  wrote:
>
>> You seem to be agreeing with me.  It's the floating point part that is
>> the issue, not the base itself.
>
> No, it's the base. Floating point can't represent 3/10 _because_ it's
> base 2 floating point. Floating point in base 10 doesn't have any
> problem representing 3/10.

Every base has the same problem for some numbers.  It's the floating
point part that causes the problem.

Binary and decimal stand out because we write a lot of decimals in
source code and computers use binary, but if decimal floating point were
common (as it increasingly is) different fractions would become the oft
quoted "surprise" results.

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


Re: Unexpected behaviour of math.floor, round and int functions (rounding)

2021-11-20 Thread Ben Bacarisse
Chris Angelico  writes:

> On Sat, Nov 20, 2021 at 3:41 PM Ben Bacarisse  wrote:
>>
>> Chris Angelico  writes:
>>
>> > On Sat, Nov 20, 2021 at 12:43 PM Ben Bacarisse  
>> > wrote:
>> >>
>> >> Chris Angelico  writes:
>> >>
>> >> > On Sat, Nov 20, 2021 at 9:07 AM Ben Bacarisse  
>> >> > wrote:
>> >> >>
>> >> >> Chris Angelico  writes:
>> >> >>
>> >> >> > On Sat, Nov 20, 2021 at 5:08 AM ast  wrote:
>> >> >>
>> >> >> >>  >>> 0.3 + 0.3 + 0.3 == 0.9
>> >> >> >> False
>> >> >> >
>> >> >> > That's because 0.3 is not 3/10. It's not because floats are
>> >> >> > "unreliable" or "inaccurate". It's because the ones you're entering
>> >> >> > are not what you think they are.
>> >> >> >
>> >> >> > When will people understand this?
>> >> >> >
>> >> >> > (Probably never. Sigh.)
>> >> >>
>> >> >> Most people understand what's going on when it's explained to them.  
>> >> >> And
>> >> >> I think that being initially baffled is not unreasonable.  After all,
>> >> >> almost everyone comes to computers after learning that 3/10 can be
>> >> >> written as 0.3.  And Python "plays along" with the fiction to some
>> >> >> extent.  0.3 prints as 0.3, 3/10 prints as 0.3 and 0.3 == 3/10 is True.
>> >> >
>> >> > In grade school, we learn that not everything can be written that way,
>> >> > and 1/3 isn't actually equal to 0.33.
>> >>
>> >> Yes.  We learn early on that 0.33 means 33/100.
>> >> We don't learn that 0.33 is a special notation for machines that
>> >> have something called "binary floating point hardware" that does not
>> >> mean 33/100.  That has to be learned later.  And every
>> >> generation has to learn it afresh.
>> >
>> > But you learn that it isn't the same as 1/3. That's my point. You
>> > already understand that it is *impossible* to write out 1/3 in
>> > decimal. Is it such a stretch to discover that you cannot write 3/10
>> > in binary?
>> >
>> > Every generation has to learn about repeating fractions, but most of
>> > us learn them in grade school. Every generation learns that computers
>> > talk in binary. Yet, putting those two concepts together seems beyond
>> > many people, to the point that they feel that floating point can't be
>> > trusted.
>>
>> Binary is a bit of a red herring here.  It's the floating point format
>> that needs to be understood.  Three tenths can be represented in many
>> binary formats, and even decimal floating point will have some surprises
>> for the novice.
>
> Not completely a red herring; binary floating-point as used in Python
> (IEEE double-precision) is defined as a binary mantissa and a scale,
> just as "blackboard arithmetic" is generally defined as a decimal
> mantissa and a scale. (At least, I don't think I've ever seen anyone
> doing arithmetic on a blackboard in hex or octal.)

You seem to be agreeing with me.  It's the floating point part that is
the issue, not the base itself.

>> >> Yes, agreed, but I was not commenting on the odd (and incorrect) view
>> >> that floating point operations are not reliable and well-defined, but on
>> >> the reasonable assumption that a clever programming language might take
>> >> 0.3 to mean what I was taught it meant in grade school.
>> >
>> > It does mean exactly what it meant in grade school, just as 1/3 means
>> > exactly what it meant in grade school. Now try to represent 1/3 on a
>> > blackboard, as a decimal fraction. If that's impossible, does it mean
>> > that 1/3 doesn't mean 1/3, or that 1/3 can't be represented?
>>
>> As you know, it is possible, but let's say we outlaw any finite notation
>> for repeated digits...  Why should I convert 1/3 to this particular
>> apparently unsuitable representation?  I will write 1/3 and manipulate
>> that number using factional notation.
>
> If you want that, the fractions module is there for you.

Yes, I know.  The only point of disagreement (as far as can see) is
that literals like 0.3 appears to be confusing for beginners.  You think
they should kno

Re: Unexpected behaviour of math.floor, round and int functions (rounding)

2021-11-19 Thread Ben Bacarisse
Chris Angelico  writes:

> On Sat, Nov 20, 2021 at 12:43 PM Ben Bacarisse  wrote:
>>
>> Chris Angelico  writes:
>>
>> > On Sat, Nov 20, 2021 at 9:07 AM Ben Bacarisse  wrote:
>> >>
>> >> Chris Angelico  writes:
>> >>
>> >> > On Sat, Nov 20, 2021 at 5:08 AM ast  wrote:
>> >>
>> >> >>  >>> 0.3 + 0.3 + 0.3 == 0.9
>> >> >> False
>> >> >
>> >> > That's because 0.3 is not 3/10. It's not because floats are
>> >> > "unreliable" or "inaccurate". It's because the ones you're entering
>> >> > are not what you think they are.
>> >> >
>> >> > When will people understand this?
>> >> >
>> >> > (Probably never. Sigh.)
>> >>
>> >> Most people understand what's going on when it's explained to them.  And
>> >> I think that being initially baffled is not unreasonable.  After all,
>> >> almost everyone comes to computers after learning that 3/10 can be
>> >> written as 0.3.  And Python "plays along" with the fiction to some
>> >> extent.  0.3 prints as 0.3, 3/10 prints as 0.3 and 0.3 == 3/10 is True.
>> >
>> > In grade school, we learn that not everything can be written that way,
>> > and 1/3 isn't actually equal to 0.33.
>>
>> Yes.  We learn early on that 0.33 means 33/100.
>> We don't learn that 0.33 is a special notation for machines that
>> have something called "binary floating point hardware" that does not
>> mean 33/100.  That has to be learned later.  And every
>> generation has to learn it afresh.
>
> But you learn that it isn't the same as 1/3. That's my point. You
> already understand that it is *impossible* to write out 1/3 in
> decimal. Is it such a stretch to discover that you cannot write 3/10
> in binary?
>
> Every generation has to learn about repeating fractions, but most of
> us learn them in grade school. Every generation learns that computers
> talk in binary. Yet, putting those two concepts together seems beyond
> many people, to the point that they feel that floating point can't be
> trusted.

Binary is a bit of a red herring here.  It's the floating point format
that needs to be understood.  Three tenths can be represented in many
binary formats, and even decimal floating point will have some surprises
for the novice.

>> Yes, agreed, but I was not commenting on the odd (and incorrect) view
>> that floating point operations are not reliable and well-defined, but on
>> the reasonable assumption that a clever programming language might take
>> 0.3 to mean what I was taught it meant in grade school.
>
> It does mean exactly what it meant in grade school, just as 1/3 means
> exactly what it meant in grade school. Now try to represent 1/3 on a
> blackboard, as a decimal fraction. If that's impossible, does it mean
> that 1/3 doesn't mean 1/3, or that 1/3 can't be represented?

As you know, it is possible, but let's say we outlaw any finite notation
for repeated digits...  Why should I convert 1/3 to this particular
apparently unsuitable representation?  I will write 1/3 and manipulate
that number using factional notation.

The novice programmer might similarly expect that when they write 0.3,
the program will manipulate that number as the faction it clearly is.
They may well be surprised by the fact that it must get put into a
format that can't represent what those three characters mean, just as I
would be surprised if you insisted I write 1/3 as a finite decimal (with
no repeat notation).

I'm not saying your analogy would not help someone understand, but you
first have to explain why 0.3 is not treated as three tenths -- why I
(to use your analogy) must not keep 1/3 as a proper fraction, but I must
instead write it using a finite number of decimal digits.  Neither is,
in my view, obvious to the beginner.

>> > But lack of knowledge is never a problem. (Or rather, it's a solvable
>> > problem, and I'm always happy to explain things to people.) The
>> > problem is when, following that lack of understanding, people assume
>> > that floats are "unreliable" or "inaccurate", and that you should
>> > never ever compare two floats for equality, because they're never
>> > "really equal". That's what leads to horrible coding practices and
>> > badly-defined "approximately equal" checks that cause far more harm
>> > than a simple misunderstanding ever could on its own.
>>
>> Agreed.  Often, the "explanations" just make things w

Re: Unexpected behaviour of math.floor, round and int functions (rounding)

2021-11-19 Thread Ben Bacarisse
Chris Angelico  writes:

> On Sat, Nov 20, 2021 at 9:07 AM Ben Bacarisse  wrote:
>>
>> Chris Angelico  writes:
>>
>> > On Sat, Nov 20, 2021 at 5:08 AM ast  wrote:
>>
>> >>  >>> 0.3 + 0.3 + 0.3 == 0.9
>> >> False
>> >
>> > That's because 0.3 is not 3/10. It's not because floats are
>> > "unreliable" or "inaccurate". It's because the ones you're entering
>> > are not what you think they are.
>> >
>> > When will people understand this?
>> >
>> > (Probably never. Sigh.)
>>
>> Most people understand what's going on when it's explained to them.  And
>> I think that being initially baffled is not unreasonable.  After all,
>> almost everyone comes to computers after learning that 3/10 can be
>> written as 0.3.  And Python "plays along" with the fiction to some
>> extent.  0.3 prints as 0.3, 3/10 prints as 0.3 and 0.3 == 3/10 is True.
>
> In grade school, we learn that not everything can be written that way,
> and 1/3 isn't actually equal to 0.33.

Yes.  We learn early on that 0.33 means 33/100.
We don't learn that 0.33 is a special notation for machines that
have something called "binary floating point hardware" that does not
mean 33/100.  That has to be learned later.  And every
generation has to learn it afresh.

> Yet somehow people
> understand that computers speak binary ("have you learned to count
> yet, or are you still on zeroes and ones?" -- insult to a machine
> empire, in Stellaris), but don't seem to appreciate that floats are
> absolutely accurate and reliable, just in binary.

Yes, agreed, but I was not commenting on the odd (and incorrect) view
that floating point operations are not reliable and well-defined, but on
the reasonable assumption that a clever programming language might take
0.3 to mean what I was taught it meant in grade school.

As an old hand, I know it won't (in most languages), and I know why it
won't, and I know why that's usually the right design choice for the
language.  But I can also appreciate that it's by no means obvious that,
to a beginner, "binary" implies the particular kind of representation
that makes 0.3 not mean 3/10.  After all, the rational 3/10 can be
represented exactly in binary in many different ways.

> But lack of knowledge is never a problem. (Or rather, it's a solvable
> problem, and I'm always happy to explain things to people.) The
> problem is when, following that lack of understanding, people assume
> that floats are "unreliable" or "inaccurate", and that you should
> never ever compare two floats for equality, because they're never
> "really equal". That's what leads to horrible coding practices and
> badly-defined "approximately equal" checks that cause far more harm
> than a simple misunderstanding ever could on its own.

Agreed.  Often, the "explanations" just make things worse.

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


Re: Unexpected behaviour of math.floor, round and int functions (rounding)

2021-11-19 Thread Ben Bacarisse
Chris Angelico  writes:

> On Sat, Nov 20, 2021 at 5:08 AM ast  wrote:

>>  >>> 0.3 + 0.3 + 0.3 == 0.9
>> False
>
> That's because 0.3 is not 3/10. It's not because floats are
> "unreliable" or "inaccurate". It's because the ones you're entering
> are not what you think they are.
>
> When will people understand this?
>
> (Probably never. Sigh.)

Most people understand what's going on when it's explained to them.  And
I think that being initially baffled is not unreasonable.  After all,
almost everyone comes to computers after learning that 3/10 can be
written as 0.3.  And Python "plays along" with the fiction to some
extent.  0.3 prints as 0.3, 3/10 prints as 0.3 and 0.3 == 3/10 is True.

The language (a language, not Python) could tell you that you were not
getting the value you asked for.  Every 0.3 could come with a warning
that 0.3 can not be represented exactly as a floating point value.  To
avoid the warning, the programmer would write ~0.3 meaning, exactly, the
binary (or whatever the base really is) floating point number closest to
0.3.

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


Re: Help with gaussian filter from scipy

2021-07-07 Thread Ben Bacarisse
Arak Rachael  writes:

> On Wednesday, 7 July 2021 at 12:47:40 UTC+2, Arak Rachael wrote:
>> On Wednesday, 7 July 2021 at 12:41:44 UTC+2, Ben Bacarisse wrote: 
>> > Arak Rachael  writes: 
>> > 
>> > > this time I am stuck on gaussian_filter scipy returns none instead of 
>> > > some valid gaussian filtered image, can someone help me please. 
>> > > 
>> > > Here is the full code: 
>> > > https://www.dropbox.com/s/18ylpiwmhlu5n62/test_filter_xdog.ipynb?dl=0 
>> > It might help to link to the code itself so people can look at it 
>> > without having to load up a project. 
>> > 
>> > -- 
>> > Ben.
>> Sorry I don't have this option. 
>> 
>> I loaded it in PyCharm and this is what I got: 
>> 
>> /home/yordan/anaconda3/envs/testing/bin/python 
>> /home/yordan/pycharm/plugins/python-ce/helpers/pydev/pydevd.py --multiproc 
>> --qt-support=auto --client 127.0.0.1 --port 36321 --file 
>> /home/yordan/devel/python.assignments/topgis-viz/topgisviz/xdog.py 
>> Connected to pydev debugger (build 211.7442.45) 
>> Usage: python xdog.py FILE OUTPUT 
>> 
>> I tried creating "'./textures/hatch.jpg" image, but it did not work.
>
> Sorry for taking your time, this turns to be a dum question, I needed
> to supply in file and out file in the command line.

No worries. Sometimes just posting the question make you look at it
differently. If you can post code, it's much better to do that.  Had it
been a little bit more obscure a problem, someone might have spotted it
but they may not have wanted to load a project file.

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


Re: Help with gaussian filter from scipy

2021-07-07 Thread Ben Bacarisse
Arak Rachael  writes:

> this time I am stuck on gaussian_filter scipy returns none instead of some 
> valid gaussian filtered image, can someone help me please.
>
> Here is the full code:
> https://www.dropbox.com/s/18ylpiwmhlu5n62/test_filter_xdog.ipynb?dl=0

It might help to link to the code itself so people can look at it
without having to load up a project.

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


Re: neonumeric - C++ arbitrary precision arithmetic library

2021-03-06 Thread Ben Bacarisse
Mr Flibble  writes:

>> Someone who says that he is capable of writing a compiler that
>> translates every language has megalomania. No one can do this.
>
> Just because you can't make one it doesn't follow that nobody else
> can.

True, but lots of very knowledgeable people have tried and failed.  And
although you use the present tense "my universal compiler, neos, that
/can/ compile any programming language" (emphasis mine) you currently
have nothing to show -- no compiler for any language, no paper outlining
how you plan to overcome the problems that stumped others, nothing but
what appears to be a false claim about neos can do.  If you want this
project to be taken seriously, you are going about it the wrong way.

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


Re: New Python implementation

2021-02-16 Thread Ben Bacarisse
"Avi Gross"  writes:

> Thanks for sharing. I took a look and he does have a few schemas for Ada and
> C from TWO YEARS ago. Nothing about the infinite number of other languages
> he plans on supporting, let alone Python. And what he has is likely not
> enough to do what he claims he can do easily and rapidly.

The C schema says almost nothing about C.  It lists one kind of comment
and a few type names.  Significantly, it says almost nothing about the
semantics of even the tiny fragment of C presented.

Attempts at a universal compiler stalled in the 1980s (though there may
have been some new developments since I stopped looking) because
expressing the semantics of different languages is so very hard.  In
fact, much of the interest in pursuing the idea came from benefits that
would be derived simply from having a language's semantics formally
described.

I don't think there is anything to see here.  If the author had come up
with some new ways to tackle any of the problems, he would be telling
people about these, not saying "be patient" (and bad-mouthing CPython).

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


Re: Mr. Flibble

2021-02-15 Thread Ben Bacarisse
Ethan Furman  writes:

> On 2/15/21 2:02 PM, Grant Edwards wrote:
>> On 2021-02-15, Ben Bacarisse  wrote:
>>
>>> You said you used Usenet (and your reply here was via Usenet).
>>> Usenet posts to comp.lang.python don't go to the mailing list (the
>>> "here" that Ethan is talking about).  Mails to the list /are/ sent
>>> here, but it's one-way traffic.
>>
>> That's new -- it always used to be two-way. When did it change?
>
> It is two-way still (or we wouldn't have seen his posts to begin
> with).

Ah, my mistake.  Sorry for the confusion.

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


Re: Mr. Flibble

2021-02-15 Thread Ben Bacarisse
Mr Flibble  writes:

> On 15/02/2021 18:09, Ethan Furman wrote:
>> Thank you to those who pointed out this individual to the
>> moderators. As Mr. Flibble accurately noted, he is not on the mailing
>> list -- so his posts won't be here either.
>
> ORLY?

You said you used Usenet (and your reply here was via Usenet).  Usenet
posts to comp.lang.python don't go to the mailing list (the "here" that
Ethan is talking about).  Mails to the list /are/ sent here, but it's
one-way traffic.

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


Re: sqlite3 cannot detect the version of compiled sqlite version at some point in runtime.

2021-01-20 Thread Ben Bacarisse
panfei  writes:

> 4. Test sqlite3
> Python 3.9.1 (default, Jan 20 2021, 14:32:50)
> [GCC 10.2.0] on linux
> Type "help", "copyright", "credits" or "license" for more information.
 import sqlite3
 conn = sqlite3.connect(':memory:')
 conn.create_function('f', 2, lambda *args: None, deterministic=True)
> Traceback (most recent call last):
>   File "", line 1, in 
> sqlite3.NotSupportedError: deterministic=True requires SQLite 3.8.3 or higher
 sqlite3.sqlite_version
> '3.34.0'
 sqlite3.version
> '2.6.0'
 
>
> It reports "deterministic=True requires SQLite 3.8.3 or higher", but
> when execute sqlite3.sqlite_version it returns 3.34.0 which higher
> than 3.8.3.
>
> Is there any advice on this issue? thanks.

Sorry, no, but I can add a data point.  It works for me on my Ubuntu
system with these versions:

$ python3
Python 3.8.5 (default, Jul 28 2020, 12:59:40) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite3
>>> sqlite3.sqlite_version
'3.31.1'
>>> sqlite3.version
'2.6.0'
>>> conn = sqlite3.connect(':memory:')
>>> conn.create_function('f', 2, lambda *args: None, deterministic=True)
>>> 

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


Re: Find word by given characters

2020-11-03 Thread Ben Bacarisse
Bischoop  writes:

> Let me clarify what I want to do:
> We all know Scrabble game.
> there's a file with Dictionary containing word in each line, the idea is
> to input some letters for example mentioned earlier: att, the script
> supposed to find all words in which letters: 'a','t','t' occur and print
> these words. It supposed not to print word: 'auto' because there's only
> one 't' but words such as: 'toast', 'toasty', 'tolerant' are meeting the
> criteria becase we have in these words one 'a' and two 't' as user has
> input.

In Scrabble, you will usually know the order you want for the known
letters, so you could just make a regular expression: t.*a.*t

In fact, you often know the gaps, so you might even be able to match
something more specific like t.a..t instead.

If you don't know the order, you can still make a chain of matches.  For
example, matching for t.*t and then also a.  Every distinct letter needs
a match, and repeated letters need a single match with .* between them.

And since Python REs have (?=...) look ahead syntax you could even make
a single pattern like this:

  (?=.*t.*t)(?=.*a)

While there are probably better ways in Python, this is what I'd do on
the command line.  For example

$ grep -P '(?=.*t.*t)(?=.*a)' word-list | wc -l
45677
$ grep 't.*t' word-list | grep a | wc -l 
45677

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


Re: musings on static variables

2020-09-16 Thread Ben Bacarisse
r...@zedat.fu-berlin.de (Stefan Ram) writes:

>   This C program use a local /static/ variable.
>
>   main.c
>
> #include 
>
> int f( void )
> { static int i = 0;
>   return i++; }
>
> int main( void )
> { printf( "%d\n", f() );
>   printf( "%d\n", f() );
>   printf( "%d\n", f() ); }
>
>   transcript
>
> 0
> 1
> 2
>
>   When asked how to do this in Python, sometimes people
>   suggest to use a module variable for this, or to add "i"
>   to "f" as an attribute, or maybe even to use some kind of
>   closure. Another (more pythonic?) way to do this, would be:
>
>   main.py
>
> def f_():
> i = 0
> while True:
> yield i
> i += 1
>
> f = f_()
> print( next( f ))
> print( next( f ))
> print( next( f ))
>
>   transcript
>
> 0
> 1
> 2

  def f(i = [0]):
  i[0] += 1
  return i[0]
   
  print(f())
  print(f())
  print(f())

maybe?  More than a bit yucky, though.

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


Re: Didn't understand the output of the following Python 3 code with reduce function?

2020-08-28 Thread Ben Bacarisse
Shivlal Sharma  writes:

> I have seen this code on one of competative programming site but I
> didn't get it, Why output is 9?
>
> from functools import *
>
> def ADDS(a,b):
> return a+1
> nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
> add = reduce(ADDS, nums)
> print(add)
>
> output: 9

Hint:

reduce(f, [e1, e2]) is f(e1, e2)
reduce(f, [e1, e2, e3]) is f(f(e1, e2), e3)
reduce(f, [e1, e2, e3, e4]) is f(f(f(e1, e2), e3), e4)

Replace f with a function that adds one to its first argument.  Does
that help?

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


Re: Behaviour of os.path.join

2020-05-27 Thread Ben Bacarisse
Roel Schroeven  writes:

> Ben Bacarisse schreef op 27/05/2020 om 17:53:
>> There is well-known (*nix) software that relies on a/b/c/ meaning
>> something different to a/b/c but I don't know anyone who thinks this is
>> a good idea.  It causes no end of confusion.
>
> rsync? I always have to look up whether or not I need to use a
> trailing / on the source directory. It's confusing indeed.

That was the one I was thinking of.

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


Re: Behaviour of os.path.join

2020-05-27 Thread Ben Bacarisse
BlindAnagram  writes:

> On 27/05/2020 16:53, Ben Bacarisse wrote:

>> As it should.  Relying on a trailing \ having the right effect is
>> brittle to say the least.
>
> In my case less brittle than leaving it out.

Brittle does not mean broken.  I know you can fix it by making sure the
trailing \ is there.  It's that solution that is brittle.

> Its not my bug to fix - the semantics of what I send is very clear on
> any Windows system.

Then there is no bug.  You just constructed the path using a method that
did not behave as you expected.  That happens all the time.

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


Re: Behaviour of os.path.join

2020-05-27 Thread Ben Bacarisse
BlindAnagram  writes:

> On 27/05/2020 13:30, Ben Bacarisse wrote:
>> BlindAnagram  writes:
>> 
>>> The issue that I raised here was whether the behaviour of os.path.join()
>>> in treating the Windows directory separator '\\' as an absolute path
>>> should be considered a bug.
>> 
>> You think it should be considered to be a relative path?  The only
>> meaning that would give you want you wanted from
>> 
>>   os.path.join(, '\\')
>> 
>> would be to treat it as being relative to the drive and to the
>> directory.  In other words you want '\\' to be a synonym for '.'  The
>> usual meaning of '\\' (outside of this specific function) is "root on
>> the current drive" but that can't sensibly be appended to any path.
>> 
>>> The behaviour of join came up for me when I tried to use the os.path
>>> functions to create a path that could only ever be used as a directory
>>> and never a file.  The only way that I found to designate a path as a
>>> directory path was to add '\\' at the end.  But this doesn't work in
>>> using os.path becaause the other os.path functions just strip it off and
>>> turn the directories back into files.
>> 
>> Nothing about the name can turn a directory into a file (or vice versa).
>> If c:\x\y is a file, calling it c:\x\y\ won't change that, but it might
>> give you an error when you try to access it.  That may be what you want.
>> If so, appending '.' is likely to be more portable.
>
> That is true if you know for sure how your path will be used.
>
> But if you don't, there is a world of difference between passing the
> paths 'name' and 'name\\' on for others to use. And in this situation it
> doesn't help when os.path functions strip the directory separator off.

As it should.  Relying on a trailing \ having the right effect is
brittle to say the least.

> This situation resulted in a bug that was surprisingly hard to track
> down because it created hidden files instead of directories as
> intended.

If so, the bug is not in os.path.join and trying to fix it by insisting
that a path have trailing \ may well just stacking up more problems for
later.

> After finding and correcting the '\\' that had been stripped off, the
> desired directories couldn't then be creaated on the target because
> hidden files were present with these names.

As I said, that's a dodgy thing to rely on.  It may be that you can't
fix the bug any other way (some aspect of the overall design may be
broken), but I would urge you to try.

There is well-known (*nix) software that relies on a/b/c/ meaning
something different to a/b/c but I don't know anyone who thinks this is
a good idea.  It causes no end of confusion.

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


Re: Behaviour of os.path.join

2020-05-27 Thread Ben Bacarisse
BlindAnagram  writes:

> The issue that I raised here was whether the behaviour of os.path.join()
> in treating the Windows directory separator '\\' as an absolute path
> should be considered a bug.

You think it should be considered to be a relative path?  The only
meaning that would give you want you wanted from

  os.path.join(, '\\')

would be to treat it as being relative to the drive and to the
directory.  In other words you want '\\' to be a synonym for '.'  The
usual meaning of '\\' (outside of this specific function) is "root on
the current drive" but that can't sensibly be appended to any path.

> The behaviour of join came up for me when I tried to use the os.path
> functions to create a path that could only ever be used as a directory
> and never a file.  The only way that I found to designate a path as a
> directory path was to add '\\' at the end.  But this doesn't work in
> using os.path becaause the other os.path functions just strip it off and
> turn the directories back into files.

Nothing about the name can turn a directory into a file (or vice versa).
If c:\x\y is a file, calling it c:\x\y\ won't change that, but it might
give you an error when you try to access it.  That may be what you want.
If so, appending '.' is likely to be more portable.

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


Re: Behaviour of os.path.join

2020-05-26 Thread Ben Bacarisse
BlindAnagram  writes:

> I came across an issue that I am wondering whether I should report as an
> issue.  If I have a directory, say:
>
>   base='C:\\Documents'
>
> and I use os.path.join() as follows:
>
>   join(base, '..\\..\\', 'build', '')

It rather defeats the purpose of os.sep if you include it in a part of
the path.  What you mean is better expressed as

  join(base, '..', '..', 'build', '')

(and base includes it too, but I can't suggest an alternative because I
don't know your intent is far as defaults go.)


> The documentation says that an absolute path in the parameter list for
> join will discard all previous parameters but '\\' is not an absoute
> path!

I think it is.  The picture is messy on Windows (because of the drive
letter) but absolute paths are usually taken to be those that start with
a path separator.

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


Re: ÿ in Unicode

2020-03-07 Thread Ben Bacarisse
moi  writes:

> Le samedi 7 mars 2020 16:41:10 UTC+1, R.Wieser a écrit :
>> Moi,
>> 
>> > Fortunately, UTF-8 has not been created the Python devs.
>> 
>> And there we go again, making vague statements/accusations - without 
>> /anything/ to back it up ofcourse
>> 
>> Kiddo, you have posted a couple of messages now, but have said exactly 
>> nothing.   Are you sure you do not want to go into politics ?
>> 
> The day, when this language will stop to interpret a byte
> as being a Latin-1 (ISO-8859-1) character, this language will
> start to work properly.

>>> "ÿ".encode('iso-8859-1')
b'\xff'

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


Re: ÿ in Unicode

2020-03-06 Thread Ben Bacarisse
moi  writes:

> Le jeudi 5 mars 2020 13:20:38 UTC+1, Ben Bacarisse a ÄCcrit :
>> moi  writes:
>>
>> >>>> 'Ä¿'.encode('utf-8')
>> > b'\xc3\xbf'
>> >>>> 'Ä¿'.encode('utf-16-le')
>> > b'\xff\x00'
>> >>>> 'Ä¿'.encode('utf-32-le')
>> > b'\xff\x00\x00\x00'
>>
>
>> That all looks as expected.
> Yes
>
>>Is there something about the output that puzzles you?
> No
>
>>Did you have a question?
> No, only a comment
>
> This buggy language is very amusing.

Whilst I am happy that you are entertained by Python, the ability to encode 
strings in various transfer formats does not strike me as being particularly 
amusing.  But there's little enough happiness in the world, so take it where 
you can!

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


Re: ÿ in Unicode

2020-03-06 Thread Ben Bacarisse
moi  writes:

> Le jeudi 5 mars 2020 13:20:38 UTC+1, Ben Bacarisse a écrit :
>> moi  writes:
>>
>> >>>> 'ÿ'.encode('utf-8')
>> > b'\xc3\xbf'
>> >>>> 'ÿ'.encode('utf-16-le')
>> > b'\xff\x00'
>> >>>> 'ÿ'.encode('utf-32-le')
>> > b'\xff\x00\x00\x00'
>>
>
>> That all looks as expected.
> Yes
>
>>Is there something about the output that puzzles you?
> No
>
>>Did you have a question?
> No, only a comment
>
> This buggy language is very amusing.

Whilst I am happy that you are entertained by Python, the ability to encode 
strings in various transfer formats does not strike me as being particularly 
amusing.  But there's little enough happiness in the world, so take it where 
you can!

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


Re: ÿ in Unicode

2020-03-06 Thread Ben Bacarisse
moi  writes:

> Le jeudi 5 mars 2020 13:20:38 UTC+1, Ben Bacarisse a écrit :
>> moi  writes:
>> 
>> >>>> 'ÿ'.encode('utf-8')
>> > b'\xc3\xbf'
>> >>>> 'ÿ'.encode('utf-16-le')
>> > b'\xff\x00'
>> >>>> 'ÿ'.encode('utf-32-le')
>> > b'\xff\x00\x00\x00'
>> 
>
>> That all looks as expected.
> Yes
>
>>Is there something about the output that puzzles you?
> No
>
>>Did you have a question?
> No, only a comment
>
> This buggy language is very amusing.

Whilst I am happy that you are entertained by Python, the ability to
encode strings in various transfer formats does not strike me as being
particularly amusing.  But there's little enough happiness in the world,
so take it where you can!

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


Re: ÿ in Unicode

2020-03-05 Thread Ben Bacarisse
moi  writes:

 'ÿ'.encode('utf-8')
> b'\xc3\xbf'
 'ÿ'.encode('utf-16-le')
> b'\xff\x00'
 'ÿ'.encode('utf-32-le')
> b'\xff\x00\x00\x00'

That all looks as expected.  Is there something about the output that
puzzles you?  Did you have a question?

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


Re: Extract all words between two keywords in .txt file (Python)

2019-12-12 Thread Ben Bacarisse
A S  writes:

> On Thursday, 12 December 2019 02:28:09 UTC+8, Ben Bacarisse  wrote:
>> A S  writes:
>> 
>> > I would like to extract all words within specific keywords in a .txt
>> > file. For the keywords, there is a starting keyword of "PROC SQL;" (I
>> > need this to be case insensitive) and the ending keyword could be
>> > either "RUN;", "quit;" or "QUIT;". This is my sample .txt file.
>> >
>> > Thus far, this is my code:
>> >
>> > with open('lan sample text file1.txt') as file:
>> > text = file.read()
>> > regex = re.compile(r'(PROC SQL;|proc sql;(.*?)RUN;|quit;|QUIT;)')
>> > k = regex.findall(text)
>> > print(k)
>> 
>> Try
>> 
>>   re.compile(r'(?si)(PROC SQL;.*(?:QUIT|RUN);)')
 
>
> Hey Ben, this works for my sample .txt file! Thanks:) but it wont
> work, if I have other multiple text files to parse through that, are
> similar but have some variations, strangely enough.

No one can help without details.  Maybe need the non-greedy .*? rather
than the .* I put in there.  That was not a deliberate change.

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


Re: Extract all words between two keywords in .txt file (Python)

2019-12-11 Thread Ben Bacarisse
A S  writes:

> I would like to extract all words within specific keywords in a .txt
> file. For the keywords, there is a starting keyword of "PROC SQL;" (I
> need this to be case insensitive) and the ending keyword could be
> either "RUN;", "quit;" or "QUIT;". This is my sample .txt file.
>
> Thus far, this is my code:
>
> with open('lan sample text file1.txt') as file:
> text = file.read()
> regex = re.compile(r'(PROC SQL;|proc sql;(.*?)RUN;|quit;|QUIT;)')
> k = regex.findall(text)
> print(k)

Try

  re.compile(r'(?si)(PROC SQL;.*(?:QUIT|RUN);)')

Read up one what (?si) means and what (?:...) means..  You can do the
same by passing flags to the compile method.

> Output:
>
> [('quit;', ''), ('quit;', ''), ('PROC SQL;', '')]

Your main issue is that | binds weakly.  Your whole pattern tries to
match any one of just four short sub-patterns:

PROC SQL;
proc sql;(.*?)RUN;
quit;
QUIT;

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


Re: How to convert the following IDL program lines to equivalent Python program lines?

2019-11-28 Thread Ben Bacarisse
Madhavan Bomidi  writes:

> I have the following IDL program lines. I want to write equivalent
> Python program lines. Can anyone suggest me equivalent Pythons program
> lines?
>
> # --- 1 --- #
> How to handle the format in IDL to Python?
>
> IDL program line:
>
> print,'Column ',J,' of product matrix A*AINV:',format='(1X,A7,I3,A27)'
>
>
> Python program line written by me:
>
> print('Column '+str(j)+' of product matrix A*AINV:')

You could just use

  print('Column', j, 'of product matrix A*AINV:')

but if you need to copy the I3 format:

  print('Column {0:3} of product matrix A*AINV:'.format(j))

I don't know what the 1X format does.  The A7 and A27 formats just seem
to involve the programmer counting the strings.  Very odd.

> #---2  #
> How the JMP can be transformed in Python?
>
> IDL program lines:
>
>   FOR K=1,M DO BEGIN
> FOR I=1,M DO BEGIN
>   IF I NE K THEN BEGIN
> IF WK(K-1,K-1) EQ 0 THEN BEGIN
>   L=1
> JMP:  IF WK(L-1,K-1) EQ 0 THEN BEGIN
> L=L+1
> GOTO, JMP
>   ENDIF
>   FOR J=K,2*M DO BEGIN
> WK(K-1,J-1)=WK(K-1,J-1)+WK(L-1,J-1)
>   ENDFOR
> ENDIF
> U=-WK(I-1,K-1)/WK(K-1,K-1)
> FOR J=K+1,2*M DO BEGIN
>   WK(I-1,J-1)=WK(I-1,J-1)+U*WK(K-1,J-1)
> ENDFOR
>   ENDIF
> ENDFOR
>   ENDFOR
>
> JMP: RETURN

This is very odd.  What does it mean when a label is duplicated in IDL?
If the second one were not there, this:

  JMP:  IF WK(L-1,K-1) EQ 0 THEN BEGIN
  L=L+1
  GOTO, JMP
ENDIF

would just be a while loop:

while WK[L-1,K-1] == 0:
  L=L+1



By the way, all those -1s suggest that the IDL was itself a translation
from a language with 1-based array indexing.  All that might be able to
be tidied up.

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


Re: join and split with empty delimiter

2019-07-18 Thread Ben Bacarisse
Danilo Coccia  writes:

> Il 18/07/2019 12:27, Ben Bacarisse ha scritto:
>> Irv Kalb  writes:
>> 
>>> I have always thought that split and join are opposite functions.  For
>>> example, you can use a comma as a delimiter:
>>>
>>>>>> myList = ['a', 'b', 'c', 'd', 'e']
>>>>>> myString = ','.join(myList)
>>>>>> print(myString)
>>> a,b,c,d,e
>>>
>>>>>> myList = myString.split(',')
>>>>>> print(myList)
>>> ['a', 'b', 'c', 'd', 'e']
>>>
>>> Works great.
>> 
>> Note that join and split do not always recover the same list:
>> 
>>>>> ','.join(['a', 'b,c', 'd']).split(',')
>> ['a', 'b', 'c', 'd']
>> 
>> You don't even have to have the delimiter in one of the strings:
>> 
>>>>> '//'.join(['a', 'b/', 'c']).split('//')
>> ['a', 'b', '/c']
>> 
>>> But i've found a case where they don't work that way.  If
>>> I join the list with the empty string as the delimiter:
>>>
>>>>>> myList = ['a', 'b', 'c', 'd']
>>>>>> myString = ''.join(myList)
>>>>>> print(myString)
>>> abcd
>>>
>>> That works great.  But attempting to split using the empty string
>>> generates an error:
>>>
>>>>>> myString.split('')
>>> Traceback (most recent call last):
>>>   File "", line 1, in 
>>> myString.split('')
>>> ValueError: empty separator
>>>
>>> I know that this can be accomplished using the list function:
>>>
>>>>>> myString = list(myString)
>>>>>> print(myString)
>>> ['a', 'b', 'c', 'd']
>>>
>>> But my question is:  Is there any good reason why the split function
>>> should give an "empty separator" error?  I think the meaning of trying
>>> to split a string into a list using the empty string as a delimiter is
>>> unambiguous - it should just create a list of single characters
>>> strings like the list function does here.
>> 
>> One reason might be that str.split('') is not unambiguous.  For example,
>> there's a case to be made that there is a '' delimiter at the start and
>> the end of the string as well as between letters.  '' is a very special
>> delimiter because every string that gets joined using it includes it!
>> It's a wild version of ','.join(['a', 'b,c', 'd']).split(',').
>> 
>> Of course str.split('') could be defined to work the way you expect, but
>> it's possible that the error is there to prompt the programmer to be
>> more explicit.
>
> It is even more ambiguous if you consider that any string starts with an
> infinite number of empty strings, followed by a character, followed by
> an infinite number of empty strings, followed by ...
> The result wouldn't fit on screen, or in memory for that!

Right, but that can be finessed by saying that two delimiters can't
overlap, which is the usual rule.  A reasonable interpretation of "not
overlapping" might well exclude having more the one delimiter in the
same place.

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


Re: join and split with empty delimiter

2019-07-18 Thread Ben Bacarisse
Irv Kalb  writes:

> I have always thought that split and join are opposite functions.  For
> example, you can use a comma as a delimiter:
>
 myList = ['a', 'b', 'c', 'd', 'e']
 myString = ','.join(myList)
 print(myString)
> a,b,c,d,e
>
 myList = myString.split(',')
 print(myList)
> ['a', 'b', 'c', 'd', 'e']
>
> Works great.

Note that join and split do not always recover the same list:

>>> ','.join(['a', 'b,c', 'd']).split(',')
['a', 'b', 'c', 'd']

You don't even have to have the delimiter in one of the strings:

>>> '//'.join(['a', 'b/', 'c']).split('//')
['a', 'b', '/c']

> But i've found a case where they don't work that way.  If
> I join the list with the empty string as the delimiter:
>
 myList = ['a', 'b', 'c', 'd']
 myString = ''.join(myList)
 print(myString)
> abcd
>
> That works great.  But attempting to split using the empty string
> generates an error:
>
 myString.split('')
> Traceback (most recent call last):
>   File "", line 1, in 
> myString.split('')
> ValueError: empty separator
>
> I know that this can be accomplished using the list function:
>
 myString = list(myString)
 print(myString)
> ['a', 'b', 'c', 'd']
>
> But my question is:  Is there any good reason why the split function
> should give an "empty separator" error?  I think the meaning of trying
> to split a string into a list using the empty string as a delimiter is
> unambiguous - it should just create a list of single characters
> strings like the list function does here.

One reason might be that str.split('') is not unambiguous.  For example,
there's a case to be made that there is a '' delimiter at the start and
the end of the string as well as between letters.  '' is a very special
delimiter because every string that gets joined using it includes it!
It's a wild version of ','.join(['a', 'b,c', 'd']).split(',').

Of course str.split('') could be defined to work the way you expect, but
it's possible that the error is there to prompt the programmer to be
more explicit.

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


Re: repr = expression representation?

2019-05-17 Thread Ben Bacarisse
Christian Gollwitzer  writes:

> Am 17.05.19 um 06:13 schrieb Stefan Ram:   However, look at this
>>
>> |>>> print( str( print ))
>> |
>>
>> |>>> print( repr( print ))
>> |
>>
>>. While it is nice that »str( print )« gives some useful
>>information, I would expect »repr( print )« to give
>>»print« - 
>
> This is impossible. Python does not use "call by name", so a function
> cannot know how the argument is called in the upper stack
> level. Consider:
>
> Apfelkiste:inotes chris$ python3
> Python 3.6.1 |Anaconda 4.4.0 (x86_64)| (default, May 11 2017, 13:04:09)
> [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
 blafasel = print
 print(repr(blafasel))
> 


I don't think that renaming is important to SR.  The result should be,
in his view, a string representing the /value/ of the argument to repr,
so repr(print) and replr(blafasel) could both return the same (as they
indeed do) thing and I think he'd be happy.

> You'll have to accept that not all Python objects can be represented
> as literals.

I don't think SR minds if the result is not a literal.  I think the hope
was simply that eval(repr(E)) === E for any expression E.  You could, in
a very limited way, fudge it like this:

def myrepr(e):
if isinstance(e, types.BuiltinFunctionType):
return e.__name__
return repr(e)

The trouble is that print does not always mean print because that
identifier can be rebound.  Python could try to provide some /other/
name for every object, one that can't be rebound (something like an
environment + string lookup) but it's probably not worth it.


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


Re: Testing the data type of a value

2019-05-12 Thread Ben Bacarisse
binoythomas1...@gmail.com writes:

> When I run the following code, I get the following output:
 print(type(5))
> class 'int'
>
> Next, I try to compare the data-type of 5 with the earlier output, I
> get no output:
 if type(5) == "":
> print("Integer")
>
> Why isn't this working? Advance thanks for your time.

See if this helps...

>>> type(5)

>>> type(type(5))

>>> type("")


so you are comparing two things with different types.  An analogous
situation would be to

>>> print(5)
5

and then to try to compare 5 with the earlier output by writing

  if 5 == "5": ...

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


Re: Help? How do i solve this problem with Python List Concept

2019-05-11 Thread Ben Bacarisse
Donald Tripdarlinq  writes:

> In the traditional Yoruba tribal Set-Up in Nigeria,West Africa the
> tradition of inheritance is very important. Now, The relative position
> of a child in the family counts when the issue of inheritance is
> considered.
>
> Question: Now a farmer with 10 children died without leaving a will
> and the Family "Ebi"(Which consist of the extended family) decided
> that the property would be in proportion of their respective age. The
> Children were born with 3 years intervals except the second to last
> and the last born with the interval of 2 and 4 years respectively. Use
> the concept of list to write a simple python program to generate the
> individual children inheritance if the man left N230,000 Before his
> death

You need a little more than that.  If the inheritance is to be in
proportion to the ages, you need to know at least one actual age, rather
than just the age gaps.  Maybe the exercise is to write a function that
takes the age of, say, the youngest child and then calculates the
inheritances?

Anyway, your starting point will be to work through an example on paper
so you are clear about what the calculations are.

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


Re: Is this a "gotcha" in Python?

2019-04-20 Thread Ben Bacarisse
Gilmeh Serda  writes:

> On Fri, 19 Apr 2019 21:01:05 +, Stefan Ram wrote:
>
>>   Has this ever been a problem for someone?
>
> Only for programmers who come here from other languages and expect Python 
> to behave in the same manner as their favorite language, so they try and 
> argue that things from other languages should be implemented into Python 
> because they think it is a good idea, when it usually isn't. Python's 
> success proves that.

Depends.  If their favourite language was Fortran, the posted code would
be unsurprising.  (There would, of course, be loads of /other/ things
that would be potential "gotcha"s.)

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


Re: Function to determine list max without itertools

2019-04-19 Thread Ben Bacarisse
Sayth Renshaw  writes:

>> Now, what happens when the code is tested with various (different) sets 
>> of test-data?
>> (remember the last question from my previous msg!?)
>> 
> It fails on any list entry that isn't a float or an int, giving a TypeError.
>
>> Once you are happy with the various test-runs, do you have any ideas for 
>> making the code more efficient?
>> -- 
>> Regards =dn
>
> Efficient No, but resistant to error I can buy using try except to
> pass through TypeErrors.
>
> def max_try(listarg):
> myMax = listarg[0]
> try:
> for item in listarg:
> if item > myMax:
> myMax = item
> except TypeError:
> print(f'Only numbers are supported, this entry "{item}" was not')
> pass
>
> return myMax
>
> Thanks.

'pass' does not do what you think!  To re-raise the exception, use
'raise'.  'pass' is a null statement that does nothing.

But catching an exception just to print a message from a utility
function like this is not really a good idea.  It would be annoying to
many used of this function whilst adding little value over and above
what the traceback will show anyway.

There is another error case where you /could/ add a little value by
catching it in your function and raising a more appropriate exception.
What test cases have you used so far?

> PS Since I am going through the list fully the only optimisation I can
> think of a generator to feed it seems sort of redundant. Unless of
> course it was a list of 10,000 numbers then maybe its useful.

I'm not sure what was meant here.  I can think of one micro-optimisation
but I'd want to test to see if really makes and difference.

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


Re: Design a function that finds all positive numbers

2019-04-09 Thread Ben Bacarisse
r...@zedat.fu-berlin.de (Stefan Ram) writes:

> Ben Bacarisse  writes:
>>Ranjith Bantu  writes:
>>>can I solve any problems like this by learning python?
>>You need to learn how to solve problems as well as learning Python --
>
>   I do not separate "solving the problem" from "using Python",
>   because the approach to solve the problem in another
>   language would be different (think of Haskell).

There's a lot here.  First, I didn't separate them.  You have to do both
together, and both need to be learned.  Second, learning how to solve
problems is a universal skill that is needed no matter what languages
you use.  You may come up with different solutions in different
languages, but problem solving skills will be needed no matter what.
Third, I don't think the solutions will always be so significantly
different in different languages.  This partly depends on the level at
which one views algorithms, and will depend on what one considers to be
significantly different so it's a bit vague.


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


Re: Design a function that finds all positive numbers

2019-04-09 Thread Ben Bacarisse
Ranjith Bantu  writes:

> A numeric array of length 'N' is given. you need to design a function
> that finds all positive numbers in the array that have their opposites
> in it swell. give the approach for solving the optimal average or best
> case performance. answer will be your obsolute.
> Array: -7,4,-3, 2, 2, -8, -2, 3, 3, 7, -2, 3, -2
> sorted: -2, -2, -2 ,2 ,2, -3, 3, 3, 4, -7, 7, -8?
>
> can I solve any problems like this by learning python?

You need to learn how to solve problems as well as learning Python --
they go hand in hand -- but Python is a good language to get started
with.

> if anybody
> knows this answer or any mistakes in this question, please explain to
> me in detail?

That would require quite a long essay!  As to the question, it's a bit
odd to talk of opposites, but it's not ambiguous.  More problematic is
what to do with duplicates.  The question should be worded so that it's
either clear what is wanted, or so that it is clear that you should
decide what to do.

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


Re: New rules for scope in a function?

2019-02-18 Thread Ben Bacarisse
"Steve"  writes:

> OK, I wrote:
>
> x = "A"
> print("x = " + x)
>
> def f(y):
> print("x= " + x + "  y= "+ y)
> 
> f(x)
>
> and it worked, inspite of what I was seeing in my own program.  
> How quick I am to blame Python. (:
> When I isolate my function that stumped me, I will post it.

This small variation might point the way.  If you can explain it, you'll
be most of the way there.

x = "A"
print("x = " + x)

def f(y):
x = "B"
print("In f, x = " + x + "  y = "+ y)

f(x)
print("x = " + x)



The material I cut did include the explanation so go back and read the
message you replied to here if you don't follow.

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


Re: The sum of ten numbers inserted from the user

2019-02-07 Thread Ben Bacarisse
Grant Edwards  writes:

> On 2019-02-07, Ben Bacarisse  wrote:
>> Ian Clark  writes:
>>
>>> This is my whack at it, I can't wait to hear about it being the wrong big o
>>> notation!
>>>
>>> numbers=[]
>>>
>>> while len(numbers) < 10:
>>> try:
>>> chip = int(input('please enter an integer: '))
>>> except ValueError:
>>> print('that is not a number, try again')
>>> else:
>>> numbers.append(chip)
>>>
>>> print(sum(numbers))
>>
>> Why would you not keep a running total, rather than list of the numbers?
>> I've not been following assiduously, so maybe I missed some other
>> requirement...
>
> Because you think it likely that tomorrow the marketing people are
> going to say "oh, and we want to know the min, max, mode, median,
> standard deviation, and count of odd vs. even.
>
> OTOH, they may instead say, "Oh, it's not 10 numbers, it's 10 million
> numbers."

Sure.  I can think of reasons for all sorts of designs.  Has there been
any hint?  It looks like a beginners' exercise with little extra to go
on.

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


Re: The sum of ten numbers inserted from the user

2019-02-07 Thread Ben Bacarisse
Bart  writes:

> On 07/02/2019 20:45, Ben Bacarisse wrote:
>> Ian Clark  writes:
>>
>>> This is my whack at it, I can't wait to hear about it being the wrong big o
>>> notation!
>>>
>>> numbers=[]
>>>
>>> while len(numbers) < 10:
>>>  try:
>>>  chip = int(input('please enter an integer: '))
>>>  except ValueError:
>>>  print('that is not a number, try again')
>>>  else:
>>>  numbers.append(chip)
>>>
>>> print(sum(numbers))
>>
>> Why would you not keep a running total, rather than list of the numbers?
>> I've not been following assiduously, so maybe I missed some other
>> requirement...
>
> Because it separates the two tasks: (A) capture N values; (B) perform
> some operation on those values, in this case summing (and taking
> advantage here of the built-in sum()).

Sure.  Did I miss some hint that this program might need to be more
flexible like that?  It looks like a beginners' exercise.

If the purpose is to be flexible, why is an array the right option rather
than, say, accumulating a value over an iterable?  You need some idea of
the future direction or what the exercise is intended to reinforce.


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


Re: The sum of ten numbers inserted from the user

2019-02-07 Thread Ben Bacarisse
Ian Clark  writes:

> This is my whack at it, I can't wait to hear about it being the wrong big o
> notation!
>
> numbers=[]
>
> while len(numbers) < 10:
> try:
> chip = int(input('please enter an integer: '))
> except ValueError:
> print('that is not a number, try again')
> else:
> numbers.append(chip)
>
> print(sum(numbers))

Why would you not keep a running total, rather than list of the numbers?
I've not been following assiduously, so maybe I missed some other
requirement...


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


Re: Bringing Order to programming

2019-01-31 Thread Ben Bacarisse
r...@zedat.fu-berlin.de (Stefan Ram) writes:

> source = \
> 'Python is an easy to learn, powerful programming language. It has' + \
> ' efficient high-level data structures and a simple but effective' + \
> ' approach to object-oriented programming. Python's elegant syntax' + \

You have an unexscped ' in there.

> ' and dynamic typing, together with its interpreted nature, make it' + \
> ' an ideal language for scripting and rapid application development' + \
> ' in many areas on most platforms. ';


>   transcript
>
> a 0.0680 s,  a 1.2040 s,  a 9.5823 s,  a 81.9688 s,

My times are very nearly linear:

a 0.0280 s,  a 0.2931 s,  a 2.9006 s,  a 29.4318 s,

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


Re: graded randomness

2018-12-28 Thread Ben Bacarisse
Abdur-Rahmaan Janhangeer  writes:

> let us say that i have a box of 5 balls,
>
> green balls - 2 with probability 2/5
> red balls 2 - with probability 2/5
> blue balls 1 - with probability 1/5
>
> how to program the selection so that the random choices reflect the
> probabilities?

>>> import random
>>> random.choice(["green", "green", "red", "red", "blue"])

Not a method that scales particularly well, but there's almost no
context to evaluate solutions.

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


Re: random choice from dictionary

2018-12-23 Thread Ben Bacarisse
"Avi Gross"  writes:

> The following is a function that iterates over the dictionary one key at a
> time and when it reaches a random one, it returns the key without further
> evaluation. On the average, it takes N/2 iterations for N keys. Asking to
> make a list(data) may be efficient in terms of time and indexing is fast but
> space is used maximally unless it just points to existing storage.
>
> Here is one way to do the function. Some might use an emum instead.
>
> def rand_key(data):
> """Get a random key from a dict without using all of memory."""
> import random
> randy = random.randrange(len(data))
> this = 0
> for key in data:
> if (this == randy):
> return(key)
> this += 1

There is beautiful variation on this that can select k random keys:

def sample_keys(data, k = 1):
"""Return k random keys from a dict."""
import random
items = len(data)
keys = []
for key in data:
r = random.random()
if r < k/items:
keys.append(key)
k -= 1
items -= 1
return keys

And there is a variation on /that/ will use fewer random numbers --
essentially picking a number of "skip" distances as you pick one.  But
it's late, and I need to get ready to eat lots...


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


Re: multiple JSON documents in one file, change proposal

2018-12-01 Thread Ben Bacarisse
Marko Rauhamaa  writes:

> Chris Angelico :
>
>> On Sat, Dec 1, 2018 at 10:16 PM Marko Rauhamaa  wrote:
>>> and the framing format is HTTP. I will need to type something like this:
>>>
>>>POST / HTTP/1.1^M
>>>Host: localhost^M
>>>Content-type: application/json^M
>>>Content-length: 54^M
>>>^M
>>>{
>>>"msgtype": "echo-req",
>>>"opid": 3487547843
>>>}
>>>
>>> That's almost impossible to type without a syntax error.
>>
>> 1) Set your Enter key to send CR-LF, at least for this operation.
>> That's half your problem solved.
>
> That can be much harder than typing ctrl-SPC. It *is* supported by
> netcat, for example, but then you have to carefully recompute the
> content-length field.
>
>> 2) Send the request like this:
>>
>> POST / HTTP/1.0
>> Content-type: application/json
>>
>> {"msgtype": "echo-req", "opid": 3487547843}
>>
>> Then shut down your end of the connection, probably with Ctrl-D. I'm
>> fairly sure I can type that without bugs, and any compliant HTTP
>> server should be fine with it.
>
> If I terminated the input, I wouldn't need any framing. The point is to
> carry a number of JSON messages/documents over a single bytestream or in
> a single file. That means the HTTP content-length would be mandatory.

I haven't been following the details of the thread, but I wonder if a
multi-part form-data POST would be useful.  Way more complex than a
simple separator, of course, but more "standard" (for some rather vague
meaning of the term).

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


Re: [Tutor] SyntaxError: can't assign to literal while using ""blkid -o export %s | grep 'TYPE' | cut -d"=" -f3" % (fs)" using subprocess module in Python

2018-11-07 Thread Ben Bacarisse
srinivasan  writes:

> Even after changing as per the below
> "blkid -o export %s | grep 'TYPE' | cut -d'=' -f3"
> or:
> 'blkid -o export %s | grep "TYPE" | cut -d"=" -f3'
> or:
> "blkid -o export %s | grep \"TYPE\" | cut -d\"=\" -f3"
>
> Still my output is:
> */dev/mmcblk1p1: LABEL="efi" UUID="1084-AA42" TYPE="vfat"*
>
> My expected output should be only:
> *vfat*
>
> Could you guys please do the needful?

Why not

  blkid %s -o value --match-tag TYPE

?  Or, better still,

  lsblk %s -n -o FSTYPE

It's not easy to answer your question about fixing the line you have,
because the output you are getting it not consistent with what you are
showing.  (And I can't find the original post that presumably has Python
code I could run myself.)

The format I get with -o export is:

DEVNAME=/dev/sda1
UUID=2726bf5f-2655-4986-815d-e4532374f218
TYPE=ext3
PARTUUID=000453d3-01

for which

  "blkid %s -o export | grep TYPE | cut -c6-"

would work.  Alternatively I get the result you want from

  "blkid %s -o export | grep TYPE | cut -d= -f2"

Note that "TYPE" and "=" don't really need to be quoted at all.

Someone suggested sed, and that too can be used like this:

  blkid %s -o export | sed -ne '/TYPE=/s///p'

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


Re: snakify issues

2018-10-13 Thread Ben Bacarisse
bob gailer  writes:

> 5:50 AM Dec 8, 2016 a post was made to this list - subject "Snakify - 
> free introductory Python online course with exercises"
>
> Recently I was engaged by a student seeking help with some of the
> exercises. I found a number of issues at the snakify web site. Thus
> began a conversation between me and the Site Maintainer Here is the
> latest:
>
> On 9/28/2018 1:02 PM, Vitaly Pavlenko wrote:
>> Hi Bob,
>>
>> Thanks for your email. I’d be very happy if you could describe what
>> sort of issues were you running into.
> I drafted a rather lengthy reply which I sent to you on October 1. I
> have not received any response.

I looked at the "landing page" and they clearly need a proof-reader.
It's intelligible, but the English is clunky.  In the body of the course
there's quite a lot of incorrect terminology.

But the material itself is so dull -- numbers, arithmetic, more numbers,
factorials, more arithmetic, numbers...  And when a string exercise came
up (capitalise a word) the hint was to use ord and chr.

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


Re: Writing bytes to stdout reverses the bytes

2018-08-19 Thread Ben Bacarisse
Grant Edwards  writes:

> On 2018-08-20, Steven D'Aprano  wrote:
>> On Mon, 20 Aug 2018 00:31:35 +, Steven D'Aprano wrote:
>>
>>> When I write bytes to stdout, why are they reversed?
>>
>> Answer: they aren't, use hexdump -C.
>
> One might think that dumping out bytes in the correct order ought to
> be the default format for hexdump.

It is if you run it as hd.

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


Re: coding style - where to declare variables

2018-07-23 Thread Ben Bacarisse
Mark Lawrence  writes:

> On 22/07/18 14:51, Abdur-Rahmaan Janhangeer wrote:
>> except local vars
>>
>> Abdur-Rahmaan Janhangeer
>> https://github.com/Abdur-rahmaanJ
>> Mauritius
>>
>
> Python doesn't have variables, it has names.

I think we should cut beginners (and probably everyone) some slack about
this.  I don't know if work is underway to purge the term from the
Python documentation, but until that is done people can be forgiven for
thinking that the term is acceptable.

For example, https://docs.python.org/3/tutorial/classes.html says

  "The global statement can be used to indicate that particular
  variables live in the global scope and should be rebound there; the
  nonlocal statement indicates that particular variables live in an
  enclosing scope and should be rebound there."

and https://www.python.org/dev/peps/pep-0526/ is titled "Syntax for
Variable Annotations".  It describes:

  "This PEP aims at adding syntax to Python for annotating the types of
  variables (including class variables and instance variables), instead
  of expressing them through comments"

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


Re: [OT] Bit twiddling homework

2018-07-20 Thread Ben Bacarisse
Brian Oney  writes:

> On Fri, 2018-07-20 at 06:37 +, Steven D'Aprano wrote:
>> On Fri, 20 Jul 2018 08:25:04 +0200, Brian Oney via Python-list wrote:
>> 
>> > PS: Can I twiddle bits in Python?
>> 
>> Yes.
>> 
>> These operators work on ints:
>> 
>>   bitwise AND:  &
>>   bitwise OR:   |
>>   bitwise XOR:  ^
>> 
> That's right I had forgotten about that.

There's also ~ for bitwise negation.  Rather than explain what this
means in a language with an unbounded integer type, you might like to
experiment, er, a bit.  (Excuse the pun.)

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


Re: variable scope in try ... EXCEPT block.

2018-07-12 Thread Ben Bacarisse
Just word on quoting...

codewiz...@gmail.com writes:

> On Thursday, July 12, 2018 at 5:45:52 AM UTC-4, Ben Bacarisse wrote:
>> 
>> [snip]

You cut everything I wrote.  What you left is what I quoted from the
Python documentation.  In fairness to the authors you should probably
have cut the attribution line and left the URL I posted.


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


Re: variable scope in try ... EXCEPT block.

2018-07-12 Thread Ben Bacarisse
aleiphoenix  writes:

> suppose following code running with Python-3.4.8 and Python-3.6.5
>
>
> # -*- coding: utf-8 -*-
>
>
> def hello():
> err = None
> print('0: {}'.format(locals()))
> try:
> b = 2
> print('1: {}'.format(locals()))
> raise ValueError()
> print('2: {}'.format(locals()))
> except ValueError as err:
> print('3: {}'.format(locals()))
> pass
> print('4: {}'.format(locals()))
> return '', err
>
>
> hello()
>
>
>
> got output:
>
> 0: {'err': None}
> 1: {'err': None, 'b': 2}
> 3: {'err': ValueError(), 'b': 2}
> 4: {'b': 2}
> Traceback (most recent call last):
>   File "err.py", line 19, in 
> hello()
>   File "err.py", line 16, in hello
> return '', err
> UnboundLocalError: local variable 'err' referenced before assignment
>
>
> But without this UnboundLocalError with Python-2.7.14
>
>
> My question is, does except ... as ... create a new scope from outer
> block, causing 'err' be hidden from outer scope? Is this intentional?

Yes, it's intentional, but it's not exactly a scope.  In

  https://docs.python.org/3/reference/compound_stmts.html#try

you will find:

  When an exception has been assigned using as target, it is cleared at
  the end of the except clause. This is as if

  except E as N:
  foo

  was translated to

  except E as N:
  try:
  foo
  finally:
  del N

  This means the exception must be assigned to a different name to be
  able to refer to it after the except clause.  Exceptions are cleared
  because with the traceback attached to them, they form a reference
  cycle with the stack frame, keeping all locals in that frame alive
  until the next garbage collection occurs.

This appears to be a change from Python 2.  That wording is not present
in

  https://docs.python.org/2/reference/compound_stmts.html#try

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


Re: Static variables [was Re: syntax difference]

2018-06-26 Thread Ben Bacarisse
  To: Bart
From: "Ben Bacarisse" 

  To: Bart
From: Ben Bacarisse 

Bart  writes:

> On 23/06/2018 23:25, Ben Bacarisse wrote:
>> Bart  writes:
>>
>>> On 23/06/2018 21:13, Chris Angelico wrote:
>>>> On Sat, Jun 23, 2018 at 10:41 PM, Bart  wrote:
>>>
>>>>> (At what point would that happen anyway; if you do this:
>>>
>>>> NONE of your examples are taking copies of the function. They all are
>>>> making REFERENCES to the same function. That is all.
>>>
>>> This is about your notion that invocations of the same function via
>>> different references, should maintain their own versions of the
>>> function's 'static' data.
>>>
>>> Since these references are created via the return g statement here:
>>>
>>>  def f():
>>>  def g():
>>>  
>>>  return g
>>>
>>> (say to create function references i and j like this:
>>>
>>>  i = f()
>>>  j = f()
>>> )
>>>
>>> I'm assuming that something special must be happening. Otherwise, how
>>> does f() know which reference it's being called via?
>>>
>>> What is different, what extra bit of information is provided when f()
>>> is invoked via i() or j()?
>>
>> f is not being invoked by either i() or j().  i = f() binds i to the
>> function returned by f.  That's a newly minted function.  In languages
>> like Python, executing def creates a function.
>
> Do you mean that if the same 'def' block is re-executed, it will
> create a different instance of the function? (Same byte-code, but a
> different set of everything else the function uses.)

Logically, yes.

> Wow. (Just think of all the times you write a function containing a
> neat bunch of local functions, every time it's called it has to create
> a new function instances for each of those functions, even if they are
> not used.)

I am surprised that this surprises you, and equally surprised that you seem to
think it's going to be in some way grossly inefficient.

--
Ben.

-+- BBBS/Li6 v4.10 Toy-3
 + Origin: Prism bbs (1:261/38)

--- BBBS/Li6 v4.10 Toy-3
 * Origin: Prism bbs (1:261/38)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Static variables [was Re: syntax difference]

2018-06-26 Thread Ben Bacarisse
  To: Bart
From: "Ben Bacarisse" 

  To: Bart
From: Ben Bacarisse 

Bart  writes:

> On 23/06/2018 21:13, Chris Angelico wrote:
>> On Sat, Jun 23, 2018 at 10:41 PM, Bart  wrote:
>
>>> (At what point would that happen anyway; if you do this:
>
>> NONE of your examples are taking copies of the function. They all are
>> making REFERENCES to the same function. That is all.
>
> This is about your notion that invocations of the same function via
> different references, should maintain their own versions of the
> function's 'static' data.
>
> Since these references are created via the return g statement here:
>
> def f():
> def g():
> 
> return g
>
> (say to create function references i and j like this:
>
> i = f()
> j = f()
> )
>
> I'm assuming that something special must be happening. Otherwise, how
> does f() know which reference it's being called via?
>
> What is different, what extra bit of information is provided when f()
> is invoked via i() or j()?

f is not being invoked by either i() or j().  i = f() binds i to the function
returned by f.  That's a newly minted function.  In languages like Python,
executing def creates a function.  In your example, i and j refer to different
functions.  If the function temporarily named g has "own" variables ("static"
in C), then each such function should have its own.  That was the point of the
example much further up.

The effect can simulated like this:

def make_counter():
def c():
c.x += 1
return c.x
c.x = 0
return c

i = make_counter()
j = make_counter()

print(i(), i(), j(), i())


--
Ben.

-+- BBBS/Li6 v4.10 Toy-3
 + Origin: Prism bbs (1:261/38)

--- BBBS/Li6 v4.10 Toy-3
 * Origin: Prism bbs (1:261/38)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: translating foreign data

2018-06-26 Thread Ben Bacarisse
  To: Steven D'Aprano
From: "Ben Bacarisse" 

  To: Steven D'Aprano
From: Ben Bacarisse 

Steven D'Aprano  writes:

> On Fri, 22 Jun 2018 11:14:59 +0100, Ben Bacarisse wrote:
>
>>>> The code page remark is curious.  Will some "code pages" have digits
>>>> that are not ASCII digits?
>>>
>>> Good question.  I have no idea.
>>
>> It's much more of an open question than I thought.
>
> Nah, Python already solves that for you:

My understanding was that the OP does not (reliably) know the encoding, though
that was a guess based on a turn of phrase.

Another guess is that the OP does not have Unicode data.  The term "code page"
hints at an 8-bit encoding or at least a pre-Unicode one.


--
Ben.

-+- BBBS/Li6 v4.10 Toy-3
 + Origin: Prism bbs (1:261/38)

--- BBBS/Li6 v4.10 Toy-3
 * Origin: Prism bbs (1:261/38)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Static variables [was Re: syntax difference]

2018-06-25 Thread Ben Bacarisse
  To: Bart
From: Ben Bacarisse 

Bart  writes:

> On 23/06/2018 23:25, Ben Bacarisse wrote:
>> Bart  writes:
>>
>>> On 23/06/2018 21:13, Chris Angelico wrote:
>>>> On Sat, Jun 23, 2018 at 10:41 PM, Bart  wrote:
>>>
>>>>> (At what point would that happen anyway; if you do this:
>>>
>>>> NONE of your examples are taking copies of the function. They all are
>>>> making REFERENCES to the same function. That is all.
>>>
>>> This is about your notion that invocations of the same function via
>>> different references, should maintain their own versions of the
>>> function's 'static' data.
>>>
>>> Since these references are created via the return g statement here:
>>>
>>>  def f():
>>>  def g():
>>>  
>>>  return g
>>>
>>> (say to create function references i and j like this:
>>>
>>>  i = f()
>>>  j = f()
>>> )
>>>
>>> I'm assuming that something special must be happening. Otherwise, how
>>> does f() know which reference it's being called via?
>>>
>>> What is different, what extra bit of information is provided when f()
>>> is invoked via i() or j()?
>>
>> f is not being invoked by either i() or j().  i = f() binds i to the
>> function returned by f.  That's a newly minted function.  In languages
>> like Python, executing def creates a function.
>
> Do you mean that if the same 'def' block is re-executed, it will
> create a different instance of the function? (Same byte-code, but a
> different set of everything else the function uses.)

Logically, yes.

> Wow. (Just think of all the times you write a function containing a
> neat bunch of local functions, every time it's called it has to create
> a new function instances for each of those functions, even if they are
> not used.)

I am surprised that this surprises you, and equally surprised that you seem to
think it's going to be in some way grossly inefficient.

--
Ben.

--- BBBS/Li6 v4.10 Toy-3
 * Origin: Prism bbs (1:261/38)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Static variables [was Re: syntax difference]

2018-06-25 Thread Ben Bacarisse
  To: Bart
From: Ben Bacarisse 

Bart  writes:

> On 23/06/2018 21:13, Chris Angelico wrote:
>> On Sat, Jun 23, 2018 at 10:41 PM, Bart  wrote:
>
>>> (At what point would that happen anyway; if you do this:
>
>> NONE of your examples are taking copies of the function. They all are
>> making REFERENCES to the same function. That is all.
>
> This is about your notion that invocations of the same function via
> different references, should maintain their own versions of the
> function's 'static' data.
>
> Since these references are created via the return g statement here:
>
> def f():
> def g():
> 
> return g
>
> (say to create function references i and j like this:
>
> i = f()
> j = f()
> )
>
> I'm assuming that something special must be happening. Otherwise, how
> does f() know which reference it's being called via?
>
> What is different, what extra bit of information is provided when f()
> is invoked via i() or j()?

f is not being invoked by either i() or j().  i = f() binds i to the function
returned by f.  That's a newly minted function.  In languages like Python,
executing def creates a function.  In your example, i and j refer to different
functions.  If the function temporarily named g has "own" variables ("static"
in C), then each such function should have its own.  That was the point of the
example much further up.

The effect can simulated like this:

def make_counter():
def c():
c.x += 1
return c.x
c.x = 0
return c

i = make_counter()
j = make_counter()

print(i(), i(), j(), i())


--
Ben.

--- BBBS/Li6 v4.10 Toy-3
 * Origin: Prism bbs (1:261/38)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: translating foreign data

2018-06-24 Thread Ben Bacarisse
  To: Steven D'Aprano
From: Ben Bacarisse 

Steven D'Aprano  writes:

> On Fri, 22 Jun 2018 11:14:59 +0100, Ben Bacarisse wrote:
>
>>>> The code page remark is curious.  Will some "code pages" have digits
>>>> that are not ASCII digits?
>>>
>>> Good question.  I have no idea.
>>
>> It's much more of an open question than I thought.
>
> Nah, Python already solves that for you:

My understanding was that the OP does not (reliably) know the encoding, though
that was a guess based on a turn of phrase.

Another guess is that the OP does not have Unicode data.  The term "code page"
hints at an 8-bit encoding or at least a pre-Unicode one.


--
Ben.

--- BBBS/Li6 v4.10 Toy-3
 * Origin: Prism bbs (1:261/38)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Static variables [was Re: syntax difference]

2018-06-23 Thread Ben Bacarisse
Bart  writes:

> On 23/06/2018 23:25, Ben Bacarisse wrote:
>> Bart  writes:
>>
>>> On 23/06/2018 21:13, Chris Angelico wrote:
>>>> On Sat, Jun 23, 2018 at 10:41 PM, Bart  wrote:
>>>
>>>>> (At what point would that happen anyway; if you do this:
>>>
>>>> NONE of your examples are taking copies of the function. They all are
>>>> making REFERENCES to the same function. That is all.
>>>
>>> This is about your notion that invocations of the same function via
>>> different references, should maintain their own versions of the
>>> function's 'static' data.
>>>
>>> Since these references are created via the return g statement here:
>>>
>>>  def f():
>>>  def g():
>>>  
>>>  return g
>>>
>>> (say to create function references i and j like this:
>>>
>>>  i = f()
>>>  j = f()
>>> )
>>>
>>> I'm assuming that something special must be happening. Otherwise, how
>>> does f() know which reference it's being called via?
>>>
>>> What is different, what extra bit of information is provided when f()
>>> is invoked via i() or j()?
>>
>> f is not being invoked by either i() or j().  i = f() binds i to the
>> function returned by f.  That's a newly minted function.  In languages
>> like Python, executing def creates a function.
>
> Do you mean that if the same 'def' block is re-executed, it will
> create a different instance of the function? (Same byte-code, but a
> different set of everything else the function uses.)

Logically, yes.

> Wow. (Just think of all the times you write a function containing a
> neat bunch of local functions, every time it's called it has to create
> a new function instances for each of those functions, even if they are
> not used.)

I am surprised that this surprises you, and equally surprised that you
seem to think it's going to be in some way grossly inefficient.

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


Re: Static variables [was Re: syntax difference]

2018-06-23 Thread Ben Bacarisse
Bart  writes:

> On 23/06/2018 21:13, Chris Angelico wrote:
>> On Sat, Jun 23, 2018 at 10:41 PM, Bart  wrote:
>
>>> (At what point would that happen anyway; if you do this:
>
>> NONE of your examples are taking copies of the function. They all are
>> making REFERENCES to the same function. That is all.
>
> This is about your notion that invocations of the same function via
> different references, should maintain their own versions of the
> function's 'static' data.
>
> Since these references are created via the return g statement here:
>
> def f():
> def g():
> 
> return g
>
> (say to create function references i and j like this:
>
> i = f()
> j = f()
> )
>
> I'm assuming that something special must be happening. Otherwise, how
> does f() know which reference it's being called via?
>
> What is different, what extra bit of information is provided when f()
> is invoked via i() or j()?

f is not being invoked by either i() or j().  i = f() binds i to the
function returned by f.  That's a newly minted function.  In languages
like Python, executing def creates a function.  In your example, i and j
refer to different functions.  If the function temporarily named g has
"own" variables ("static" in C), then each such function should have its
own.  That was the point of the example much further up.

The effect can simulated like this:

def make_counter():
def c():
c.x += 1
return c.x
c.x = 0
return c

i = make_counter()
j = make_counter()

print(i(), i(), j(), i())


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


Re: translating foreign data

2018-06-22 Thread Ben Bacarisse
Steven D'Aprano  writes:

> On Fri, 22 Jun 2018 11:14:59 +0100, Ben Bacarisse wrote:
>
>>>> The code page remark is curious.  Will some "code pages" have digits
>>>> that are not ASCII digits?
>>>
>>> Good question.  I have no idea.
>> 
>> It's much more of an open question than I thought.
>
> Nah, Python already solves that for you:

My understanding was that the OP does not (reliably) know the encoding,
though that was a guess based on a turn of phrase.

Another guess is that the OP does not have Unicode data.  The term "code
page" hints at an 8-bit encoding or at least a pre-Unicode one.


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


Re: translating foreign data

2018-06-22 Thread Ben Bacarisse
Ethan Furman  writes:

> On 06/21/2018 01:20 PM, Ben Bacarisse wrote:

>> You say in a followup that you don't need to worry about digit grouping
>> marks (like thousands separators) so I'm not sure what the problem is.
>> Can't you just replace ',' with '.' a proceed as if you had only one
>> representation?
>
> I could, and that would work right up until a third decimal separator
> was found.  I'd like to solve the problem just once if possible.

Ah, I see.  I took you to mean you knew this won't be an issue.

>> The code page remark is curious.  Will some "code pages" have digits
>> that are not ASCII digits?
>
> Good question.  I have no idea.

It's much more of an open question than I thought.  My only advice,
then, it to ignore problems that *might* arise.  Solve the problem you
face now and hope that you can extend it as needed.  It's good to check
if there is an well-known solution ready to use out of the box, but
since there really isn't, you might as well get something working now.

> I get the appropriate decoder/encoder
> based on the code page contained in the file, then decode to unicode
> and go from there.

It's rather off-topic but what does it mean for the code page to be
contained in the file?  Are you guessing the character encoding from the
rest of the file contents or is there some actual description of the
encoding present?

> ... I was hoping to map the code page to
> a locale that would properly translate the numbers for me,

> Worst case scenario is I manually create a map for each code page to
> decimal separator, but there's more than a few and I'd rather not if
> there is already a prebuilt solution out there.

That can't work in general, but you may be lucky with your particular
data set.  For example, files using one of the "Latin" encodings could
have numbers written using the UK convention (0.5) or the French
convention (0,5).  I do both depending on the audience.

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


Re: translating foreign data

2018-06-21 Thread Ben Bacarisse
Ethan Furman  writes:
 
> I need to translate numeric data in a string format into a binary
> format.  I know there are at least two different methods of
> representing parts less that 1, such as "10.5" and "10,5".  The data
> is encoded using code pages, and can vary depending on the file being
> read (so I can't rely on current locale settings).
>
> I'm sure this is a solved problem, but I'm not finding those
> solutions.  Any pointers?

You say "at least two" and give two but not knowing the others will hamper
anyone trying to help.  (I appreciate that you may not yet know if there
are to be any others.)

You say in a followup that you don't need to worry about digit grouping
marks (like thousands separators) so I'm not sure what the problem is.
Can't you just replace ',' with '.' a proceed as if you had only one
representation?

The code page remark is curious.  Will some "code pages" have digits
that are not ASCII digits?

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


Re: syntax difference

2018-06-18 Thread Ben Bacarisse
Bart  writes:

> On 18/06/2018 11:45, Chris Angelico wrote:
>> On Mon, Jun 18, 2018 at 8:33 PM, Bart  wrote:
>
>
>>> You're right in that neither task is that trivial.
>>>
>>> I can remove comments by writing a tokeniser which scans Python source and
>>> re-outputs tokens one at a time. Such a tokeniser normally ignores comments.
>>>
>>> But to remove type hints, a deeper understanding of the input is needed. I
>>> would need a parser rather than a tokeniser. So it is harder.
>>
>> They would actually both end up the same. To properly recognize
>> comments, you need to understand enough syntax to recognize them. To
>> properly recognize type hints, you need to understand enough syntax to
>> recognize them. And in both cases, you need to NOT discard important
>> information like consecutive whitespace.
>
> No. If syntax is defined on top of tokens, then at the token level,
> you don't need to know any syntax. The process that scans characters
> looking for the next token, will usually discard comments. Job done.

You don't even need to scan for tokens other than strings.  From what I
read in the documentation a simple scanner like this would do the trick:

  %option noyywrap
  %x sqstr dqstr sqtstr dqtstr
  %%
   
  \'  ECHO; BEGIN(sqstr);
  \"  ECHO; BEGIN(dqstr);
  \'\'\'  ECHO; BEGIN(dqtstr);
  \"\"\"  ECHO; BEGIN(dqtstr);
   
  \"   |
  \'   |
  \'\'\'  |
  \"\"\"  ECHO; BEGIN(INITIAL);
   
  \\\'   |
  \\\"   |
  .  ECHO;
   
  #.*
   
  %%
  int main(void) { yylex(); }

and it's only this long because there are four kinds of string.  Not
being a Python expert, there may be some corner case errors.  And really
there are comments that should not be removed such as #! on line 1 and
encoding declarations, but they would just need another line or two.

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


Re: syntax difference

2018-06-16 Thread Ben Bacarisse
Cameron Simpson  writes:

> ... In Python 3 we have "format strings", which let you write:
>
>  name = "Sharon"
>  age = 35
>  print(f"The person named {name|r} is {age} years old.")

You meant {name!r} I think there.

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


Re: Stefan's headers [was:Names and identifiers]

2018-06-10 Thread Ben Bacarisse
Jon Ribbens  writes:

> I'd suggest that since the processes he's purporting to disallow are
> entirely standard and automated and he knows full well they exist and
> that there is no mechanism by which they could be affected by his
> notice, the notice has little effect.

The Copyright notice is probably intended for human eyes.  IIRC his
posts don't show up on Google groups, for example, so there *is* a
mechanism by which *some* of the headers (it may be X-no-archive) do get
acted on.


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


Re: Sorting NaNs

2018-06-02 Thread Ben Bacarisse
Paul Rubin  writes:

> Steven D'Aprano  writes:
>> it too will mess up sorting in unpredictable ways. So don't do that.
>
> Hmm.  GHCi 7.4.2:
>
> Prelude> let x = 0.0 / 0.0
> Prelude> x
> NaN
> Prelude> x==x
> False
> Prelude> :m Data.List
> Prelude Data.List> sort [1,2,x,4,5]
> [1.0,2.0,4.0,5.0,NaN]

But

  Prelude Data.List> sort [1,x,2,4,5]
  [2.0,4.0,5.0,NaN,1.0]

and

  Prelude Data.List> sort [1,2,x,4,5,x]
  [NaN,1.0,2.0,4.0,5.0,NaN]

and

  Prelude Data.List> sort [1,2,x,4,5,x,1/0]
  [1.0,2.0,4.0,Infinity,NaN,5.0,NaN]

> Not sure what to make of this but at least sorting seems to give a
> predictable result.

I suspect it is predictable if you know the algorithm, but I doubt it's
specified nor easily guessable from "outside".

(GHCi, version 8.0.2 here)

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


Re: Pink Floyd: is there anybody in here?

2018-05-30 Thread Ben Bacarisse
Steven D'Aprano  writes:

> On Wed, 30 May 2018 21:53:05 +0100, Ben Bacarisse wrote:
>
>> Rob Gaddi  writes:
>> 
>>> On 05/30/2018 09:34 AM, Paul Rubin wrote:
>>>> I think Usenet posts are no longer getting forwarded to the mailing
>>>> list, but now I wonder if this is getting out at all, even to usenet.
>>>>
>>>> Does anyone see it?
>>>
>>> Can't speak for the mailing list, but this came out to Usenet just
>>> fine.
>> 
>> Snap.  The original and the reply.
>
> You shouldn't generalise about Usenet, as individual news servers can and 
> do drop messages. In this case, gmane seems to be dropping Paul Rubin's 
> posts.

Was I generalising?  I didn't intend to.  I only meant I saw both on
Usenet.

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


Re: Pink Floyd: is there anybody in here?

2018-05-30 Thread Ben Bacarisse
Rob Gaddi  writes:

> On 05/30/2018 09:34 AM, Paul Rubin wrote:
>> I think Usenet posts are no longer getting forwarded to the mailing
>> list, but now I wonder if this is getting out at all, even to usenet.
>>
>> Does anyone see it?
>
> Can't speak for the mailing list, but this came out to Usenet just
> fine.

Snap.  The original and the reply.

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


Re: List replication operator

2018-05-25 Thread Ben Bacarisse
Steven D'Aprano  writes:

> On Thu, 24 May 2018 16:05:32 -0700, Paul wrote:
>
>> How would one make a multi-dimensional list now, with truly-separate sub
>> lists?  Is there just no way to do it with the replication operator?
>
> Correct. Let's say you want to make a 1-D list with three items 
> initialised to zero. This works brilliantly:
>
> py> [0]*3
> [0, 0, 0]
>
> This seems like it ought to create a 3x3 2-D list:
>
> py> y = [[0]*3]*3
> py> y
> [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>
>
> but alas, it's a trap:
>
> py> y[0][0] = 1
> py> y
> [[1, 0, 0], [1, 0, 0], [1, 0, 0]]

Another way of looking at it would be in terms of evaluation rather than
copying.  [] evaluates to a new list object, so if there were an
alternate version of L * n (for the sake of argument L ** n) that
evaluated the list expression n times to make the new list you would
also get the behaviour you want.

You would also be able to use it in situations like this:

  import random
  [random.randint(1,10)]**6

to get (for example) [2, 4, 7, 1, 1, 8].

Of course, this is just what the [L for _ in range(n)] solution does,
but maybe the situation merits a shorthand?


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


Re: best way to remove leading zeros from a tuple like string

2018-05-20 Thread Ben Bacarisse
<pre>"Michael F. Stemper" <michael.stem...@gmail.com> writes:

> On 2018-05-20 16:19, Ben Bacarisse wrote:
>> bruceg113...@gmail.com writes:
>>
>>> Lets say I have the following tuple like string.
>>>(128, 020, 008, 255)
>>>
>>> What is the best way to to remove leading zeroes and end up with the 
>>> following.
>>>(128, 20, 8, 255)-- I do not care about spaces
>>
>> You could use a regexp:
>>
>>import re
>>...
>>re.sub(r"(?<![0-9])0+(?=[0-9])", "", "(128, 020, 008, 255)")
>>
>> I post this because I think it works (interesting corner cases are 10005
>> and 000), 
>
> Seeing this makes me realize that mine will eliminate any numbers that
> are all leading zero, including '0'. Also, forms like '-0042' will be
> left unchanged.

I realised after posting the negatives won't work.  Not, I suspect, an
issue for the OP but -0042 can certainly be said to have "leading
zeros".

> Maybe splitting it into integer forms and sending each through
> str( int( ) ) would be the safest.

Yup.  I gave a version of that method too which handles negative numbers
by accident (by leaving the - in place!).  A better version would be

  re.sub(r"-?[0-9]+", lambda m: str(int(m.group(0))), s)

<snip>
-- 
Ben.
-- 
<a  rel="nofollow" href="https://mail.python.org/mailman/listinfo/python-list">https://mail.python.org/mailman/listinfo/python-list</a>
</pre>

Re: best way to remove leading zeros from a tuple like string

2018-05-20 Thread Ben Bacarisse
bruceg113...@gmail.com writes:

> Lets say I have the following tuple like string.
>   (128, 020, 008, 255)
>
> What is the best way to to remove leading zeroes and end up with the 
> following.
>   (128, 20, 8, 255)-- I do not care about spaces

You could use a regexp:

  import re
  ...
  re.sub(r"(?https://mail.python.org/mailman/listinfo/python-list

Re: syntax oddities

2018-05-18 Thread Ben Bacarisse
bartc  writes:

> On 17/05/2018 23:49, Chris Angelico wrote:
>> On Fri, May 18, 2018 at 8:44 AM, Paul  wrote:
>
>>> I've been using email for thirty years, including thousands of group emails
>>> at many tech companies, and no one has ever suggested, let alone insisted
>>> on, bottom posting.  If someone's late to a thread they can read from it
>>> the bottom up.
>>
>> Remind me which direction text is usually written in English?
>
> Is this a trick question? It's usually written left to right.

in a rather biased way "front to back" -- turning pages to the left.
an English book is read left to right, top to bottom and what we call
two" because in printed text, pages also ordered need to be order.  Thus
we read English text left to right and top to bottom.  I say "at least
bottom.  The slightly sarcastic question was supposed remind people that
lines left to right, lines are stacked, almost always from top to
There are at least two directions for most text.  After constructing

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


Re: object types, mutable or not?

2018-05-17 Thread Ben Bacarisse
Anders Wegge Keller  writes:

> På Wed, 16 May 2018 14:48:27 +0100
> Paul Moore  skrev:
>
>> C++ called that an "rvalue". And then went on to define things that
>> could go on the left hand side of an assignment as "lvalues". And now
>> we have two confusing concepts to explain - see what happens when you
>> let a standards committee define your language? :-)
>
>  I'm not sure the C++ committee has to bear the responsibility for those
> terms. They are pretty well defined in the C world, so I think you need to
> point the finger of accusation at either Brian or Dennis.

The terms are much older than that.  The first BCPL (1967) reference
manual uses the terms, and I don't think Martin Richards invented them.

(And C++ has added glvalue and prvalue to lvalue and rvalue.)

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


Re: Leading 0's syntax error in datetime.date module (Python 3.6)

2018-05-11 Thread Ben Bacarisse
bartc  writes:

> On 11/05/2018 01:25, Marko Rauhamaa wrote:
>> Chris Angelico :
>>
>>> Octal makes a lot of sense in the right contexts.
>>
>> I think octal is a historical relic from a time when people weren't yet
>> comfortable with hexadecimal.
>
> It's a relic from when machines had word sizes that were multiples of
> three bits, or were divided up on 3-bit boundaries.

It got into C via B and B was often used on machine with a word size
that was a multiple of three.  But octal was very useful on 16-bit
PDP-11s which is probably why it was kept.  The PDP-11 has 8 registers
and uses 3 bits to specify the addressing mode and many instructions use
the top bit to indicate a variation such as word or byte operation.  The
result is that you'd never choose to use hex to look at PDP-11 code.
That familiarity with octal must have played a bit part in deciding to
include it in C.

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


Re: try-except syntax

2018-04-05 Thread Ben Bacarisse
ElChino  writes:

> I'm trying to simplify a try-except construct. E.g. how come
> this:
>   try:
> _x, pathname, _y = imp.find_module (mod, mod_path)
> return ("%s" % pathname)
>   except ImportError:
> pass
>   except RuntimeError:
> pass
> return ("")
>
> Cannot be simplified into this:
>   try:
> _x, pathname, _y = imp.find_module (mod, mod_path)
> return ("%s" % pathname)
>   except ImportError:
>   except RuntimeError:
> pass
> return ("")
>
> Like a "fall-through" in a C-switch statement.

The except parts don't fall through, and each one needs a "suite".
Also, the "pass" before the return is mysterious which makes me think
there's an indent error in what you posted.

Anyway, to coalesce two or more exception handlers, you are probably
looking for

  except (ImportError, RuntimeError):

which matches both.

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


Re: Why is the use of an undefined name not a syntax error?

2018-04-01 Thread Ben Bacarisse
David Foster  writes:

> My understanding is that the Python interpreter already has enough
> information when bytecode-compiling a .py file to determine which
> names correspond to local variables in functions. That suggests it has
> enough information to identify all valid names in a .py file and in
> particular to identify which names are not valid.
>
> If broken name references were detected at compile time, it would
> eliminate a huge class of errors before running the program: missing
> imports, call of misspelled top-level function, reference to
> misspelled local variable.

I'm not sure what you mean by "valid name" and "broken name references".
The usual error is about unbound names, and binding happens at run-time.
Consider this rather contrived example:

def g(a):
if f1(a):
x = a
else:
y = 2*a
return x+1 if f2(a) else y+1

('a' is there only to prevent some obvious optimisations.)

Are there any broken name references here?  You might get an
UnboundLocalError, though that depends on what f1 and f2 return.


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


Re: Curious case of UnboundLocalError

2018-03-30 Thread Ben Bacarisse
Johannes Bauer <dfnsonfsdu...@gmx.de> writes:

> On 30.03.2018 13:13, Ben Bacarisse wrote:
>
>>> import collections
>>>
>>> class Test(object):
>>> def __init__(self):
>>> z = {
>>> "y": collections.defaultdict(list),
>> 
>> This mention of collections refers to ...
>> 
>>> }
>>> for (_, collections) in z.items():
>> 
>> ... this local variable.
>
> Yup, but why? I mean, at the point of definition of "z", the only
> definition of "collections" that would be visible to the code would be
> the globally imported module, would it not? How can the code know of the
> local declaration that only comes *after*?

Why questions can be hard.  The language definition says what's supposed
to happen.  Is that enough of an answer to why?

  4.2.2. Resolution of names
  
  A scope defines the visibility of a name within a block. If a local
  variable is defined in a block, its scope includes that block. [...]


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


Re: Curious case of UnboundLocalError

2018-03-30 Thread Ben Bacarisse
Johannes Bauer  writes:

> I stumbled about something that I cannot quite explain while doing some
> stupid naming of variables in my code, in particular using "collections"
> as an identifier. However, what results is strange. I've created a
> minimal example. Consider this:
>
> import collections
>
> class Test(object):
>   def __init__(self):
>   z = {
>   "y": collections.defaultdict(list),

This mention of collections refers to ...

>   }
>   for (_, collections) in z.items():

... this local variable.

>   pass
>
> Test()

The same thing would happen in a plain function:

  import collections
 
  def f():
  z = { "y": collections.defaultdict(list) }
  for (_, collections) in z.items():
  pass
 
  f()

> In my opinion, this should run. However, this is what happens on Python
> 3.6.3 (default, Oct  3 2017, 21:45:48) [GCC 7.2.0] on linux):
>
> Traceback (most recent call last):
>   File "x.py", line 11, in 
> Test()
>   File "x.py", line 6, in __init__
> "y": collections.defaultdict(list),
> UnboundLocalError: local variable 'collections' referenced before assignment
>
> Interestingly, when I remove the class:

The significant change is removing the function that creates a local scope.

> import collections

This introduces "collections" as a global ...

> z = {
>   "y": collections.defaultdict(list),
> }
> for (_, collections) in z.items():

... and this uses that global ...

>   pass
>
> It works as expected (doesn't throw).

... except now collections is bound to a list (from the for) and no
longer refers to the module.

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


Re: Enumerating all 3-tuples (Posting On Python-List Prohibited)

2018-03-15 Thread Ben Bacarisse
Lawrence D’Oliveiro <lawrenced...@gmail.com> writes:

> On Thursday, March 15, 2018 at 2:56:24 PM UTC+13, Ben Bacarisse wrote:
>>
>> Lawrence D’Oliveiro writes:
>> 
>>> On Wednesday, March 14, 2018 at 2:18:24 PM UTC+13, Ben Bacarisse wrote:
>>>
>>>> Lawrence D’Oliveiro writes:
>>>> 
>>>> The original problem -- triples of natural numbers -- is
>>>> not particularly hard, but the general problem -- enumerating n-tuples
>>>> of some sequence -- is more interesting because it is a bit harder.
>>>
>>> It’s not harder--it’s exactly the same difficulty. You iterate the
>>> naturals, then interpose a function mapping them onto the set that you
>>> really want to use.
>> 
>> Yes, I said exactly that a couple of messages ago.
>
> I see. So you said it is a bit harder, and you also said it’s not
> harder at all. Got it.

Yes, I was not clear.  It was the point about mapping from a solution
that uses the natural numbers that's I mentioned before.  The "bit
harder" comes from generalising to n-tuples.

(I get the feeling I should apologise for something because I think I
have annoyed or irritated you.  I'm sure I don't always get the right
tone but I really hope I've not been rude.  I'm sorry if I have been.)

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


Re: Enumerating all 3-tuples (Posting On Python-List Prohibited)

2018-03-14 Thread Ben Bacarisse
Lawrence D’Oliveiro <lawrenced...@gmail.com> writes:

> On Wednesday, March 14, 2018 at 2:18:24 PM UTC+13, Ben Bacarisse wrote:
>> Lawrence D’Oliveiro writes:
>> 
>> The original problem -- triples of natural numbers -- is
>> not particularly hard, but the general problem -- enumerating n-tuples
>> of some sequence -- is more interesting because it is a bit harder.
>
> It’s not harder--it’s exactly the same difficulty. You iterate the
> naturals, then interpose a function mapping them onto the set that you
> really want to use.

Yes, I said exactly that a couple of messages ago.

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


Re: Enumerating all 3-tuples (Posting On Python-List Prohibited)

2018-03-13 Thread Ben Bacarisse
Lawrence D’Oliveiro <lawrenced...@gmail.com> writes:

> On Tuesday, March 13, 2018 at 1:58:48 PM UTC+13, Ben Bacarisse wrote:
>> Of course you can always generate n-tuples of N and then map these to
>> n-tuples of the intended sequence but that seems inelegant.
>
> This whole discussion seems to be going off on esoteric, irrelevant
> tangents. The problem was not that hard to solve.

Sure, but that's one thing that makes Usenet (and email lists)
interesting.  The original problem -- triples of natural numbers -- is
not particularly hard, but the general problem -- enumerating n-tuples
of some sequence -- is more interesting because it is a bit harder.

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


Re: Enumerating all 3-tuples (Posting On Python-List Prohibited)

2018-03-12 Thread Ben Bacarisse
Lawrence D’Oliveiro <lawrenced...@gmail.com> writes:

> On Sunday, March 11, 2018 at 2:40:16 PM UTC+13, Ben Bacarisse wrote:
>> It would be nice to avoid relying on any value-based ordering.
>
> I don’t see why. The set of elements has to have the same cardinality
> as the set of natural numbers, after all. Why not take advantage of
> that?

Maybe we are saying the same thing?  The elements from which the tuple
members are drawn need only be a sequence defined by a successor
function.  The values themselves need have no ordering nor, indeed, have
any of the arithmetic properties of N.

Of course you can always generate n-tuples of N and then map these to
n-tuples of the intended sequence but that seems inelegant.

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


Re: Enumerating all 3-tuples (Posting On Python-List Prohibited)

2018-03-10 Thread Ben Bacarisse
Lawrence D’Oliveiro <lawrenced...@gmail.com> writes:

> On Sunday, March 11, 2018 at 3:24:05 AM UTC+13, Ben Bacarisse wrote:
>> Unfortunately my Python is not up to using iterators well enough to
>> avoid a "maximum recursion depth exceeded" error.
>
> My solution only needed recursion up to a depth equal to the length of
> the tuples. The ordering is done based on the maximum value of any
> element of the tuple.

I'm sure deep recursion is not needed, it's just tricky translating from
a lazy language when one is not familiar with all the iterator
facilities in Python.  For example, I couldn't find an append operation
that returns an iterable.

It would be nice to avoid relying on any value-based ordering.  There is
inevitably an order that comes from the iterable whose elements are
being paired, trippled or whatever, but that's all that's really
required for a solution.

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


Re: Enumerating all 3-tuples

2018-03-10 Thread Ben Bacarisse
bartc <b...@freeuk.com> writes:

> On 10/03/2018 20:06, Ben Bacarisse wrote:
>>> On 10/03/2018 14:23, Ben Bacarisse wrote:

>>>> Off topic: I knocked up this Haskell version as a proof-of-concept:
>>>>
>>>> import Data.List
>>>>
>>>> pn n l = pn' n (map (:[]) l)
>>>>  where pn' n lists | n == 1 = lists
>>>>| otherwise = diag (pn' (n-1) lists) lists
>>>>diag l1 l2 = zipWith (++) (concat (inits l1))
>>>>  (concat (map reverse (inits 
>>>> l2)))
>>>>

>> but, as I've said, the order of the results is not the usual one (except
>> for pairs).

> OK. I ran it like this:
>
>  main = print (take 20 (pn 3 [1..]))
>
> But I'm trying to understand the patterns in the sequence. If I use:
>
>  main = print (take 50 (pn 2 [1..]))
>
> then group the results into sets of 1, 2, 3, etc pairs, showing each
> group on a new line, then this gives sequences which are equivalent to
> the diagonals of the OP's 2D grid. (Except they don't alternate in
> direction; is that what you mean?)

Yes, the pattern for pairs (pn 2 [1..]) is the normal one (one of them
anyway).  In the 2D grid the diagonals are lines of equal sum (for a
numeric grid, of course) and all the pairs that sum to x appear before
those that sum to x+1:

*Main> take 28 $ map sum $ pn 2 [1..]
[2,3,3,4,4,4,5,5,5,5,6,6,6,6,6,7,7,7,7,7,7,8,8,8,8,8,8,8]

The recursive step breaks this rule.  I'm sure there's a better rule,
but it's getting more and more off-topic...

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


Re: Enumerating all 3-tuples

2018-03-10 Thread Ben Bacarisse
bartc <b...@freeuk.com> writes:

> [repost as original seems to have gone to email; my newsreader has
> somehow acquired a 'Reply' button where 'Followup' normally goes.]

[I thought it was intended but my reply bounced.]

> On 10/03/2018 14:23, Ben Bacarisse wrote:
>> Ben Bacarisse <ben.use...@bsb.me.uk> writes:
>
>> Off topic: I knocked up this Haskell version as a proof-of-concept:
>>
>>import Data.List
>>
>>pn n l = pn' n (map (:[]) l)
>> where pn' n lists | n == 1 = lists
>>   | otherwise = diag (pn' (n-1) lists) lists
>>   diag l1 l2 = zipWith (++) (concat (inits l1))
>> (concat (map reverse (inits l2)))
>>

> What's the output? (And what's the input; how do you invoke pn, if
> that's how it's done?)

You pass a number and a list which should probably be infinite like
[1..].  You'd better take only a few of the resulting elements then:

*Main> let triples = pn 3 [1..]
*Main> take 20 triples
[[1,1,1],[1,1,2],[1,2,1],[1,1,3],[1,2,2],[2,1,1],[1,1,4],[1,2,3],[2,1,2],[1,3,1],[1,1,5],[1,2,4],[2,1,3],[1,3,2],[2,2,1],[1,1,6],[1,2,5],[2,1,4],[1,3,3],[2,2,2]]

or you can index the list to look at particular elements:

*Main> triples !! 1000
[70,6,1628]

but, as I've said, the order of the results is not the usual one (except
for pairs).

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


Re: Enumerating all 3-tuples

2018-03-10 Thread Ben Bacarisse
Sorry for following up to myself again...

Ben Bacarisse <ben.use...@bsb.me.uk> writes:

>> ...  But I think that is an easier way (no code yet though!) unless
>> you are set on one particular enumeration: consider the triple as a pair
>> one element of which runs over the enumeration of pairs you already
>> have.


This algorithm has the disadvantage that the sequence is not any of the
usual "zig-zag" patterns.  Using numbers, for example the sums of the
triples are not monotonic:

*Main> take 30 $ map sum (pn 2 [1..])
[3,4,4,5,5,4,6,6,5,5,7,7,6,6,5,8,8,7,7,6,5,9,9,8,8,7,6,6,10,10]

That probably makes it a non-starter for you.

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


Re: Enumerating all 3-tuples

2018-03-10 Thread Ben Bacarisse
Ben Bacarisse <ben.use...@bsb.me.uk> writes:

> Steven D'Aprano <steve+comp.lang.pyt...@pearwood.info> writes:
>
>> I am trying to enumerate all the three-tuples (x, y, z) where each of x, 
>> y, z can range from 1 to ∞ (infinity).


> ...  But I think that is an easier way (no code yet though!) unless
> you are set on one particular enumeration: consider the triple as a pair
> one element of which runs over the enumeration of pairs you already
> have.
>
> Start with
>
>   1,1  <->  1
>   2,1  <->  2
>   1,2  <->  3
>   3,1  <->  4
>   2,2  <->  5
>   1,3  <->  6
>   ...
>
> but replace the first element by the numbered pair from this same list:
>
>   (1,1),1
>   (2,1),1
>   (1,1),2
>   (1,2),1
>   (2,1),2
>   (1,1),3
>   ...
>
> If it were a sane time here I'd try to code this.  Looks like fun but it
> must wait...

One advantage of this method is that is does rely on any numeric
properties of the base list.  Any sequence-like object can be used to
make an list of n-tuples.

Unfortunately my Python is not up to using iterators well enough to
avoid a "maximum recursion depth exceeded" error.  Basically everything
must be kept "lazy" and I'm not sure how to do that in Python.  It will
help my Python to learn so I will have a go.

Off topic: I knocked up this Haskell version as a proof-of-concept:

  import Data.List

  pn n l = pn' n (map (:[]) l)
   where pn' n lists | n == 1 = lists
 | otherwise = diag (pn' (n-1) lists) lists
 diag l1 l2 = zipWith (++) (concat (inits l1))
   (concat (map reverse (inits l2)))

Notes:

map (:[]) l turns [1, 2, 3, ...] into [[1], [2], [3], ...]

inits gives the list of initial segments of l.  I.e. (inits "abc") is
["", "a", "ab", "abc"].

concat joins a list of lists into one list.

zipWith (++) l1 l2 makes a list by pair-wise appending the elements of
l1 and l2.

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


Re: Enumerating all 3-tuples

2018-03-09 Thread Ben Bacarisse
Steven D'Aprano  writes:

> I am trying to enumerate all the three-tuples (x, y, z) where each of x, 
> y, z can range from 1 to ∞ (infinity).
>
> This is clearly unhelpful:
>
> for x in itertools.count(1):
> for y in itertools.count(1):
> for z in itertools.count(1):
> print(x, y, z)
>
> as it never advances beyond x=1, y=1 since the innermost loop never 
> finishes.
>
> Georg Cantor to the rescue! (Well, almost...)
>
> https://en.wikipedia.org/wiki/Pairing_function
>
> The Russian mathematician Cantor came up with a *pairing function* that 
> encodes a pair of integers into a single one. For example, he maps the 
> coordinate pairs to integers as follows:
>
> 1,1  ->  1
> 2,1  ->  2
> 1,2  ->  3
> 3,1  ->  4
> 2,2  ->  5
>
> and so forth. He does this by writing out the coordinates in a grid:
>
> 1,1  1,2  1,3  1,4  ...
> 2,1  2,2  2,3  2,4  ...
> 3,1  3,2  3,3  3,4  ...
> 4,1  4,2  4,3  4,4  ...
> ...
>
> and then iterating over them along the diagonals, starting from the top 
> corner. That's just what I'm after, and I have this function that works 
> for 2-tuples:
>
> def cantor(start=0):
> """Yield coordinate pairs using Cantor's Pairing Function.
>
> Yields coordinate pairs in (Z*,Z*) over the diagonals:
>
> >>> it = cantor()
> >>> [next(it) for _ in range(10)]
> [(0,0), (1,0), (0,1), (2,0), (1,1), (0,2), (3,0), (2,1), (1,2), (0,3)]
>
> If ``start`` is given, it is used as the first x- and y-coordinate.
> """
> i = start
> while True:
> for j in range(start, i+1):
> yield (i-j+start, j)
> i += 1
>
>
> But I've stared at this for an hour and I can't see how to extend the 
> result to three coordinates. I can lay out a grid in the order I want:
>
> 1,1,1   1,1,2   1,1,3   1,1,4   ...
> 2,1,1   2,1,2   2,1,3   2,1,4   ...
> 1,2,1   1,2,2   1,2,3   1,2,4   ...
> 3,1,1   3,1,2   3,1,3   3,1,4   ...
> 2,2,1   2,2,2   2,2,3   2,2,4   ...
> ...
>
> and applying Cantor's diagonal order will give me what I want, but damned 
> if I can see how to do it in code.

Rather than a grid you would need a cube, and the diagonals become
planes.  But I think that is an easier way (no code yet though!) unless
you are set on one particular enumeration: consider the triple as a pair
one element of which runs over the enumeration of pairs you already
have.

Start with

  1,1  <->  1
  2,1  <->  2
  1,2  <->  3
  3,1  <->  4
  2,2  <->  5
  1,3  <->  6
  ...

but replace the first element by the numbered pair from this same list:

  (1,1),1
  (2,1),1
  (1,1),2
  (1,2),1
  (2,1),2
  (1,1),3
  ...

If it were a sane time here I'd try to code this.  Looks like fun but it
must wait...

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


Re: How to make Python run as fast (or faster) than Julia

2018-02-27 Thread Ben Bacarisse
Christian Gollwitzer  writes:

> George Marsaglia is a researcher who invented a couple of PRNGs which
> are both simple (one of the first was called KISS) yet surprisingly
> good.

s/is/was/

Sadly, he died a few years ago (2011).

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


Re: How to make Python run as fast (or faster) than Julia

2018-02-26 Thread Ben Bacarisse
bartc  writes:

> A C version is given below. (One I may have messed around with, which
> I'm not sure works properly. For an original, google for Marsaglia and
> KISS64 or SUPRKISS64.)

The version I know uses unsigned integers.  Did you change then to signed?

For a Python version, go back to the original C and work from there.

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


Re: How to make Python run as fast (or faster) than Julia

2018-02-23 Thread Ben Bacarisse
Steven D'Aprano  writes:

> On Fri, 23 Feb 2018 00:26:33 +, bartc wrote:
>
>> The point of the article was Julia vs. Python. You can't make Python
>> faster by switching to a faster algorithm; you have to use the same one
>> on both.
>
> No, the point of the article was to write Python code that is as fast as 
> the Julia code.

I did not get that impression.  In fact I was not really sure what the
point was.  At the start, the authors says

  "My take on this kind of cross language comparison is that the
  benchmarks should be defined by tasks to perform, then have language
  experts write the best code they can to perform these tasks."

but if that is the point (rather the one on you picked up on) then the
article could be, at best, only half the story.

> I don't know why the Julia programmers chose to use such a poor 
> algorithm:

It's odd indeed, but given that they did, what you take to be the point
of the article -- to write a good Python algorithm as fast as the
terrible Julia one -- seems a bit pointless.

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


Re: could use some help with this problem! (Posting On Python-List Prohibited)

2018-02-20 Thread Ben Bacarisse
Lawrence D’Oliveiro <lawrenced...@gmail.com> writes:

> On Wednesday, February 21, 2018 at 3:10:25 AM UTC+13, Ben Bacarisse wrote:
>> You almost never /have/ to use nested loops.  Has the course got this
>> far without introducing the idea of a function?
>
> If you are using a function to avoid a nested loop, perhaps that’s not
> such a smart use of a function...

Agreed.  And yet it /might/ be a smart use of one.  Nothing about simply
avoiding a loop is sufficient to make the assessment.

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


Re: could use some help with this problem! I've been working on it for days but cant seem to get it right !

2018-02-20 Thread Ben Bacarisse
Marc Cohen  writes:

> USING PYTHON 2:

Why is that?

> Write a program to play this game. This may seem tricky, so break it
> down into parts. Like many programs, we have to use nested loops (one
> loop inside another). In the outermost loop, we want to keep playing
> until we are out of stones.

You almost never /have/ to use nested loops.  Has the course got this
far without introducing the idea of a function?


> So, the basic outline of the program should be something like this:
>
> totalStones = 100
>
> maxStones = 5

maxTake or maxMove might be a more helpful name.

> pile = TOTAL # all stones are in the pile to start
>
> while [pile is not empty]:
>
> while [player 1's answer is not valid]:
>
> [ask player 1]
>
> [execute player1’s move]
>
> Do the same for player 2…. (this can be achieved by a for loop)

Is the idea for the program to play an optimal strategy for player 2, or
is the program simply doing the housekeeping -- verifying moves and
tracing the pile of stones?


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


  1   2   3   >