Re: Python 2.7 range Function provokes a Memory Error

2023-03-06 Thread Stephen Tucker
Hi again,

I tried xrange, but I got an error telling me that my integer was too big
for a C long.

Clearly, xrange in Py2 is not capable of dealing with Python (that is,
possibly very long) integers.

I am raising this because,

(a) IF xrange in Py3 is a simple "port" from Py2, then it won't handle
Python integers either.

AND

(b) IF xrange in Py3 is intended to be equivalent to range (which, even in
Py2, does handle Python integers)

THEN

It could be argued that xrange in Py3 needs some attention from the
developer(s).

Stephen Tucker.


On Thu, Mar 2, 2023 at 6:24 PM Jon Ribbens via Python-list <
python-list@python.org> wrote:

> On 2023-03-02, Stephen Tucker  wrote:
> > The range function in Python 2.7 (and yes, I know that it is now
> > superseded), provokes a Memory Error when asked to deiliver a very long
> > list of values.
> >
> > I assume that this is because the function produces a list which it then
> > iterates through.
> >
> > 1. Does the  range  function in Python 3.x behave the same way?
>
> No, in Python 3 it is an iterator which produces the next number in the
> sequence each time.
>
> > 2. Is there any equivalent way that behaves more like a  for loop (that
> is,
> > without producing a list)?
>
> Yes, 'xrange' in Python 2 behaves like 'range' in Python 3.
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Python 2.7 range Function provokes a Memory Error

2023-03-02 Thread Stephen Tucker
Hi,

The range function in Python 2.7 (and yes, I know that it is now
superseded), provokes a Memory Error when asked to deiliver a very long
list of values.

I assume that this is because the function produces a list which it then
iterates through.

1. Does the  range  function in Python 3.x behave the same way?

2. Is there any equivalent way that behaves more like a  for loop (that is,
without producing a list)?

To get round the problem I have written my own software that is used in a
for  loop.

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


Re: Precision Tail-off?

2023-02-17 Thread Stephen Tucker
As a follow-up to my previous message, I have just produced the following
log on IDLE, for your information:
--
>>> math.e ** (math.log
(12345678900) / 3)
4.979338592181741e+16
>>> 10 ** (math.log10 (12345678900)
/ 3)
4.979338592181736e+16
>>> 12345678900 ** (1.0 / 3.0)
4.979338592181734e+16
>>> 123456789e42 ** (1.0 / 3.0)
4.979338592181734e+16
------

Stephen Tucker.


On Fri, Feb 17, 2023 at 10:27 AM Stephen Tucker 
wrote:

> Thanks, one and all, for your reponses.
>
> This is a hugely controversial claim, I know, but I would consider this
> behaviour to be a serious deficiency in the IEEE standard.
>
> Consider an integer N consisting of a finitely-long string of digits in
> base 10.
>
> Consider the infinitely-precise cube root of N (yes I know that it could
> never be computed unless N is the cube of an integer, but this is a
> mathematical argument, not a computational one), also in base 10. Let's
> call it RootN.
>
> Now consider appending three zeroes to the right-hand end of N (let's call
> it NZZZ) and NZZZ's infinitely-precise cube root (RootNZZZ).
>
> The *only *difference between RootN and RootNZZZ is that the decimal
> point in RootNZZZ is one place further to the right than the decimal point
> in RootN.
>
> None of the digits in RootNZZZ's string should be different from the
> corresponding digits in RootN.
>
> I rest my case.
>
> Perhaps this observation should be brought to the attention of the IEEE. I
> would like to know their response to it.
>
> Stephen Tucker.
>
>
> On Thu, Feb 16, 2023 at 6:49 PM Peter Pearson 
> wrote:
>
>> On Tue, 14 Feb 2023 11:17:20 +, Oscar Benjamin wrote:
>> > On Tue, 14 Feb 2023 at 07:12, Stephen Tucker 
>> wrote:
>> [snip]
>> >> I have just produced the following log in IDLE (admittedly, in Python
>> >> 2.7.10 and, yes I know that it has been superseded).
>> >>
>> >> It appears to show a precision tail-off as the supplied float gets
>> bigger.
>> [snip]
>> >>
>> >> For your information, the first 20 significant figures of the cube
>> root in
>> >> question are:
>> >>49793385921817447440
>> >>
>> >> Stephen Tucker.
>> >> --
>> >> >>> 123.456789 ** (1.0 / 3.0)
>> >> 4.979338592181744
>> >> >>> 1234567890. ** (1.0 / 3.0)
>> >> 49793385921817.36
>> >
>> > You need to be aware that 1.0/3.0 is a float that is not exactly equal
>> > to 1/3 ...
>> [snip]
>> > SymPy again:
>> >
>> > In [37]: a, x = symbols('a, x')
>> >
>> > In [38]: print(series(a**x, x, Rational(1, 3), 2))
>> > a**(1/3) + a**(1/3)*(x - 1/3)*log(a) + O((x - 1/3)**2, (x, 1/3))
>> >
>> > You can see that the leading relative error term from x being not
>> > quite equal to 1/3 is proportional to the log of the base. You should
>> > expect this difference to grow approximately linearly as you keep
>> > adding more zeros in the base.
>>
>> Marvelous.  Thank you.
>>
>>
>> --
>> To email me, substitute nowhere->runbox, invalid->com.
>> --
>> https://mail.python.org/mailman/listinfo/python-list
>>
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Precision Tail-off?

2023-02-17 Thread Stephen Tucker
Thanks, one and all, for your reponses.

This is a hugely controversial claim, I know, but I would consider this
behaviour to be a serious deficiency in the IEEE standard.

Consider an integer N consisting of a finitely-long string of digits in
base 10.

Consider the infinitely-precise cube root of N (yes I know that it could
never be computed unless N is the cube of an integer, but this is a
mathematical argument, not a computational one), also in base 10. Let's
call it RootN.

Now consider appending three zeroes to the right-hand end of N (let's call
it NZZZ) and NZZZ's infinitely-precise cube root (RootNZZZ).

The *only *difference between RootN and RootNZZZ is that the decimal point
in RootNZZZ is one place further to the right than the decimal point in
RootN.

None of the digits in RootNZZZ's string should be different from the
corresponding digits in RootN.

I rest my case.

Perhaps this observation should be brought to the attention of the IEEE. I
would like to know their response to it.

Stephen Tucker.


On Thu, Feb 16, 2023 at 6:49 PM Peter Pearson 
wrote:

> On Tue, 14 Feb 2023 11:17:20 +, Oscar Benjamin wrote:
> > On Tue, 14 Feb 2023 at 07:12, Stephen Tucker 
> wrote:
> [snip]
> >> I have just produced the following log in IDLE (admittedly, in Python
> >> 2.7.10 and, yes I know that it has been superseded).
> >>
> >> It appears to show a precision tail-off as the supplied float gets
> bigger.
> [snip]
> >>
> >> For your information, the first 20 significant figures of the cube root
> in
> >> question are:
> >>49793385921817447440
> >>
> >> Stephen Tucker.
> >> --
> >> >>> 123.456789 ** (1.0 / 3.0)
> >> 4.979338592181744
> >> >>> 1234567890. ** (1.0 / 3.0)
> >> 49793385921817.36
> >
> > You need to be aware that 1.0/3.0 is a float that is not exactly equal
> > to 1/3 ...
> [snip]
> > SymPy again:
> >
> > In [37]: a, x = symbols('a, x')
> >
> > In [38]: print(series(a**x, x, Rational(1, 3), 2))
> > a**(1/3) + a**(1/3)*(x - 1/3)*log(a) + O((x - 1/3)**2, (x, 1/3))
> >
> > You can see that the leading relative error term from x being not
> > quite equal to 1/3 is proportional to the log of the base. You should
> > expect this difference to grow approximately linearly as you keep
> > adding more zeros in the base.
>
> Marvelous.  Thank you.
>
>
> --
> To email me, substitute nowhere->runbox, invalid->com.
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Precision Tail-off?

2023-02-13 Thread Stephen Tucker
Hi,

I have just produced the following log in IDLE (admittedly, in Python
2.7.10 and, yes I know that it has been superseded).

It appears to show a precision tail-off as the supplied float gets bigger.

I have two questions:
1. Is there a straightforward explanation for this or is it a bug?
2. Is the same behaviour exhibited in Python 3.x?

For your information, the first 20 significant figures of the cube root in
question are:
   49793385921817447440

Stephen Tucker.
--
>>> 123.456789 ** (1.0 / 3.0)
4.979338592181744
>>> 123456.789 ** (1.0 / 3.0)
49.79338592181744
>>> 123456789. ** (1.0 / 3.0)
497.9338592181743
>>> 123456789000. ** (1.0 / 3.0)
4979.338592181743
>>> 12345678900. ** (1.0 / 3.0)
49793.38592181742
>>> 1234567890. ** (1.0 / 3.0)
497933.8592181741
>>> 123456789. ** (1.0 / 3.0)
4979338.59218174
>>> 123456789000. ** (1.0 / 3.0)
49793385.9218174
>>> 12345678900. ** (1.0 / 3.0)
497933859.2181739
>>> 1234567890. ** (1.0 / 3.0)
4979338592.181739
>>> 123456789. ** (1.0 / 3.0)
49793385921.81738
>>> 123456789000. ** (1.0 / 3.0)
497933859218.1737
>>> 12345678900. ** (1.0 / 3.0)
4979338592181.736
>>> 1234567890. ** (1.0 / 3.0)
49793385921817.36
>>> 123456789. ** (1.0 / 3.0)
497933859218173.56
>>> 123456789000. ** (1.0 / 3.0)
4979338592181735.0
>>> 12345678900. ** (1.0 / 3.0)
4.979338592181734e+16
>>> 1234567890. ** (1.0 / 3.0)
4.979338592181734e+17
>>> 123456789. ** (1.0 /
3.0)
4.979338592181733e+18
>>> 123456789000. ** (1.0 /
3.0)
4.979338592181732e+19
>>> 12345678900. **
(1.0 / 3.0)
4.9793385921817313e+20
--
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: IDLE "Codepage" Switching?

2023-01-18 Thread Stephen Tucker
Thanks for these responses.

I was encouraged to read that I'm not the only one to find this all
confusing.

I have investigated a little further.

1. I produced the following IDLE log:

>>> mylongstr = ""
>>> for thisCP in range (1, 256):
mylongstr += chr (thisCP) + " " + str (ord (chr (thisCP))) + ", "


>>> print mylongstr
1, 2, 3, 4, 5, 6, 7, 8, 9,
 10, 11, 12,
 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
31,   32, ! 33, " 34, # 35, $ 36, % 37, & 38, ' 39, ( 40, ) 41, * 42, + 43,
, 44, - 45, . 46, / 47, 0 48, 1 49, 2 50, 3 51, 4 52, 5 53, 6 54, 7 55, 8
56, 9 57, : 58, ; 59, < 60, = 61, > 62, ? 63, @ 64, A 65, B 66, C 67, D 68,
E 69, F 70, G 71, H 72, I 73, J 74, K 75, L 76, M 77, N 78, O 79, P 80, Q
81, R 82, S 83, T 84, U 85, V 86, W 87, X 88, Y 89, Z 90, [ 91, \ 92, ] 93,
^ 94, _ 95, ` 96, a 97, b 98, c 99, d 100, e 101, f 102, g 103, h 104, i
105, j 106, k 107, l 108, m 109, n 110, o 111, p 112, q 113, r 114, s 115,
t 116, u 117, v 118, w 119, x 120, y 121, z 122, { 123, | 124, } 125, ~
126, 127, タ 128, チ 129, ツ 130, テ 131, ト 132, ナ 133, ニ 134, ヌ 135, ネ 136, ノ
137, ハ 138, ヒ 139, フ 140, ヘ 141, ホ 142, マ 143, ミ 144, ム 145, メ 146, モ 147,
ヤ 148, ユ 149, ヨ 150, ラ 151, リ 152, ル 153, レ 154, ロ 155, ワ 156, ン 157, ゙
158, ゚ 159, ᅠ 160, ᄀ 161, ᄁ 162, ᆪ 163, ᄂ 164, ᆬ 165, ᆭ 166, ᄃ 167, ᄄ 168,
ᄅ 169, ᆰ 170, ᆱ 171, ᆲ 172, ᆳ 173, ᆴ 174, ᆵ 175, ᄚ 176, ᄆ 177, ᄇ 178, ᄈ
179, ᄡ 180, ᄉ 181, ᄊ 182, ᄋ 183, ᄌ 184, ᄍ 185, ᄎ 186, ᄏ 187, ᄐ 188, ᄑ 189,
ᄒ 190, ﾿ 191, À 192, Á 193, Â 194, Ã 195, Ä 196, Å 197, Æ 198, Ç 199, È
200, É 201, Ê 202, Ë 203, Ì 204, Í 205, Î 206, Ï 207, Ð 208, Ñ 209, Ò 210,
Ó 211, Ô 212, Õ 213, Ö 214, × 215, Ø 216, Ù 217, Ú 218, Û 219, Ü 220, Ý
221, Þ 222, ß 223, à 224, á 225, â 226, ã 227, ä 228, å 229, æ 230, ç 231,
è 232, é 233, ê 234, ë 235, ì 236, í 237, î 238, ï 239, ð 240, ñ 241, ò
242, ó 243, ô 244, õ 245, ö 246, ÷ 247, ø 248, ù 249, ú 250, û 251, ü 252,
ý 253, þ 254, ÿ 255,
>>>

2. I copied and pasted the IDLE log into a text file and ran a program on
it that told me about every byte in the log.

3. I discovered the following:

Bytes 001 to 127 (01 to 7F hex) inclusive were printed as-is;

Bytes 128 to 191 (80 to BF) inclusive were output as UTF-8-encoded
characters whose codepoints were FF00 hex more than the byte values (hence
the strange glyphs);

Bytes 192 to 255 (C0 to FF) inclusive were output as UTF-8-encoded
characters - without any offset being added to their codepoints in the
meantime!

I thought you might just be interested in this - there does seem to be some
method in IDLE's mind, at least.

Stephen Tucker.








On Wed, Jan 18, 2023 at 9:41 AM Peter J. Holzer  wrote:

> On 2023-01-17 22:58:53 -0500, Thomas Passin wrote:
> > On 1/17/2023 8:46 PM, rbowman wrote:
> > > On Tue, 17 Jan 2023 12:47:29 +, Stephen Tucker wrote:
> > > > 2. Does the IDLE in Python 3.x behave the same way?
> > >
> > > fwiw
> > >
> > > Python 3.10.6 (main, Nov 14 2022, 16:10:14) [GCC 11.3.0] on linux
> > > Type "help", "copyright", "credits" or "license()" for more
> information.
> > > str = ""
> > > for c in range(140, 169):
> > >  str += chr(c) + " "
> > >
> > > print(str)
> > > Œ   Ž ‘ ’ “ ” • – — ˜ ™ š › œ   ž Ÿ   ¡ ¢ £ ¤ ¥
> > > ¦ § ¨
> > >
> > >
> > > I don't know how this will appear since Pan is showing the icon for a
> > > character not in its set.  However, even with more undefined characters
> > > the printable one do not change. I get the same output running Python3
> > > from the terminal so it's not an IDLE thing.
> >
> > I'm not sure what explanation is being asked for here.  Let's take
> Python3,
> > so we can be sure that the strings are in unicode.  The font being used
> by
> > the console isn't mentioned, but there's no reason it should have glyphs
> for
> > any random unicode character.
>
> Also note that the characters between 128 (U+0080) and 159 (U+009F)
> inclusive aren't printable characters. They are control characters.
>
> hp
>
> --
>_  | Peter J. Holzer| Story must make more sense than reality.
> |_|_) ||
> | |   | h...@hjp.at |-- Charles Stross, "Creative writing
> __/   | http://www.hjp.at/ |   challenge!"
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


IDLE "Codepage" Switching?

2023-01-17 Thread Stephen Tucker
I have four questions.

1. Can anybody explain the behaviour in IDLE (Python version 2.7.10)
reported below? (It seems that the way it renders a given sequence of bytes
depends on the sequence.)

2. Does the IDLE in Python 3.x behave the same way?

3. If it does, is this as it should behave?

4. If it is, then why is it as it should behave?
==
>>> mylongstr = ""
>>> for thisCP in range (157, 169):
mylongstr += chr (thisCP) + " "


>>> print mylongstr
ン ゙ ゚ ᅠ ᄀ ᄁ ᆪ ᄂ ᆬ ᆭ ᄃ ᄄ
>>> mylongstr = ""
>>> for thisCP in range (158, 169):
mylongstr += chr (thisCP) + " "


>>> print mylongstr
ž Ÿ   ¡ ¢ £ ¤ ¥ ¦ § ¨
>>> mylongstr = ""
>>> for thisCP in range (157, 169):
    mylongstr += chr (thisCP) + " "


>>> print mylongstr
ン ゙ ゚ ᅠ ᄀ ᄁ ᆪ ᄂ ᆬ ᆭ ᄃ ᄄ
==

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


Re: file.read Method Documentation (Python 2.7.10)

2023-01-12 Thread Stephen Tucker
Chris,

Thanks for this clarification.

I have not found documentation that disagrees with you. I simply observe
that the documentation that I have alluded to earlier in this chain
(section 5.9 File Objects) could have been made clearer by the addition of
a note along the lines that the behaviour of a file's read method (in
particular, what the unit of information is that it reads (that is, "byte",
"UTF-8 encoded character", or whatever)) depends on the way in which the
file has been opened.

Thank you, Chris (and others) for your attention to my request. I consider
this enquiry closed.

Stephen.




On Wed, Jan 11, 2023 at 5:36 PM Chris Angelico  wrote:

> On Thu, 12 Jan 2023 at 04:31, Stephen Tucker 
> wrote:
> > 1. Create BOM.txt
> > 2. Input three bytes at once from BOM.txt and print them
> > 3. Input three bytes one at a time from BOM.txt and print them
>
> All of these correctly show that a file, in binary mode, reads and writes
> bytes.
>
> > 4. Input three bytes at once from BOM.txt and print them
> > >>> import codecs
> > >>> myfil = codecs.open ("BOM.txt", mode="rb", encoding="UTF-8")
>
> This is now a codecs file, NOT a vanilla file object. See its docs here:
>
> https://docs.python.org/2.7/library/codecs.html#codecs.open
>
> The output is "codec-dependent" but I would assume that UTF-8 will
> yield Unicode text strings.
>
> > 5. Attempt to input three bytes one at a time from BOM.txt and print them
> > -
> >
> > >>> myfil = codecs.open ("BOM.txt", mode="rb", encoding="UTF-8")
> > >>> myBOM_4 = myfil.read (1)
> > >>> myBOM_4
> > u'\ufeff'
>
> > A. The attempt at Part 5 actually inputs all three bytes when we ask it
> to input just the first one!
>
> On the contrary; you asked it for one *character* and it read one
> character.
>
> Where were you seeing documentation that disagreed with this?
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: file.read Method Documentation (Python 2.7.10)

2023-01-11 Thread Stephen Tucker
Chris,

Thanks for your reply.

I hope the evidence below (taken from IDLE) clarifies my issue:

Stephen.

==


1. Create BOM.txt
-

>>> myfil = open ("BOM.txt", "wb")
>>> myfil.write ("\xef" + "\xbb" + "\xbf")
>>> myfil.close()

2. Input three bytes at once from BOM.txt and print them


>>> myfil = open ("BOM.txt", "rb")
>>> myBOM = myfil.read (3)
>>> myBOM
'\xef\xbb\xbf'
>>> myfil.close()

3. Input three bytes one at a time from BOM.txt and print them
--

>>> myfil = open ("BOM.txt", "rb")
>>> myBOM_1 = myfil.read (1)
>>> myBOM_2 = myfil.read (1)
>>> myBOM_3 = myfil.read (1)
>>> myBOM_1
'\xef'
>>> myBOM_2
'\xbb'
>>> myBOM_3
'\xbf'
>>> myfil.close()

4. Input three bytes at once from BOM.txt and print them


>>> import codecs
>>> myfil = codecs.open ("BOM.txt", mode="rb", encoding="UTF-8")
>>> myBOM = unicode (myfil.read (3))
>>> myBOM
u'\ufeff'
>>> myfil.close ()

5. Attempt to input three bytes one at a time from BOM.txt and print them
-

>>> myfil = codecs.open ("BOM.txt", mode="rb", encoding="UTF-8")
>>> myBOM_4 = myfil.read (1)
>>> myBOM_5 = myfil.read (1)
>>> myBOM_6 = myfil.read (1)
>>> myBOM_4
u'\ufeff'
>>> myBOM_5
u''
>>> myBOM_6
u''
>>> myfil.close()

Notes

A. The attempt at Part 5 actually inputs all three bytes when we ask it to
input just the first one!

B. The outcome from Part 5 shows that, actually, the request to input text
in Part 4 brought about a response from the program something like this:

   Input the UTF-8-encoded character as the first "byte";
   As expected, after reaching the end of the file, continue supplying an
empty string for each of the requested extra bytes.

==


On Wed, Jan 11, 2023 at 11:00 AM Chris Angelico  wrote:

> On Wed, 11 Jan 2023 at 21:31, Stephen Tucker 
> wrote:
> >
> > Chris -
> >
> > In the Python 2.7.10 documentation, I am referring to section 5.
> Built-in Types, subsection 5.9 File Objects.
> >
> > In that subsection, I have the following paragraph:
> >
> > file.read([size])
> >
> > Read at most size bytes from the file (less if the read hits EOF before
> obtaining size bytes). If the size argument is negative or omitted, read
> all data until EOF is reached. The bytes are returned as a string object.
> An empty string is returned when EOF is encountered immediately. (For
> certain files, like ttys, it makes sense to continue reading after an EOF
> is hit.) Note that this method may call the underlying C function fread()
> more than once in an effort to acquire as close to size bytes as possible.
> Also note that when in non-blocking mode, less data than was requested may
> be returned, even if no size parameter was given.
> >
>
> Yes, so it should be that number of bytes, which is what it does, isn't it?
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: file.read Method Documentation (Python 2.7.10)

2023-01-11 Thread Stephen Tucker
Chris -

In the Python 2.7.10 documentation, I am referring to section 5. Built-in
Types, subsection 5.9 File Objects.

In that subsection, I have the following paragraph:

file.read([*size*])

Read at most *size* bytes from the file (less if the read hits EOF before
obtaining *size* bytes). If the *size* argument is negative or omitted,
read all data until EOF is reached. The bytes are returned as a string
object. An empty string is returned when EOF is encountered immediately.
(For certain files, like ttys, it makes sense to continue reading after an
EOF is hit.) Note that this method may call the underlying C function
fread() more than once in an effort to acquire as close to *size* bytes as
possible. Also note that when in non-blocking mode, less data than was
requested may be returned, even if no *size* parameter was given.

Note

This function is simply a wrapper for the underlying fread() C function,
and will behave the same in corner cases, such as whether the EOF value is
cached.
Stephen.

On Mon, Jan 9, 2023 at 6:25 PM Chris Angelico  wrote:

> On Tue, 10 Jan 2023 at 01:36, Stephen Tucker 
> wrote:
> >
> > Dear Python-list,
> >
> > Yes, I know that Python 2.x is no longer supported.
> >
> > I have found that the documentation for this method is misleading when
> the
> > file being read is UTF-8-encoded:
> >
> >Instead of reading *size* bytes, the method reads *size *UTF-8 byte
> > *sequences*.
> >
> > Has this error been corrected in the Python 3.x documentation?
> >
>
> What documentation is this? The builtin 'file' type doesn't know
> anything about encodings, and only ever returns bytes.
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


file.read Method Documentation (Python 2.7.10)

2023-01-09 Thread Stephen Tucker
Dear Python-list,

Yes, I know that Python 2.x is no longer supported.

I have found that the documentation for this method is misleading when the
file being read is UTF-8-encoded:

   Instead of reading *size* bytes, the method reads *size *UTF-8 byte
*sequences*.

Has this error been corrected in the Python 3.x documentation?

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


Are these good ideas?

2022-11-14 Thread Stephen Tucker
Hi,

I have two related issues I'd like comments on.

Issue 1 - Global Values

Some years ago, I had a situation where
(a) I could supply low-level functions that carry out tasks,
(b) I needed those functions to communicate with each other, but
(c) I had no access to the module that invoked my functions.

In order to achieve this, I hit on the idea that I also supply a module
that I describe as a "global values" module. This module …
(i) … defines the values that the functions use to communicate with each
other;
(ii) … is the subject of an import statement in each of my functions;
(iii) … initialises its values at the start of each run (since the import
only carries out an actual import once per session);
(iv) … acts as a repository for the values thereafter.

This solution works well.

Given that I am not particularly concerned about efficiency,
(1) Is this a reasonable way to achieve this goal?
(2) Do you know of any better ways?

Issue 2 - Passed Parameters

I am now facing another situation where I am wanting to pass 6 or 7
parameters down through several layers of logic (function A calling
function B calling ... ) and for results to be passed back.

Having had the idea described above, I am considering using it again to
save all the parameter-and-results passing.

I see nothing wrong with doing that, but I may well be missing something!

Comments, please!

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


Discerning "Run Environment"

2022-05-18 Thread Stephen Tucker
Hi,

I am a Windows 10 user still using Python 2.x (for good reasons, I assure
you.)

I have a Python 2.x module that I would like to be able to use in a variety
of Python 2.x programs. The module outputs characters to the user that are
only available in the Unicode character set.

I have found that the selection of characters in that set that are
available to my software depends on whether, for example, the program is
being run during an IDLE session or at a Command Prompt.

I am therefore needing to include logic in this module that (a) enables it
to output appropriate characters depending on whether it is being run
during an IDLE session or at a command prompt, and (b) enables it to
discern which of these two "run environments" it is running in.

Goal (a) is achieved easily by using string.replace to replace unavailable
characters with available ones where necessary.

The best way I have found so far to achieve goal (b) is to use sys.modules
and ascertain whether any modules contain the string "idlelib". If they do,
that I assume that the software is being run in an IDLE session.

I suspect that there is a more Pythonic (and reliable?) way of achieving
goal (b).

Can anyone please tell me if there is, and, if there is, what it is?

Thanks.

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


Re: Printing Unicode strings in a list

2022-04-28 Thread Stephen Tucker
To Cameron Simpson,

Thanks for your in-depth and helpful reply. I have noted it and will be
giving it close attention when I can.

The main reason why I am still using Python 2.x is that my colleagues are
still using a GIS system that has a Python programmer's interface - and
that interface uses Python 2.x.

The team are moving to an updated version of the system whose Python
interface is Python 3.x.

However, I am expecting to retire over the next 8 months or so, so I do not
need to be concerned with Python 3.x - my successor will be doing that.

Stephen.


On Thu, Apr 28, 2022 at 2:07 PM Cameron Simpson  wrote:

> On 28Apr2022 12:32, Stephen Tucker  wrote:
> >Consider the following log from a run of IDLE:
> >==
> >
> >Python 2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)]
> >on win32
> >Type "copyright", "credits" or "license()" for more information.
> >>>> print (u"\u2551")
> >║
> >>>> print ([u"\u2551"])
> >[u'\u2551']
> >>>>
> >==
> >
> >Yes, I am still using Python 2.x - I have good reasons for doing so and
> >will be moving to Python 3.x in due course.
>
> Love to hear those reasons. Not suggesting that they are invalid.
>
> >I have the following questions arising from the log:
> >1. Why does the second print statement not produce [ ║]  or ["║"] ?
>
> Because print() prints the str() or each of its arguments, and str() of
> a list if the same as its repr(), which is a list of the repr()s of
> every item in the list. Repr of a Unicode string looks like what you
> have in Python 2.
>
> >2. Should the second print statement produce [ ║]  or ["║"] ?
>
> Well, to me its behaviour is correct. Do you _want_ to get your Unicode
> glyph? in quotes? That is up to you. But consider: what would be sane
> output if the list contained the string "], [3," ?
>
> >3. Given that I want to print a list of Unicode strings so that their
> >characters are displayed (instead of their Unicode codepoint definitions),
> >is there a more Pythonic way of doing it than concatenating them into a
> >single string and printing that?
>
> You could print them with empty separators:
>
> print(s1, s2, .., sep='')
>
> To do that in Python 2 you need to:
>
> from __future__ import print_function
>
> at the top of your Python file. Then you've have a Python 3 string print
> function. In Python 2, pint is normally a statement and you don't need
> the brackets:
>
> print u"\u2551"
>
> but print() is genuinely better as a function anyway.
>
> >4. Does Python 3.x exhibit the same behaviour as Python 2.x in this
> respect?
>
> Broadly yes, except that all strings are Unicode strings and we don't
> bothing with the leading "u" prefix.
>
> Cheers,
> Cameron Simpson 
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Printing Unicode strings in a list

2022-04-28 Thread Stephen Tucker
Hi PythonList Members,

Consider the following log from a run of IDLE:

==

Python 2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)]
on win32
Type "copyright", "credits" or "license()" for more information.
>>> print (u"\u2551")
║
>>> print ([u"\u2551"])
[u'\u2551']
>>>

==

Yes, I am still using Python 2.x - I have good reasons for doing so and
will be moving to Python 3.x in due course.

I have the following questions arising from the log:

1. Why does the second print statement not produce [ ║]  or ["║"] ?

2. Should the second print statement produce [ ║]  or ["║"] ?

3. Given that I want to print a list of Unicode strings so that their
characters are displayed (instead of their Unicode codepoint definitions),
is there a more Pythonic way of doing it than concatenating them into a
single string and printing that?

4. Does Python 3.x exhibit the same behaviour as Python 2.x in this respect?

Thanks in anticipation.

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


Re: Is there a better way to create a list of None objects?

2021-08-12 Thread Stephen Tucker
Thanks for this feedback, Chris, Matthieu. Both are spot on - and thanks
for the timing comparison, Matthieu. I suppose I didn't think to try the
solution you suggest because I didn't think that I would end up with a
single list, but 8 of them.

OK, I'll stop wriggling.

Stephen.

On Thu, Aug 12, 2021 at 10:22 AM Matthieu Dartiailh 
wrote:

> You can achieve the same result by writing:
> [None] * 8
>
> Comparing both cases in IPython I get:
>
> In [1]: %timeit list((None,)*8)
> 110 ns ± 0.785 ns per loop (mean ± std. dev. of 7 runs, 1000 loops
> each)
>
> In [2]: %timeit [None] * 8
> 88.2 ns ± 0.432 ns per loop (mean ± std. dev. of 7 runs, 1000 loops
> each)
>
> So the list multiplication appears a bit faster.
>
> Best
>
> Matthieu
>
> Le 8/12/2021 à 10:57 AM, Stephen Tucker a écrit :
> > Hi,
> >
> > I thought I'd share the following piece of code that I have recently
> written
> > (a) to check that what I have done is reasonable - even optimum,
> > (b) to inform others who might be wanting to do similar things, and
> > (c) to invite comment from the community.
> >
> > ---
> >
> > #
> >
> > # Yes: Create an empty list of Band Limits for this language
> >
> > #
> >
> > # Note. The rather complicated logic on the right-hand side of the
> >
> > #   assignment below is used here because none of the following
> >
> > #   alternatives had the desired effect:
> >
> > #
> >
> > # Logic Effect
> >
> > #
> >
> > # [None * 8]TypeError: unsupported operand type(s) for *: ...
> >
> > # [(None) * 8]  TypeError: unsupported operand type(s) for *: ...
> >
> > # [((None)) * 8]TypeError: unsupported operand type(s) for *: ...
> >
> > # [(None,) * 8] [(None, None, None, None, None, None, None, None)]
> >
> > # list ((None) * 8) TypeError: unsupported operand type(s) for *: ...
> >
> > #
> >
> > diclll_BLim [thisISO_] = list ((None,) * 8)
> >
> >
> > ---
> >
> > Thanks in anticipation.
> >
> > Stephen Tucker.
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Is there a better way to create a list of None objects?

2021-08-12 Thread Stephen Tucker
Hi,

I thought I'd share the following piece of code that I have recently written
(a) to check that what I have done is reasonable - even optimum,
(b) to inform others who might be wanting to do similar things, and
(c) to invite comment from the community.

---

#

# Yes: Create an empty list of Band Limits for this language

#

# Note. The rather complicated logic on the right-hand side of the

#   assignment below is used here because none of the following

#   alternatives had the desired effect:

#

# Logic Effect

#

# [None * 8]TypeError: unsupported operand type(s) for *: ...

# [(None) * 8]  TypeError: unsupported operand type(s) for *: ...

# [((None)) * 8]TypeError: unsupported operand type(s) for *: ...

# [(None,) * 8] [(None, None, None, None, None, None, None, None)]

# list ((None) * 8) TypeError: unsupported operand type(s) for *: ...

#

diclll_BLim [thisISO_] = list ((None,) * 8)


---

Thanks in anticipation.

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


Are there Python modules that allow a program to write to the screen?

2021-04-25 Thread Stephen Tucker
Hi,

I have old software written in GWBASIC that I use to plot diagrams on the
screen.

In Windows 10, I have to resort to using the DOSBox emulator to run it.

I would dearly like to re-write it in Python - ideally Python 2.7.

What, if anything, is available?

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


Re: Simple question - end a raw string with a single backslash ?

2020-10-19 Thread Stephen Tucker
For a neatish way to get a string to end with a single backslash, how about
   mystr = r"abc\ "[:-1]
(Note the space at the end of the rough-quoted string.)



Virus-free.
www.avast.com

<#DAB4FAD8-2DD7-40BB-A1B8-4E2AA1F9FDF2>

On Mon, Oct 19, 2020 at 9:26 AM Antoon Pardon  wrote:

>
>
> Op 13/10/20 om 15:14 schreef Serhiy Storchaka:
> > 13.10.20 11:52, Tony Flury via Python-list пише:
> >> I am trying to write a simple expression to build a raw string that ends
> >> in a single backslash. My understanding is that a raw string should
> >> ignore attempts at escaping characters but I get this :
> >>
> >>  >>> a = r'end\'
> >>File "", line 1
> >>  a = r'end\'
> >>^
> >> SyntaxError: EOL while scanning string literal
> >>
> >> I interpret this as meaning that the \' is actually being interpreted as
> >> a literal quote - is that a bug ?
> >
> > r'You can\'t end raw string literal with a single "\"'
> >
> > If backslash be true inner in a raw string, the above literal would end
> > after \'. It would be very hard to write a raw string containing both \'
> > and \", and even \''' and \""" (there are such strings in the stdlib).
> >
> > So you have problem either with trailing backslash, or with inner
> > backslash followed by quotes. Both problems cannot be solved at the same
> > time. Python parser works as it works because initially it was easier to
> > implement, and now this cannot be changed because it would break some
> > amount of correct code.
>
> IMO the way python does this is broken.
>
>  >>> st=r'You can\'t end raw string literal with a single "\"'
>  >>> print(st)
>
> Now either the \ is special or it is not.
>
> 1) If it is special, it should change how the ' is treated but not
> appear itself.
>
> 2) If it is not special, it should just appear and not change how the '
> is treated.
>
> What python does here is a combination of both. The \ appears and it
> changes how the ' is treated. That is IMO broken.
>
> --
> Antoon Pardon.
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Exceptions versus Windows ERRORLEVEL

2020-04-06 Thread Stephen Tucker
Thanks, Eryk - this is very helpful.

Stephen.

On Mon, Apr 6, 2020 at 6:43 AM Eryk Sun  wrote:

> On 4/3/20, Stephen Tucker  wrote:
> >
> > Does an exception raised by a Python 3.x program on a Windows machine set
> > ERRORLEVEL?
>
> ERRORLEVEL is an internal state of the CMD shell. It has nothing to do
> with Python. If Python exits due to an unhandled exception, the
> process exit code will be 1. If CMD waits on the process, it will set
> the ERRORLEVEL based on the exit code. But CMD doesn't always wait. By
> default its START command doesn't wait. Also, at the interactive
> command prompt it doesn't wait for non-console applications such as
> "pythonw.exe"; it only waits for console applications such as
> "python.exe".
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Exceptions versus Windows ERRORLEVEL

2020-04-03 Thread Stephen Tucker
Hi,

I have found that raising an exception in a Python 2.7.10 program running
under Windows does not set ERRORLEVEL.

I realise that Python 2.x is no longer supported.

Does an exception raised by a Python 3.x program on a Windows machine set
ERRORLEVEL?

If not, are there plans for it to do so?

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


Re: Multiple comparisons in a single statement

2020-03-16 Thread Stephen Tucker
OK. You are right. I was misleading.

I am sorry for wasting your time.

Thanks you for helping me to express myself.

Stephen.



<https://www.avast.com/sig-email?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=webmail>
Virus-free.
www.avast.com
<https://www.avast.com/sig-email?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=webmail>
<#DAB4FAD8-2DD7-40BB-A1B8-4E2AA1F9FDF2>

On Fri, Mar 13, 2020 at 7:05 PM Dennis Lee Bieber 
wrote:

> On Fri, 13 Mar 2020 09:34:35 +, Stephen Tucker  >
> declaimed the following:
>
> >
> >*All:  *For the record, I meant that the tuples are all the same. The
>
>
> "all the same" is still ambiguous...
>
> >>> str1 = "A String"
> >>> str2 = "Another String"
> >>> str3 = "A" + " " + "String"
> >>> id(str1), id(str2), id(str3)
> (105461360, 105461296, 105461232)
> >>> tpl1 = (str1, str2)
> >>> tpl2 = (str1, str2)
> >>> tpl3 = (str3, str2)
> >>> id(tpl1), id(tpl2), id(tpl3)
> (90094216, 90094152, 90093576)
> >>> tpl1 == tpl2
> True
> >>> tpl1 == tpl3
> True
> >>> tpl4 = tpl3
> >>> tpl4 == tpl3
> True
> >>> tpl1 is tpl2
> False
> >>> tpl1 is tpl3
> False
> >>> tpl1 is tpl4
> False
> >>> tpl3 is tpl4
> True
> >>>
>
> tpl3 IS THE SAME as tpl4
> tpl1 is NOT THE SAME as tpl2, tpl3, or tpl4
>
> However, the CONTENTS of tpl4 compare as equivalent to tpl1, tpl2, and tpl3
>
>
> --
> Wulfraed Dennis Lee Bieber AF6VN
> wlfr...@ix.netcom.com
> http://wlfraed.microdiversity.freeddns.org/
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Multiple comparisons in a single statement

2020-03-13 Thread Stephen Tucker
*Chris:*   Thank you for your confirmation.

*All:  *For the record, I meant that the tuples are all the same. The
tuples I have in mind contain strings, so the issue regarding the
"equality" (or otherwise) of 0 and 0.0 does not arise in my case.

Stephen.




To answer the question

On Thu, Mar 12, 2020 at 11:26 PM John Pote 
wrote:

>
> On 12/03/2020 18:08, Chris Angelico wrote:
> > On Fri, Mar 13, 2020 at 4:55 AM Stephen Tucker 
> wrote:
> >> A quickie (I hope!).
> >>
> >> I am running Python 2.7.10 (and, yes, I know, support for it has been
> >> withdrawn.)
> > This is the same in Python 3.
> >
> >> I have three tuples that have been generated separately and I want to
> check
> >> that they are identical. all I want to do is to terminate the program
> and
> >> report an error if all three are not identical.
> >>
> >> My initial attempt to do this is to use logic of the form
> >>
> >> if not (mytup1 == mytup2 == mytup3):
> >> raise Exception ("Tuples are not identical")
> >>
> >> I have tried this logic form in IDLE, and it seems to do what I want.
> >>
> >> Is this a reasonable way to do this, or is there a better way?
> >>
> > Yes absolutely! (Although, as a minor quibble, I would say "equal"
> > rather than "identical" here - when you talk about identity, you're
> > usually using the 'is' operator.) The meaning of chained comparisons
> > is broadly equivalent to comparing the middle one against the others
> > ("a==b==c" is "a==b and b==c"), which does the right thing here.
> >
> > It's slightly unusual to negate a query rather than using "!=", but it
> > makes good sense here.
>
> In case anyone thinks the original expr
>   not (mytup1 == mytup2 == mytup3)
> could be changed to
>   (mytup1 != mytup2!= mytup3)
> remember that applying De Morgan's theorem to the original expression
> would require the 'and' operation used in chained comparisons to change
> to an 'or' operation (Python always does the 'and' operation in chained
> comparisions). EG for simple integers instead of tuples,
>
>  >>> not (1==1==1)
> False
>  >>> not (2==1==1)
> True
>  >>> (1!=1!=1)
> False  correct as before
>  >>> (2!=1!=1)
> False  oops!
>
> John
>
> >
> > ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Multiple comparisons in a single statement

2020-03-12 Thread Stephen Tucker
A quickie (I hope!).

I am running Python 2.7.10 (and, yes, I know, support for it has been
withdrawn.)

I have three tuples that have been generated separately and I want to check
that they are identical. all I want to do is to terminate the program and
report an error if all three are not identical.

My initial attempt to do this is to use logic of the form

if not (mytup1 == mytup2 == mytup3):
   raise Exception ("Tuples are not identical")

I have tried this logic form in IDLE, and it seems to do what I want.

Is this a reasonable way to do this, or is there a better way?

Thanks in anticipation.

Stephen Tucker.


<https://www.avast.com/sig-email?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=webmail>
Virus-free.
www.avast.com
<https://www.avast.com/sig-email?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=webmail>
<#DAB4FAD8-2DD7-40BB-A1B8-4E2AA1F9FDF2>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Clarification on Immutability please

2020-01-21 Thread Stephen Tucker
Oh dear, I am sorry. I have created quite a storm.

Moreover, I am sorry because I misremembered what I had typed into Idle. My
original tuple only had two elements, not three, so the slicing [:2] didn't
affect the tuple at all - and so the second id() gave the same address as
the first one.

So, yes, I am stupid - or just having senior moments (I am 65, after all).

Stephen.




On Wed, Jan 22, 2020 at 4:30 AM Michael Torrie  wrote:

> On 1/21/20 6:52 PM, Ethan Furman wrote:
> > On 01/21/2020 10:55 AM, Michael Torrie wrote:
> >
> >> Slicing
> >> returns a new object whether one is slicing a tuple, list, or a string,
> >> the latter two are mutable objects.
> >
> > Strings are not mutable.
>
> Yup I got my items in the wrong order. I meant to say list, tuple, or a
> string, the latter two are immutable objects.  Thanks for correcting me.
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Clarification on Immutability please

2020-01-21 Thread Stephen Tucker
Hi Python-list folk,

I am sure this has been answered many times before, but I need to ask it
again.

Given that the following is valid Python 2.7.10 (when keyboarded into Idle):

mytup = ("q", "w", "e")
id(mytup)
mytup = mytup [:2]
id(mytup)

and even that the first id(mytup) returns the same address as the second
one, I am left wondering exactly what immutability is.

I am left concluding that mytup is not actually a tuple (even though type
(mytup) tells me that it is).

My only explanation is that mytup is, actually, a pointer to a tuple; the
pointer can't change, but the contents of that pointer (or the data to
which the pointer points) can change.

That said, if I then type

mytup = mytup + ("r", "t")
id(mytup)

I find that this third id call returns a different address from the one
returned by the first two.

Somehow, it seems, tuples can be reduced in length (from the far end)
(which is not what I was expecting), but they cannot be extended (which I
can understand).

I am probably confused, ignorant, stupid, or any combination of the above.

Can you please help me become less so?

Many thanks.

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


Re: The file method read does not "see" CR

2019-12-10 Thread Stephen Tucker
Chris,

Many thanks. The first part of your answer was spot on. I have modified the
program, opening its input file in "rb" mode, and now the program is
working as I intend it to.

I am puzzled by the second part, where you say that the read call will
return one character, if the file is in text mode.

I was expecting this statement to read

   The read call will return one byte if the file is in binary mode.

Given that I *was *opening the file in "r" mode (which, I am assuming, is
"text" mode), then, if your statement is true, I have two more questions:

   1. If CR is a character and I open the file in text mode, then why does
the program not "see" the CR characters?

   2. Does the program not see CR characters under these circumstances
because they do not "count" as characters or for some other reason?

(You have probably spotted that this question 1 is virtually the same as my
original question.)

Stephen.














On Tue, Dec 10, 2019 at 10:39 AM Chris Angelico  wrote:

> On Tue, Dec 10, 2019 at 9:17 PM Stephen Tucker 
> wrote:
> >
> > I am running Python 2.7.10 on a Windows 10 machine. I have written a
> Python
> > program that counts occurrences of bytes in a text file and have run it
> on
> > a small test file. This file has CR-LF sequences at the ends of its
> lines.
> > The Python program counted the LF bytes, but didn't count any CR bytes.
> > Given that the documentation for the read method claims that exactly size
> > bytes are read by each call to the method (in this case, size is 1) does
> > this behaviour constitute a bug?
> >
>
> Are you trying to treat the file as text, or bytes? Are you looking
> for occurrences of bytes, or characters? Make a decision on that, then
> code accordingly. If you want to look for bytes, then open the file in
> binary mode and read it as bytes. If you want to look for characters,
> then you probably shouldn't care about which sort of line ending it
> is, but if you really do, then disable newline processing and examine
> the end of each logical line.
>
> The read call will return one character, if the file is in text mode.
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


The file method read does not "see" CR

2019-12-10 Thread Stephen Tucker
I am running Python 2.7.10 on a Windows 10 machine. I have written a Python
program that counts occurrences of bytes in a text file and have run it on
a small test file. This file has CR-LF sequences at the ends of its lines.
The Python program counted the LF bytes, but didn't count any CR bytes.
Given that the documentation for the read method claims that exactly size
bytes are read by each call to the method (in this case, size is 1) does
this behaviour constitute a bug?

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


Re: Difference between array( [1,0,1] ) and array( [ [1,0,1] ] )

2019-06-21 Thread Stephen Tucker
Markos,

I can explain the difference from a non-numpy point of view - I hope you
will be able to see how this difference affects what you are trying to do
in numpy.

vector_1 is an np.array consisting of a three-element list, with the three
elements being 1, 0 and 1.

vector_2 is an np.array consisting (at the top level) of a one-element
list, with that element (at this top level) being a three-element list,
with these three elements (at the lower level) being 1, 0 and 1.

Stephen.




On Fri, Jun 21, 2019 at 7:29 AM Markos  wrote:

>
> Hi,
>
> I'm studying Numpy and I don't understand the difference between
>
> >>> vector_1 = np.array( [ 1,0,1 ] )
>
> with 1 bracket and
>
> >>> vector_2 = np.array( [ [ 1,0,1 ] ] )
>
> with 2 brackets
>
> The shape of vector_1 is:
>
> >>> vector_1.shape
> (3,)
>
> But the shape of vector_2 is:
>
> >>> vector_2.shape
> (1, 3)
>
> The transpose on vector_1 don't work:
>
> >>> vector_1.T
> array([1, 0, 1])
>
> But the transpose method in vector_2 works fine:
>
> >>> vector_2.T
> array([[1],
> [0],
> [1]])
>
>
> I thought that both vectors would be treated as an matrix of 1 row and 3
> columns.
>
> Why this difference?
>
> Any tip?
>
> Thank you,
> Markos
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Question about floating point

2018-08-28 Thread Stephen Tucker
Hi Frank,

One difference is that, in order to carry out the instructions embodied in
the first example, the computer has to perform arithmetic. And it adds the
binary approximation of 1.1 (which is very slightly wrong) to the binary
approximation of 2.2 (which, again, is very slightly wrong). It then prints
the denary equivalent to the sum of those two which happens to be very
slightly more than 3.3.

When you type 3.3, it stores that as the binary approximation of 3.3 (which
is y at that stage, to answer your question, and is, again, no surprise,
also very slightly wrong) and then prints the denary equivalent of that
binary approximation which happens to end up sufficiently close to 3.3 so
as to cause it to print 3.3.

I hope that helps.

The experts around here (of which I am not one) may well point you to the
decimal  package which allows better handling of such arithmetic, if you
are want the computer to behave more like you would want it to behave.

Regards,

Stephen Tucker.








On Tue, Aug 28, 2018 at 3:11 PM, Frank Millman  wrote:

> Hi all
>
> I know about this gotcha -
>
> x = 1.1 + 2.2
>>>> x
>>>>
>>> 3.3003
>
> According to the docs, the reason is that "numbers like 1.1 and 2.2 do not
> have exact representations in binary floating point."
>
> So when I do this -
>
> y = 3.3
>>>> y
>>>>
>>> 3.3
>
> what exactly is happening? What is 'y' at this point?
>
> Or if I do this -
>
> z = (1.1 + 2.2) * 10 / 10
>>>> z
>>>>
>>> 3.3
>
> What makes it different from the first example?
>
> Thanks
>
> Frank Millman
>
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Learning Python

2018-06-05 Thread Stephen Tucker
I have found Learning Python by Mark Lutz helpful. I have the 4th edition
(2009). Its ISBN is 978-0-596-15806-4.

A lot will depend on your learning style. This book reads more like a set
of course notes than a reference book, but it does contain tables and
summaries, too.

On Tue, Jun 5, 2018 at 5:51 PM, T Berger  wrote:

> Can someone learn Python through a book such as Head Start Python? Would
> an online course from MIT or google be better?
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: integer copy

2017-10-20 Thread Stephen Tucker
ast,

For what it's worth,

After

a = 5
b = 5
afloat = float(a)
bfloat = float(b)

afloat is bfloat

returns False.

Stephen Tucker.


On Fri, Oct 20, 2017 at 9:58 AM, ast  wrote:

>
> "ast"  a écrit dans le message de
> news:59e9b419$0$3602$426a7...@news.free.fr...
>
> Neither works for large integers which is
> even more disturbing
>
> a = 6555443
>
> b = copy.copy(a)
> a is b
>
> True
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to write raw strings to Python

2017-07-05 Thread Stephen Tucker
Sam,

You use

f.write(r'hello\tworld')

The r in front of the string stands for raw and is intended to switch off
the escape function of the backslash in the string. It works fine so long
as the string doesn't end with a backslash, as in

f.write('hello\tworld\')

If you try this, you get an error message.

Stephen.




Virus-free.
www.avast.com

<#DAB4FAD8-2DD7-40BB-A1B8-4E2AA1F9FDF2>

On Wed, Jul 5, 2017 at 3:37 PM, Sam Chats  wrote:

> I want to write, say, 'hello\tworld' as-is to a file, but doing
> f.write('hello\tworld') makes the file
> look like:
> hello   world
>
> How can I fix this? Thanks in advance.
>
> Sam
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to write raw strings to Python

2017-07-05 Thread Stephen Tucker
Sam,

You use

r'hello\tworld'

The r in front of the string stands for raw and it is intended to switch
off the normal escape function of a backslash. It works fine so long as the
string doesn't end with a backslash. If you end the string with a
backslash, as in

r'hello\tworld\'

you get an error message.

Stephen.



Virus-free.
www.avast.com

<#DAB4FAD8-2DD7-40BB-A1B8-4E2AA1F9FDF2>

On Wed, Jul 5, 2017 at 3:37 PM, Sam Chats  wrote:

> I want to write, say, 'hello\tworld' as-is to a file, but doing
> f.write('hello\tworld') makes the file
> look like:
> hello   world
>
> How can I fix this? Thanks in advance.
>
> Sam
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how to add new tuple as key in dictionary?

2017-06-30 Thread Stephen Tucker
Hello there, Ho Yeung Lee,

The use of groupkey[tuple([0,3])] to the right of the = is attempting to
access an entry in your dictionary that you have not already created. That
is why you are getting the error message.
You need to create an entry whose key is tuple([0,3]) before you can access
it. The following code does not provoke an error message:

groupkey = {(0,0): []}
groupkey = {tuple([0,3]): []}
groupkey[tuple([0,3])] = groupkey[tuple([0,3])] + [[0,1]]

I hope this helps you.

Stephen.





Virus-free.
www.avast.com

<#DAB4FAD8-2DD7-40BB-A1B8-4E2AA1F9FDF2>

On Fri, Jun 30, 2017 at 11:35 AM, Ho Yeung Lee  wrote:

> I find that list can not be key in dictionary
> then find tuple can be as key
>
> but when I add new tuple as key , got error in python 2.7
>
> groupkey = {(0,0): []}
> groupkey[tuple([0,3])] = groupkey[tuple([0,3])] + [[0,1]]
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Unhelpful error message

2017-06-06 Thread Stephen Tucker
Hi,

I have just been thrown through an unecessary loop because of an unhelpful
error message.

I am running Python 2.7.10 on a Windows 10 machine.

I incorporate sample output from IDLE:

~~~

>>> print float ("123.456")
123.456
>>> print float ("")

Traceback (most recent call last):
  File "", line 1, in 
print float ("")
ValueError: could not convert string to float:
>>>

~~~
The unhelpful message is the response that the system gives when you try to
convert a null string to a floating point number. Now, in the example I
have given here, it is obvious that the string is null, but in the example
that threw me into a loop, it was not obvious.

It would be more helpful is the system replied:

ValueError: could not convert null string to float

Any chance of that becoming the case?

Stephen Tucker.


<https://www.avast.com/sig-email?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=webmail>
Virus-free.
www.avast.com
<https://www.avast.com/sig-email?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=webmail>
<#DAB4FAD8-2DD7-40BB-A1B8-4E2AA1F9FDF2>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help Please ! Undocumented ERROR message so dont know how to fix the problem

2017-05-03 Thread Stephen Tucker
To murdock: What Rhodri wrote is correct. I sense that it might be helpful
for you if I were to tell you that there is a difference between a function
and a function call. If your function were named

MyFunction

then

print (MyFunction)

would print a user-friendly-ish message about the function. This message
tells you (a) that the object you are asking Python to print is a function,
and (b) the address (in hexadecimal) in memory where the code for
MyFunction is stored. This is what your code is doing - hence the message
from Python.

If, on the other hand you have

print (MyFunction(any-parameters-to-MyFunction-with-commas-between-them))

then Python would recognise that (a) you are wanting it to call MyFunction
with the specified parameters, if any, (b) you are expecting that the
function will return a printable result, and (c) you are also expecting it
to print that result.

So, in order to get Python to do that, all you need to do is:

(1) to add the parentheses after the function name in the print statement [
so print (MyFunction) becomes print (MyFunction()) ];

(2) If your function has any parameters, add them, separated with commas,
between the parentheses [ so print (MyFunction()) becomes print
(MyFunction(parameters-separated-with-commas)) ];

(3) and rerun the new code - which should then do what you are wanting it
to do.

I hope this helps.

Stephen Tucker.









<https://www.avast.com/sig-email?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=webmail>
Virus-free.
www.avast.com
<https://www.avast.com/sig-email?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=webmail>
<#DAB4FAD8-2DD7-40BB-A1B8-4E2AA1F9FDF2>

On Tue, May 2, 2017 at 2:11 PM, Rhodri James  wrote:

> On 02/05/17 03:57, murdock wrote:
>
>> I am having a problem that seems to persist. I have written a program
>> that makes a mathematical calculation and uses a uses library that I have
>> written. It had been working but somehow in playing around with it, it
>> stoppedgo figure!  But here is the thing, when I run the program it
>> gives me a very ambiguous message with only a string as in:
>>
>> "The Receiver Noise Figure =  > 0x063E5A60>  dBm"
>>
>
> This is not an error message.  This is Python faithfully printing out what
> you asked it to print out.  Here's the line that does the printing:
>
> print ("The Receiver Noise Figure = ",Hamath._Noise_Figure," dBm" )
>
> The weird-looking bit of the message is the representation of a function,
> and lo! in the parameters to print() there is the function
> Hamath._Noise_Figure.  Note that this is the function itself, *not* the
> result of calling it, since you *don't* call it.
>
> --
> Rhodri James *-* Kynesim Ltd
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: calling a program from Python batch file

2016-12-07 Thread Stephen Tucker
This might be totally irrelevant, but, if (a) the data to be read by the
program during a given run is known when the program is run/launched, (b)
that data is purely textual and (c) that data can be read by the program
from the stdin channel, then my idea is (1) before the launch, put that
data into a file named, say, inputfile.dat, and then (2)  launch the
program with a command like

call program.bat outputfile.dat

Finally, if the program can read its data from a given file and possibly
needs to output its data, again, to a named file, and those files' names
can be read from the parameters to the call, then

call program.bat inputfile.dat outputfile.dat

can be used.








On Wed, Dec 7, 2016 at 6:23 PM, Michael Torrie  wrote:

> On 12/07/2016 10:59 AM, John Gordon wrote:
> > In  Karim
> Farokhnia  writes:
> >
> >> Hi there,
> >
> >> I am writing a batch file in Python. The batch file, in part, calls a
> >> program named "oq-console.bat" to run. Then once the program comes up
> >> (it looks like windows CMD), I need the batch file to type some commands
> >> to make it run (just like I would do it by myself).
> >
> > If you need to start up a program, provide interactive input to it, and
> > perhaps examine its interactive output, then you want the "pexpect"
> module:
> >
> > Pexpect is a pure Python module for spawning child applications;
> > controlling them; and responding to expected patterns in their
> output.
> > Pexpect allows your script to spawn a child application and control
> it
> > as if a human were typing commands.
> >
> > https://pexpect.readthedocs.io/en/stable/
>
> Does Pexpect work on Windows?
>
> In the OP's case it looks like the standard in pipe is sufficient.
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Quick way to calculate lines of code/comments in a collection of Python scripts?

2016-10-24 Thread Stephen Tucker
Tomasz,

How about using the command prompt command FIND /C  on each of your source
files as follows:

FIND/C "#" >NumbersOfLinesContainingPythonComments.dat
FIND/C /V "#" >NumbersOfLinesNotContainingPythonComments.dat

You would end up with two files each with a column of line counts;

Import these lines into an Excel Spreadsheet and calculate whatever you
like with them.

Stephen.



On Sun, Oct 23, 2016 at 9:51 PM, Tomasz Rola  wrote:

> On Wed, Oct 05, 2016 at 01:56:59PM -0400, Malcolm Greene wrote:
> > Looking for a quick way to calculate lines of code/comments in a
> > collection of Python scripts. This isn't a LOC per day per developer
> > type analysis - I'm looking for a metric to quickly judge the complexity
> > of a set of scripts I'm inheriting.
> >
> > Thank you,
> > Malcolm
>
> A bit more than what you asked for (and sorry for being late) but I
> find sloccount quite good. Or at least interesting (computes sloc and
> some stats about project, given project dir or a single file with
> code):
>
> http://www.dwheeler.com/sloccount/
>
> --
> Regards,
> Tomasz Rola
>
> --
> ** A C programmer asked whether computer had Buddha's nature.  **
> ** As the answer, master did "rm -rif" on the programmer's home**
> ** directory. And then the C programmer became enlightened...  **
> ** **
> ** Tomasz Rola  mailto:tomasz_r...@bigfoot.com **
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Doubled backslashes in Windows paths

2016-10-07 Thread Stephen Tucker
Hi Oz,

This might only be tangential to your actual issue, but, there again, it
might be the tiny clue that you actually need.

In Python, I use raw strings and single backslashes in folder hierarchy
strings to save the problem of the backslash in ordinary strings. Even with
this policy, however, there is a slight "gotcha": Although it is claimed
that r" ... " suspends the escape interpretation of the backslash in the
string, a raw string cannot end with a backslash:

   myraw = "\a\b\"

provokes the error message:

   SyntaxError: EOL while scanning string literal

To see how well this approach deals with folder hierarchies with spaces in
their names, I created the following file:

c:\Python27\ArcGIS10.4\Lib\idlelib\sjt\sp in\test.txt

Note the space in the folder name  sp in .

In IDLE, I then issued the following statement:

infile= open (r"c:\Python27\ArcGIS10.4\Lib\idlelib\sjt\sp in\test.txt", "r")

Note that I didn't need to get enclosing quotes into my folder hierarchy
string. It begins with  c  and ends with  t .

The statement worked as you might expect, and granted me access to the
lines in the file.

It seems that it is only necessary to enclose a folder hierarchy string in
quotes when defining the string in a situation in which spaces would
otherwise be interpreted as terminators. The classis case of this is in a
command with parameters in a batch file. If the string has been defined
before it is presented to the Windows Command interpreter, the spaces are
accepted as part of it without the need then of enclosing quotes.

Hope this helps.

Yours,

Stephen Tucker.


On Fri, Oct 7, 2016 at 6:30 AM, Oz-in-DFW  wrote:

> I'm using Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC
> v.1900 32 bit (Intel)] on Windows 7
>
> I'm trying to write some file processing that looks at file size,
> extensions, and several other things and I'm having trouble getting a
> reliably usable path to files.
>
> The problem *seems* to be doubled backslashes in the path, but I've read
> elsewhere that this is just an artifact of the way the interpreter
> displays the strings.
>
> I'm getting an error message on an os.path.getsize call;
>
> Path: -
> "C:\Users\Rich\Desktop\2B_Proc\2307e60da6451986dd8d23635b845386.jpg" -
> Traceback (most recent call last):
>   File "C:\Users\Rich\workspace\PyTest\test.py", line 19, in 
> if os.path.getsize(path)>1:
>   File "C:\Python32\lib\genericpath.py", line 49, in getsize
> return os.stat(filename).st_size
> WindowsError: [Error 123] The filename, directory name, or volume
> label syntax is incorrect:
> '"C:\\Users\\Rich\\Desktop\\2B_Proc\\2307e60da6451986dd8d23635b8453
> 86.jpg"'
>
> From (snippet)
>
> path = '"'+dirpath+name+'"'
> path = os.path.normpath(path)
> print("Path: -",path,"-")
> if os.path.getsize(path)>1:
> print("Path: ",path," Size:
> ",os.path.getsize(dirpath+name))
>
> but if I manually use a console window and cut and paste the path I
> print, it works;
>
> C:\>dir
> "C:\Users\Rich\Desktop\2B_Proc\2307e60da6451986dd8d23635b845386.jpg"
>  Volume in drive C is Windows7_OS
>
>  Directory of C:\Users\Rich\Desktop\2B_Proc
>
> 10/03/2016  08:35 AM59,200
> 2307e60da6451986dd8d23635b845386.jpg
>1 File(s) 59,200 bytes
>0 Dir(s)  115,857,260,544 bytes free
>
> So the file is there and the path is correct. I'm adding quotes to the
> path to deal with directories and filenames that have spaces in them.
> If I drop the quotes, everything works as I expect *until* I encounter
> the first file/path with spaces.
>
> I'll happily RTFM, but I need some hints as to which FM to R
>
> --
> mailto:o...@ozindfw.net
> Oz
> POB 93167
> Southlake, TX 76092 (Near DFW Airport)
>
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: degrees and radians.

2016-08-24 Thread Stephen Tucker
For what it's worth, mathematicians naturally work with angles in radians.

The mathematics of the trignonmetric functions works naturally when the
angle is expressed in radians.

For the older among us, logarithms also have a "natural" base, and that is
the number e. Back in those days, however, even the mathematicians would
use logarithm tables where the values were shown to base 10.


On Wed, Aug 24, 2016 at 6:26 AM, Steven D'Aprano <
steve+comp.lang.pyt...@pearwood.info> wrote:

> On Wednesday 24 August 2016 14:26, Gary Herron wrote:
>
> > Do you really need anything more complex than this?
> >
> >  >>> toRadians = math.pi/180.0
> >
> >  >>> math.sin(90*toRadians)
> > 1.0
> >
> > Perhaps I'm not understanding what you mean by "clunky",  but this seems
> > pretty clean and simple to me.
>
> The math module has two conversion functions, math.radians() and
> math.degrees().
>
>
> Some other languages (Julia, by memory, and perhaps others) have dedicated
> sind(), cosd(), tand() or possibly dsin(), dcos(), dtan() functions which
> take
> their argument in degrees and are more accurate than doing a conversion to
> radians first. I'd like to see that.
>
> I've also seen languages with sinp() etc to calculate the sine of x*pi
> without
> the intermediate calculation.
>
> But if I were designing Python from scratch, I'd make sin(), cos() and
> tan()
> call dunder methods __sin__ etc:
>
>
> def sin(obj):
> if hasattr(type(obj), '__sin__'):
> y = type(obj).__sin__()
> if y is not NotImplemented:
> return y
> elif isinstance(obj, numbers.Number):
> return float.__sin__(float(obj))
> raise TypeError
>
> Likewise for asin() etc.
>
> Then you could define your own numeric types, such as a Degrees type, a
> PiRadians type, etc, with their own dedicated trig function
> implementations,
> without the caller needing to care about which sin* function they call.
>
>
>
>
> --
> Steve
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Self Learning Fortran Programming

2016-06-01 Thread Stephen Tucker
Hi, there, Muhammad,

I have found Learning Python by Mark Lutz helpful. The fourth edition
covers both Python 2.6 and 3.x. Although it is a text book for a course
that Mark delivers, there are useful summaries of the various functions and
methods for strings, integers, etc at various spots in the book.

Stephen Tucker.

<https://www.avast.com/sig-email?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=webmail>
Virus-free.
www.avast.com
<https://www.avast.com/sig-email?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=webmail>
<#DDB4FAA8-2DD7-40BB-A1B8-4E2AA1F9FDF2>

On Wed, Jun 1, 2016 at 6:47 AM, Joel Goldstick 
wrote:

> start here:
>
>
> https://www.python.org/about/gettingstarted/
>
> On Wed, Jun 1, 2016 at 12:50 AM, Muhammad Ali
>  wrote:
> >
> > Hello,
> >
> > I am interested in Python programming, however, it will be my first
> serious attempt towards coding/simulation/programming. My back ground is
> Physics, no practical experience with programming languages.
> >
> > So, this post is for the valuable suggestions from the experts that how
> can I start self learning Python from scratch to advanced level in minimum
> time. For this, please recommend Python version, literature, text books,
> websites, video lectures, your personnel tips, etc. In addition, you may
> also add some extra suggestions for shell script writing as well. You may
> recommend for both Linux and Windows operating systems.
> >
> > Looking for your posts.
> >
> > Thank you.
> > --
> > https://mail.python.org/mailman/listinfo/python-list
>
>
>
> --
> Joel Goldstick
> http://joelgoldstick.com/blog
> http://cc-baseballstats.info/stats/birthdays
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: find all multiplicands and multipliers for a number

2015-04-10 Thread Stephen Tucker
Dario Alpern has written a program that uses the Elliptic Curve Method
(ECM) for factorising a number. ECM is one of the _very_ fast methods for
finding the prime factors of a number. He has even offered the code for his
program. You could have a go at using or converting his code to do what you
are wanting to do. The URL for this is

http://www.alpertron.com.ar/ECM.HTM

This program found the prime factors of  2^111+1  in less than 1 second on
my computer. (And that is the string I gave it.)

What has been said by previous contributors about the difficulty of
factorising numbers is all true. However, there are some relatively fast
algorithms out there. Try searching for

Number Field Sieve
Quadratic Number Field Sieve

and see where they take you.



On Sat, Apr 11, 2015 at 3:04 AM, Steven D'Aprano <
steve+comp.lang.pyt...@pearwood.info> wrote:

> On Sat, 11 Apr 2015 11:06 am, Dave Angel wrote:
>
> > But the real place to get improvement is to only divide by primes,
> > rather than every possible integer.  And once you've done the division,
> > let q be the next value for dividend.  So you'll get a list like
> >
> > [3, 3, 3, 37]
> >
> > for the value 999
>
>
> Prime factorization is a *hard* problem. If it wasn't, most of modern
> technology that relies on encryption (like https, ssh, internet banking
> etc.) would be trivially broken.
>
> But for what it is worth, my pyprimes library can return the prime
> factorization of numbers:
>
> py> import pyprimes.factors
> py> pyprimes.factors.factorise(1234567890)
> [2, 3, 3, 5, 3607, 3803]
> py> pyprimes.factors.factorise(9753124680)
> [2, 2, 2, 3, 3, 3, 5, 13, 191, 3637L]
>
> It may be a bit slow for very large numbers. On my computer, this takes 20
> seconds:
>
> py> pyprimes.factors.factorise(2**111+1)
> [3, 3, 1777, 3331, 17539, 25781083, 107775231312019L]
>
>
> but that is the nature of factorising large numbers.
>
>
> http://code.google.com/p/pyprimes/source/browse/
>
>
>
> --
> Steven
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Challenge: optimizing isqrt

2014-11-26 Thread Stephen Tucker
Another _possible_ performance improvement that is staring us in the face
is that 2*b could be replaced with b<<1. Given that b+b (an earlier
suggestion of mine) involves two table look-ups for b, whereas b<<1 only
involves one, it seems that the scope here for improvement is significant.

By the way, I hope this post is not "top-posted" as my previous one was.
Apologies for that - I am new to this kind of thing.



On Wed, Nov 26, 2014 at 12:46 AM, Dave Angel  wrote:

> On 11/25/2014 02:31 PM, Serhiy Storchaka wrote:
>
>> п'ятниця, 21-лис-2014 08:15:57 ви написали:
>>
>>> This looks very good indeed. As a matter of interest, is there any
>>> particular reason you have used 2*b instead of b+b? Might b+b be faster
>>> than b*2?
>>>
>>
>> Yes, it is slightly faster, but the effect is indiscernible in total
>> time. But
>> there is not harm to use b+b.
>>
>>  Also, in various lines, you use //2. Would >>1 be quicker? On reflection,
>>> perhaps you have had to use //2 because >>1 cannot be used in those
>>> situations.
>>>
>>
>> I thought this effect would be insignificant too. But actually it is
>> measurable
>> (about 10% for some input). Thanks, this optimization is worth to be
>> applied.
>>
>>
> Unfortunately, for many values, the version of the function with >>1 is
> slower.  It's only when the argument is bigger than 10**40 that it's as
> much as 1% faster.  But it's true that for really large values, it's
> quicker.
>
> A quick test shows that 3.3 is about 20% faster for both these functions
> than 2.7.
>
> My oversight earlier was assuming a native type.  Once you get into
> "longs" which aren't supported by the processor, the shift will likely
> become much faster than divide.
>
>
> --
> DaveA
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Challenge: optimizing isqrt

2014-11-23 Thread Stephen Tucker
Serhiy,

This looks very good indeed. As a matter of interest, is there any
particular reason you have used 2*b instead of b+b? Might b+b be faster
than b*2?

Also, in various lines, you use //2. Would >>1 be quicker? On reflection,
perhaps you have had to use //2 because >>1 cannot be used in those
situations.

Stephen Tucker.




On Thu, Nov 20, 2014 at 6:00 PM, Serhiy Storchaka 
wrote:

> On 01.11.14 03:29, Steven D'Aprano wrote:
>
>> There is an algorithm for calculating the integer square root of any
>> positive integer using only integer operations:
>>
>
> Here is my optimized implementation inspired by Christian's ideas.
>
> import math, sys
>
> C1 = sys.float_info.radix ** sys.float_info.mant_dig
> C2 = int(sys.float_info.max)
> C3 = C2.bit_length() - 2
>
> def isqrt(n):
> if n < 0:
> raise ValueError
> if n == 0:
> return 0
> if n <= C1:
> return int(math.sqrt(n))
> if n <= C2:
> x = int(math.sqrt(n))
> else:
> b = (n.bit_length() - C3) // 2
> x = int(math.sqrt(n >> (2 * b))) << b
> y = (x + n // x) // 2
> if y == x:
> return x
> while True:
> x = y
> y = (x + n // x) // 2
> if y >= x:
> return x
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Unicode Objects in Tuples

2013-10-11 Thread Stephen Tucker
A quick reply to all you contributors (by the way, I was not expecting to
get so many responses so quickly - I am (as you probably realise) new to
this kind of thing.

I am stuck with Python 2.X because ESRI's ArcGIS system uses it -
otherwise, yes, you're all right, I would be in Python 3.X like a shot! So
that rules out any answers to my questions that involve Python 3.X. (Sorry,
perhaps I should have mentioned that at the outset - as I say, I'm new to
all this.)

ESRI compound the problem, actually, by making all the strings that the
ArcGIS Python interface delivers (from MS SQLServer) Unicode! (I suppose,
on reflection, they have no choice.) So I am stuck with the worst of both
worlds - a generation of Python (2.X) that is inept at handling unicode (on
an operating system (MS Windows 7) that is not much better, and being
flooded with unicode strings from my users' databases! Anything you can
come up with to ease all this (like, "convert *all* your strings to unicode
as soon as you can and render them as ASCII as late as you can") has
already been of help.

On the original question, well, I accept Ned's answer (at 10.22). I also
like the idea of a helper function given by Peter Otten at 09.51. It still
seems like a crutch to help poor old Python 2.X to do what any programmer
(or, at least the programmers like me :-)  ) think it ought to be able to
by itself. The distinction between the "geekiness" of a tuple compared with
the "non-geekiness" of a string is, itself, far too geeky for my liking.
The distinction seems to be an utterly spurious - even artificial or
arbitrary one to me. (Sorry about the rant.)




On Fri, Oct 11, 2013 at 10:22 AM, Ned Batchelder wrote:

>  On 10/11/13 4:16 AM, Stephen Tucker wrote:
>
> I am using IDLE, Python 2.7.2 on Windows 7, 64-bit.
>
> I have four questions:
>
> 1. Why is it that
>  print unicode_object
>  displays non-ASCII characters in the unicode object correctly, whereas
>   print (unicode_object, another_unicode_object)
>  displays non-ASCII characters in the unicode objects as escape sequences
> (as repr() does)?
>
>  2. Given that this is actually *deliberately *the case (which I, at the
> moment, am finding difficult to accept), what is the neatest (that is, the
> most Pythonic) way to get non-ASCII characters in unicode objects in tuples
> displayed correctly?
>
>  3. A similar thing happens when I write such objects and tuples to a file
> opened by
>  codecs.open ( ..., "utf-8")
>  I have also found that, even though I use  write  to send the text to the
> file, unicode objects not in tuples get their non-ASCII characters sent to
> the file correctly, whereas, unicode objects in tuples get their characters
> sent to the file as escape sequences. Why is this the case?
>
>  4. As for question 1 above, I ask here also: What is the neatest way to
> get round this?
>
>  Stephen Tucker.
>
>
> Although Python 3 is better than Python 2 at Unicode, as the others have
> said, the most important point is one that you hit upon yourself.
>
> When you print an object x, you are actually printing str(x).  The str()
> of a tuple is a paren, followed by the repr()'s of its elements, separated
> by commas, then a closing paren.  Tuples and lists use the repr() of their
> elements when producing either their own str() or their own repr().
>
> Python 3 does better at this because repr() in Python 3 will gladly
> include non-ASCII characters in its output, while Python 2 will only
> include ASCII characters, and so must resort to escape sequences.  (BTW: if
> you like the ASCII-only idea from Python 2, Python 3 has the ascii()
> function and the %a string formatting directive for that very purpose.)
>
> The two string representation alternatives str() and repr() can be
> confusing.  Think of it as: str() is for customers, repr() is for
> developers, or: str() is for humans, repr() is for geeks.   The reason
> tuples use the repr() of their elements is that the parens+commas
> representation of a tuple is geeky to begin with, so it uses repr() of its
> elements, even for str(tuple).
>
> The way to avoid repr() for the elements is to format the tuple yourself.
>
> --Ned.
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Unicode Objects in Tuples

2013-10-11 Thread Stephen Tucker
I am using IDLE, Python 2.7.2 on Windows 7, 64-bit.

I have four questions:

1. Why is it that
 print unicode_object
displays non-ASCII characters in the unicode object correctly, whereas
 print (unicode_object, another_unicode_object)
displays non-ASCII characters in the unicode objects as escape sequences
(as repr() does)?

2. Given that this is actually *deliberately *the case (which I, at the
moment, am finding difficult to accept), what is the neatest (that is, the
most Pythonic) way to get non-ASCII characters in unicode objects in tuples
displayed correctly?

3. A similar thing happens when I write such objects and tuples to a file
opened by
 codecs.open ( ..., "utf-8")
I have also found that, even though I use  write  to send the text to the
file, unicode objects not in tuples get their non-ASCII characters sent to
the file correctly, whereas, unicode objects in tuples get their characters
sent to the file as escape sequences. Why is this the case?

4. As for question 1 above, I ask here also: What is the neatest way to get
round this?

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


getting rpy2 from repository

2010-02-28 Thread Stephen Tucker
Hi all, I have Enthought Python 4.3 installed on my OS X 10.5. When I do $ 
easy_install rpy2

Searching for rpy2
No matching release version found. Searching for latest development version.
Reading http://www.enthought.com/repo/epd/eggs/MacOSX/10.4_x86/
Please enter credentials to access this repository:
User Name: 

Is there a way to point to the original (non-Enthought) repository, or is there 
a better way?

Thanks very much in advance!

Stephen



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