Re: [Tutor] Puzzled again

2011-08-03 Thread Richard D. Moores
On Wed, Aug 3, 2011 at 12:10, Peter Otten <__pete...@web.de> wrote:
> Richard D. Moores wrote:
>
>> On Wed, Aug 3, 2011 at 10:11, Peter Otten <__pete...@web.de> wrote:
>>> Richard D. Moores wrote:
>>>
 I wrote before that I had pasted the function (convertPath()) from my
 initial post into mycalc.py because I had accidentally deleted it from
 mycalc.py. And that there was no problem importing it from mycalc.
 Well, I was mistaken (for a reason too tedious to go into). There WAS
 a problem, the same one as before.
>>>
>>> Dave was close, but Steven hit the nail: the string r"C:\Users\Dick\..."
>>> is fine, but when you put it into the docstring it is not a raw string
>>> within another string, it becomes just a sequence of characters that is
>>> part of the outer string. As such \U marks the beginning of a special way
>>> to define a unicode codepoint:
>>>
>> "\U0041"
>>> 'A'
>>>
>>> As "sers\Dic", the eight characters following the \U in your docstring,
>>> are not a valid hexadecimal number you get an error message.
>>>
>>> The solution is standard procedure: escape the backslash or use a
>>> rawstring:
>>>
>>> Wrong:
>>>
>> """yadda r"C:\Users\Dick\..." yadda"""
>>> File "", line 1
>>> SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in
>>> position 10-12: truncated \U escape
>>>
>>> Correct:
>>>
>> """yadda r"C:\\Users\Dick\..." yadda"""
>>> 'yadda r"C:\\Users\\Dick\\..." yadda'
>>>
>>> Also correct:
>>>
>> r"""yadda r"C:\Users\Dick\..." yadda"""
>>> 'yadda r"C:\\Users\\Dick\\..." yadda'
>>
>> Here's from my last post:
>>
>> 
>> Now I edit it back to its original problem form:
>>
>> def convertPath(path):
>>    """
>>    Given a path with backslashes, return that path with forward slashes.
>>
>>    By Steven D'Aprano  07/31/2011 on Tutor list
>>    >>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'
>>    >>> convertPath(path)
>>    'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf'
>>    """
>>    import os.path
>>    separator = os.path.sep
>>    if separator != '/':
>>        path = path.replace(os.path.sep, '/')
>>    return path
>>
>> and get
>>
>> C:\Windows\System32>python
>> Python 3.2.1 (default, Jul 10 2011, 20:02:51) [MSC v.1500 64 bit
>> (AMD64)] on win32
>> Type "help", "copyright", "credits" or "license" for more information.
> import mycalc2
>> Traceback (most recent call last):
>>  File "", line 1, in 
>>  File "C:\Python32\lib\site-packages\mycalc2.py", line 10
>>    """
>> SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes
>> in position 144-146: truncated \UXXX
>> X escape
>>
>> Using HxD, I find that the bytes in 144-146 are 20, 54, 75 or  the
>> , 'T', 'u' of  " Tutor" .  A screen shot of HxD with this
>> version of mycalc2.py open in it is at
>> . You can see that I believe the
>> offset integers are base-10 ints. I do hope that's correct, or I've
>> done a lot of work for naught.
>> 
>>
>> So have I not used HxD correctly (my first time to use a hex reader)?
>> If I have used it correctly, why do the reported problem offsets of
>> 144-146 correspond to such innocuous things as 'T', 'u' and ,
>> and which come BEFORE the problems you and Steven point out?
>
> Come on, put that r before the docstring

Yes! That works! Now I've got it. As I told Steven, I didn't
understand that suggestion before, partly
because I had the """ on a separate line, and was also confused by the
"yadda"s.

> def convertPath(path):
>    r"""
>    Given a path with backslashes, return that path with forward slashes.
>    ...
>
> and see the problem go away.

It did!

>The numbers reported by Python are byte offsets
> within the string literal:

Ah, that explains the mystery. Thanks, Peter.

Dick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Puzzled again

2011-08-03 Thread Richard D. Moores
On Wed, Aug 3, 2011 at 12:16, Steven D'Aprano  wrote:
> Richard D. Moores wrote:
>>
>> I wrote before that I had pasted the function (convertPath()) from my
>> initial post into mycalc.py because I had accidentally deleted it from
>> mycalc.py. And that there was no problem importing it from mycalc.
>> Well, I was mistaken (for a reason too tedious to go into). There WAS
>> a problem, the same one as before.
>
> Richard, too much information! Please try to be more concise in your posts.
> Try to find the *simplest* code that demonstrates the problem.

Yes. Sorry.

> E.g. instead of a 14 line function (including docstring) you should be able
> to demonstrate the problem with a TWO liner:
>
> def func():
>    """ text r'aaa\Userswxyzabcd' """
>
> In Python 3, you will get a SyntaxError complaining about a truncated
> \U escape. This comes back to what I said earlier: r' inside another
> string does not start a raw string. (In much the same way that [ inside a
> string does not create a list.) \U instroduces a Unicode escape. Since
> docstrings are unicode in Python 3, and serswxyz are not valid hex digits,
> you get an error.
>
> To fix, you need to either make the whole docstring a raw string:
>
>    r""" text r'aaa\Userswxyzabcd' """

Yes! That works! I didn't understand that suggestion before, partly
because I had the """ on a separate line, and was also confused by the
"yadda"s.

> or you need to escape the backslashes:
>
>    """ text r'aaa\\Userswxyzabcd' """

Well, that's not so good, because it distorts the example I'm giving.
Right? (Hey, I learned to put examples in my docstrings from you.)

> You don't even need to use import to work with this. You can just copy and
> paste the string into an interactive interpreter:
>
> # Python 2:
 s = """ text r'aaa\Userswxyzabcd' """
 print s
>  text r'aaa\Userswxyzabcd'
>
>
> # Python 3:
 s = """ text r'aaa\Userswxyzabcd' """
>  File "", line 1
> SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in
> position 11-13: truncated \U escape
>
> Remember: function docstrings are just ordinary strings. All the rules for
> strings apply equally to docstrings.
>
>
> You also report (in tedious detail!) apparent discrepancies between the
> offsets reported by Python when importing the file, and the actual content
> of the file at those offsets. I'm not even going to attempt to diagnose
> that. Without access to the exact source files, not copy and pasted into an
> email or a pastebin, there is no hope of diagnosing it. It would just be a
> major waste of time and energy.
>
> The most likely cause is that the version of the file you are importing is
> not the same as the version of the file you have open in the hex editor.

No, I made sure that the 2 were the same. HxD has a refresh function,
which I made sure to use (press F5).

> E.g. suppose you open the file in the hex editor. Then you edit the file in
> your text editor, and save changes. Then you import it in Python, which
> reports the offsets according to the version of the file on disk. You look
> at the hex editor, but you're seeing the *old* version, before the changes.
>
> Unless the problem is *reproducible*, i.e. you can repeat it at will,
> there's no way of knowing for sure what happened. (Unless you have a time
> machine and can go back in time to see exactly you did.)
>
> Don't lose any sleep over this sort of thing. We've all done it. My
> favourite is when I'm making incremental edits to a file, but forget to
> reload() changes in the interactive interpreter correctly. Python ends up
> finding an error on (let's say) line 42, but by the time the error is
> reported, line 42 on disk has changed and so the traceback prints a
> completely irrelevant line.
>
> If you *can* reproduce the error at will, e.g. do this:
>
> (1) Take a source file in a known state;
> (2) Import the file into a *freshly started* Python interpreter;

I was always importing into a "freshly started" Python interpreter.

> (3) Python reports an error on some line;
> (4) but the line doesn't seem to have anything to do with that error
>
> and repeat it as often as you like, then it would be worth sharing the file
> for further investigation, by attaching it to an email, not copying and
> pasting the text from it.

OK. I didn't know attachments were permitted on Tutor.  But in looking
at my Tutor archive in Gmail, I see that they are. Thanks.

> Disclaimer: due to the way Python's parser works, sometimes a missing
> parenthesis or bracket will cause a syntax error on the line *following* the
> erroneous line. This is a known limitation.

Happens often to me, because I tend to leave out a ')' or 2 at the end
of a print() statement.

Thanks for all your kind instruction and advice, Steven.

Dick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Puzzled again

2011-08-03 Thread Steven D'Aprano

Richard D. Moores wrote:

I wrote before that I had pasted the function (convertPath()) from my
initial post into mycalc.py because I had accidentally deleted it from
mycalc.py. And that there was no problem importing it from mycalc.
Well, I was mistaken (for a reason too tedious to go into). There WAS
a problem, the same one as before.


Richard, too much information! Please try to be more concise in your 
posts. Try to find the *simplest* code that demonstrates the problem.


E.g. instead of a 14 line function (including docstring) you should be 
able to demonstrate the problem with a TWO liner:


def func():
""" text r'aaa\Userswxyzabcd' """

In Python 3, you will get a SyntaxError complaining about a truncated 
\U escape. This comes back to what I said earlier: r' inside 
another string does not start a raw string. (In much the same way that [ 
inside a string does not create a list.) \U instroduces a Unicode 
escape. Since docstrings are unicode in Python 3, and serswxyz are not 
valid hex digits, you get an error.


To fix, you need to either make the whole docstring a raw string:

r""" text r'aaa\Userswxyzabcd' """

or you need to escape the backslashes:

""" text r'aaa\\Userswxyzabcd' """


You don't even need to use import to work with this. You can just copy 
and paste the string into an interactive interpreter:


# Python 2:
>>> s = """ text r'aaa\Userswxyzabcd' """
>>> print s
 text r'aaa\Userswxyzabcd'


# Python 3:
>>> s = """ text r'aaa\Userswxyzabcd' """
  File "", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in 
position 11-13: truncated \U escape


Remember: function docstrings are just ordinary strings. All the rules 
for strings apply equally to docstrings.



You also report (in tedious detail!) apparent discrepancies between the 
offsets reported by Python when importing the file, and the actual 
content of the file at those offsets. I'm not even going to attempt to 
diagnose that. Without access to the exact source files, not copy and 
pasted into an email or a pastebin, there is no hope of diagnosing it. 
It would just be a major waste of time and energy.


The most likely cause is that the version of the file you are importing 
is not the same as the version of the file you have open in the hex editor.


E.g. suppose you open the file in the hex editor. Then you edit the file 
in your text editor, and save changes. Then you import it in Python, 
which reports the offsets according to the version of the file on disk. 
You look at the hex editor, but you're seeing the *old* version, before 
the changes.


Unless the problem is *reproducible*, i.e. you can repeat it at will, 
there's no way of knowing for sure what happened. (Unless you have a 
time machine and can go back in time to see exactly you did.)


Don't lose any sleep over this sort of thing. We've all done it. My 
favourite is when I'm making incremental edits to a file, but forget to 
reload() changes in the interactive interpreter correctly. Python ends 
up finding an error on (let's say) line 42, but by the time the error is 
reported, line 42 on disk has changed and so the traceback prints a 
completely irrelevant line.


If you *can* reproduce the error at will, e.g. do this:

(1) Take a source file in a known state;
(2) Import the file into a *freshly started* Python interpreter;
(3) Python reports an error on some line;
(4) but the line doesn't seem to have anything to do with that error

and repeat it as often as you like, then it would be worth sharing the 
file for further investigation, by attaching it to an email, not copying 
and pasting the text from it.


Disclaimer: due to the way Python's parser works, sometimes a missing 
parenthesis or bracket will cause a syntax error on the line *following* 
the erroneous line. This is a known limitation.




--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Puzzled again

2011-08-03 Thread Peter Otten
Richard D. Moores wrote:

> On Wed, Aug 3, 2011 at 10:11, Peter Otten <__pete...@web.de> wrote:
>> Richard D. Moores wrote:
>>
>>> I wrote before that I had pasted the function (convertPath()) from my
>>> initial post into mycalc.py because I had accidentally deleted it from
>>> mycalc.py. And that there was no problem importing it from mycalc.
>>> Well, I was mistaken (for a reason too tedious to go into). There WAS
>>> a problem, the same one as before.
>>
>> Dave was close, but Steven hit the nail: the string r"C:\Users\Dick\..."
>> is fine, but when you put it into the docstring it is not a raw string
>> within another string, it becomes just a sequence of characters that is
>> part of the outer string. As such \U marks the beginning of a special way
>> to define a unicode codepoint:
>>
> "\U0041"
>> 'A'
>>
>> As "sers\Dic", the eight characters following the \U in your docstring,
>> are not a valid hexadecimal number you get an error message.
>>
>> The solution is standard procedure: escape the backslash or use a
>> rawstring:
>>
>> Wrong:
>>
> """yadda r"C:\Users\Dick\..." yadda"""
>> File "", line 1
>> SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in
>> position 10-12: truncated \U escape
>>
>> Correct:
>>
> """yadda r"C:\\Users\Dick\..." yadda"""
>> 'yadda r"C:\\Users\\Dick\\..." yadda'
>>
>> Also correct:
>>
> r"""yadda r"C:\Users\Dick\..." yadda"""
>> 'yadda r"C:\\Users\\Dick\\..." yadda'
> 
> Here's from my last post:
> 
> 
> Now I edit it back to its original problem form:
> 
> def convertPath(path):
>"""
>Given a path with backslashes, return that path with forward slashes.
> 
>By Steven D'Aprano  07/31/2011 on Tutor list
>>>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'
>>>> convertPath(path)
>'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf'
>"""
>import os.path
>separator = os.path.sep
>if separator != '/':
>path = path.replace(os.path.sep, '/')
>return path
> 
> and get
> 
> C:\Windows\System32>python
> Python 3.2.1 (default, Jul 10 2011, 20:02:51) [MSC v.1500 64 bit
> (AMD64)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
 import mycalc2
> Traceback (most recent call last):
>  File "", line 1, in 
>  File "C:\Python32\lib\site-packages\mycalc2.py", line 10
>"""
> SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes
> in position 144-146: truncated \UXXX
> X escape
> 
> Using HxD, I find that the bytes in 144-146 are 20, 54, 75 or  the
> , 'T', 'u' of  " Tutor" .  A screen shot of HxD with this
> version of mycalc2.py open in it is at
> . You can see that I believe the
> offset integers are base-10 ints. I do hope that's correct, or I've
> done a lot of work for naught.
> 
> 
> So have I not used HxD correctly (my first time to use a hex reader)?
> If I have used it correctly, why do the reported problem offsets of
> 144-146 correspond to such innocuous things as 'T', 'u' and ,
> and which come BEFORE the problems you and Steven point out?

Come on, put that r before the docstring

def convertPath(path):
r"""
Given a path with backslashes, return that path with forward slashes.
...

and see the problem go away. The numbers reported by Python are byte offsets 
within the string literal:

>>> "\Uinvalidnumber"
  File "", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in 
position 0-2: truncated \U escape
>>> "1\Uinvalidnumber"
  File "", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in 
position 1-3: truncated \U escape
>>> "12\Uinvalidnumber"
  File "", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in 
position 2-4: truncated \U escape
>>> "123\Uinvalidnumber"
  File "", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in 
position 3-5: truncated \U escape


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Puzzled again

2011-08-03 Thread Dave Angel

On 08/03/2011 01:48 PM, Richard D. Moores wrote:

On Wed, Aug 3, 2011 at 10:11, Peter Otten<__pete...@web.de>  wrote:



Dave was close, but Steven hit the nail: the string r"C:\Users\Dick\..." is
fine, but when you put it into the docstring it is not a raw string within
another string, it becomes just a sequence of characters that is part of the
outer string. As such \U marks the beginning of a special way to define a
unicode codepoint:


Here's from my last post:


Now I edit it back to its original problem form:

def convertPath(path):
"""
Given a path with backslashes, return that path with forward slashes.

By Steven D'Aprano  07/31/2011 on Tutor list
>>>  path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'
>>>  convertPath(path)
'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf'
"""



Traceback (most recent call last):
  File "", line 1, in
  File "C:\Python32\lib\site-packages\mycalc2.py", line 10
"""
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes
in position 144-146: truncated \UXXX
X escape

Using HxD, I find that the bytes in 144-146 are 20, 54, 75 or  the
, 'T', 'u' of  " Tutor" .  A screen shot of HxD with this
version of mycalc2.py open in it is at
. You can see that I believe the
offset integers are base-10 ints. I do hope that's correct, or I've
done a lot of work for naught.


So have I not used HxD correctly (my first time to use a hex reader)?
If I have used it correctly, why do the reported problem offsets of
144-146 correspond to such innocuous things as 'T', 'u' and,
and which come BEFORE the problems you and Steven point out?

This one is my fault, for pointing you to the hex viewer.  Peter is 
correct.  But the offset is relative to the beginning of the 
triple-quoted string.
The problem has nothing to do with the encoding of the file itself, but 
instead just with the backslashes inside the triple-quoted string.  
Since you have a \U, the parser also expects 8 hex digits.  The thing 
that threw me was that this particular symptom is specific to Python 
3.x, which I don't normally use.


The following line would have the same problem:

mystring = "abc \Unexpected def"

since the letters nexpecte  don't spell out a valid hexcode.  You would 
instead want


mystring = r"abc \Unexpected def"

--

DaveA

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Puzzled again

2011-08-03 Thread Richard D. Moores
On Wed, Aug 3, 2011 at 10:11, Peter Otten <__pete...@web.de> wrote:
> Richard D. Moores wrote:
>
>> I wrote before that I had pasted the function (convertPath()) from my
>> initial post into mycalc.py because I had accidentally deleted it from
>> mycalc.py. And that there was no problem importing it from mycalc.
>> Well, I was mistaken (for a reason too tedious to go into). There WAS
>> a problem, the same one as before.
>
> Dave was close, but Steven hit the nail: the string r"C:\Users\Dick\..." is
> fine, but when you put it into the docstring it is not a raw string within
> another string, it becomes just a sequence of characters that is part of the
> outer string. As such \U marks the beginning of a special way to define a
> unicode codepoint:
>
 "\U0041"
> 'A'
>
> As "sers\Dic", the eight characters following the \U in your docstring, are
> not a valid hexadecimal number you get an error message.
>
> The solution is standard procedure: escape the backslash or use a rawstring:
>
> Wrong:
>
 """yadda r"C:\Users\Dick\..." yadda"""
>  File "", line 1
> SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in
> position 10-12: truncated \U escape
>
> Correct:
>
 """yadda r"C:\\Users\Dick\..." yadda"""
> 'yadda r"C:\\Users\\Dick\\..." yadda'
>
> Also correct:
>
 r"""yadda r"C:\Users\Dick\..." yadda"""
> 'yadda r"C:\\Users\\Dick\\..." yadda'

Here's from my last post:


Now I edit it back to its original problem form:

def convertPath(path):
   """
   Given a path with backslashes, return that path with forward slashes.

   By Steven D'Aprano  07/31/2011 on Tutor list
   >>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'
   >>> convertPath(path)
   'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf'
   """
   import os.path
   separator = os.path.sep
   if separator != '/':
   path = path.replace(os.path.sep, '/')
   return path

and get

C:\Windows\System32>python
Python 3.2.1 (default, Jul 10 2011, 20:02:51) [MSC v.1500 64 bit
(AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import mycalc2
Traceback (most recent call last):
 File "", line 1, in 
 File "C:\Python32\lib\site-packages\mycalc2.py", line 10
   """
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes
in position 144-146: truncated \UXXX
X escape

Using HxD, I find that the bytes in 144-146 are 20, 54, 75 or  the
, 'T', 'u' of  " Tutor" .  A screen shot of HxD with this
version of mycalc2.py open in it is at
. You can see that I believe the
offset integers are base-10 ints. I do hope that's correct, or I've
done a lot of work for naught.


So have I not used HxD correctly (my first time to use a hex reader)?
If I have used it correctly, why do the reported problem offsets of
144-146 correspond to such innocuous things as 'T', 'u' and ,
and which come BEFORE the problems you and Steven point out?

Dick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Puzzled again

2011-08-03 Thread Peter Otten
Richard D. Moores wrote:

> I wrote before that I had pasted the function (convertPath()) from my
> initial post into mycalc.py because I had accidentally deleted it from
> mycalc.py. And that there was no problem importing it from mycalc.
> Well, I was mistaken (for a reason too tedious to go into). There WAS
> a problem, the same one as before.

Dave was close, but Steven hit the nail: the string r"C:\Users\Dick\..." is 
fine, but when you put it into the docstring it is not a raw string within 
another string, it becomes just a sequence of characters that is part of the 
outer string. As such \U marks the beginning of a special way to define a 
unicode codepoint:

>>> "\U0041"
'A'

As "sers\Dic", the eight characters following the \U in your docstring, are 
not a valid hexadecimal number you get an error message.

The solution is standard procedure: escape the backslash or use a rawstring:

Wrong:

>>> """yadda r"C:\Users\Dick\..." yadda"""
  File "", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in 
position 10-12: truncated \U escape

Correct:

>>> """yadda r"C:\\Users\Dick\..." yadda"""
'yadda r"C:\\Users\\Dick\\..." yadda'

Also correct:

>>> r"""yadda r"C:\Users\Dick\..." yadda"""
'yadda r"C:\\Users\\Dick\\..." yadda'


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Puzzled again

2011-08-03 Thread Richard D. Moores
I wrote before that I had pasted the function (convertPath()) from my
initial post into mycalc.py because I had accidentally deleted it from
mycalc.py. And that there was no problem importing it from mycalc.
Well, I was mistaken (for a reason too tedious to go into). There WAS
a problem, the same one as before.

I now have a hex editor, HxD (),
and have some info to report.

I've left convertPath() in mycalc.py, in importable form, and have
been experimenting with it in a new module, mycalc2.

The first run:

def convertPath(path):
"""
Given a path with backslashes, return that path with forward slashes.

By Steven D'Aprano  07/31/2011 on Tutor list
"""
#>>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'
#>>> convertPath(path)
#'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf'
import os.path
separator = os.path.sep
if separator != '/':
path = path.replace(os.path.sep, '/')
return path

gets

C:\Windows\System32>python
Python 3.2.1 (default, Jul 10 2011, 20:02:51) [MSC v.1500 64 bit
(AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import mycalc2
>>>

Now I edit it back to its original problem form:

def convertPath(path):
"""
Given a path with backslashes, return that path with forward slashes.

By Steven D'Aprano  07/31/2011 on Tutor list
>>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'
>>> convertPath(path)
'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf'
"""
import os.path
separator = os.path.sep
if separator != '/':
path = path.replace(os.path.sep, '/')
return path

and get

C:\Windows\System32>python
Python 3.2.1 (default, Jul 10 2011, 20:02:51) [MSC v.1500 64 bit
(AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import mycalc2
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python32\lib\site-packages\mycalc2.py", line 10
"""
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes
in position 144-146: truncated \UXXX
X escape

Using HxD, I find that the bytes in 144-146 are 20, 54, 75 or  the
, 'T', 'u' of  " Tutor" .  A screen shot of HxD with this
version of mycalc2.py open in it is at
. You can see that I believe the
offset integers are base-10 ints. I do hope that's correct, or I've
done a lot of work for naught.

Next I try

def convertPath(path):
"""
Given a path with backslashes, return that path with forward slashes.

By Steven D'Aprano  07/31/2011
>>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'
>>> convertPath(path)
'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf'
"""
import os.path
separator = os.path.sep
if separator != '/':
path = path.replace(os.path.sep, '/')
return path

and get

>>> import mycalc2
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python32\lib\site-packages\mycalc2.py", line 10
"""
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes
in position 130-132: truncated \UXXX
escape
>>>

where 130-132 are 20, 30, 37 or the , '0', '7'  of " 07/31/2011".

So I go with

def convertPath(path):
"""
Given a path with backslashes, return that path with forward slashes.

By Steven D'Aprano
>>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'
>>> convertPath(path)
'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf'
"""
import os.path
separator = os.path.sep
if separator != '/':
path = path.replace(os.path.sep, '/')
return path

and get

>>> import mycalc2
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python32\lib\site-packages\mycalc2.py", line 10
"""
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes
in position 118-120: truncated \UXXX
escape

Where 118-120 are 65, 6E, 20, or the 'e', 'n',  of "Steven "

I then delete that line, and go with

def convertPath(path):
"""
Given a path with backslashes, return that path with forward slashes.

>>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'
>>> convertPath(path)
'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf'
"""
import os.path
separator = os.path.sep
if separator != '/':
path = path.replace(os.path.sep, '/')
return path

and get

>>> import mycalc2
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python32\lib\site-packages\mycalc2.py", line 9
"""
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes
in position 95-97: truncated \U
escape

where 95-97 are 64, 20, 73 or the 'd', , 's' of "forward slashes"

So I delete "forward slashes" and go with

def convertPath(path):
"""
Given a path with backslash

Re: [Tutor] Puzzled again

2011-08-03 Thread Steven D'Aprano

Richard D. Moores wrote:


But here's a try using the regular command line:

C:\Windows\System32>python
Python 3.2.1 (default, Jul 10 2011, 20:02:51) [MSC v.1500 64 bit
(AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

from mycalc import convertPath

Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python32\lib\site-packages\mycalc.py", line 36
"""
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes
in position 149-151: truncated \UXXX
X escape


Ha ha, well I'm gratified that my prediction of the error you would 
receive under Python 3 is correct, but it doesn't really solve your 
problem under Python 2.7.



What happens when you import the code using the standard Python2.7 
interactive interpreter? I would expect that the truncated \U 
error will go away. If you're still getting the earlier SyntaxError, I 
would open the file in a hex editor and see what's there. I expect that 
there's something unexpected and invisible.


I've seen this happen sometimes when copying and pasting from websites. 
For reasons that I'm sure make sense to web designers who haven't given 
it any thought, some websites put non-breaking spaces into source code, 
which plays merry hell with copying and pasting it because it looks to 
the naked eye like a normal space but isn't.


I've also seen ctrl-Z end of file characters in source code, another 
invisible to the naked eye thing. Or so-called "high-ASCII" bytes. If 
you get an error like this:


SyntaxError: Non-ASCII character '\\xe2' in file script.py on line 21,
but no encoding declared; see
http://www.python.org/peps/pep-0263.html for details

that's your problem.

I don't trust errors given by IDEs, because they often play games with 
the source code and sometimes give misleading error messages. Whenever 
you have mysterious syntax errors you can't explain, bypass the IDE and 
go straight to the standard Python interactive interpreter. (Make sure 
you use the same version though.)





--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Puzzled again

2011-08-03 Thread Richard D. Moores
Ops!

I accidentally erased convertPath() from mycalc.py while trying out
various things. It was my only copy of convertPath that had the
docstring as posted, so I went to my initial post and copy-and-pasted
it into mycalc.py. Now no problem:

from Wing's shell:

Python 3.2.1 (default, Jul 10 2011, 20:02:51) [MSC v.1500 64 bit (AMD64)]
Type "help", "copyright", "credits" or "license" for more information.
>>> from mycalc import convertPath
>>>

So I'm no longer able to try the various things suggested by you guys.
10 thousand apologies.

Dick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Puzzled again

2011-08-03 Thread Steven D'Aprano

Steven D'Aprano wrote:

Richard D. Moores wrote:

Puzzled again. Why the error. Line 36 is the line just above "import
os.path". I have many other functions in mycalc.py with examples
formatted exactly the same way.

def convertPath(path):
"""
Given a path with backslashes, return that path with forward slashes.

By Steven D'Aprano  07/31/2011 on Tutor list
>>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'


Are you aware that this is not a raw string? It's wrapped inside another 
non-raw string, so it is merely a sub-string containing the letters r 
single-quote C colon backslash-U etc. Now, as it turns out, backslash-U 
and friends don't have any special meanings, so it will work fine, but 



*slaps head*

Doh! No, I was wrong. \U DOES have a special meaning. It introduces an 
eight-character unicode escape sequence, but only in unicode strings.


>>> u'\Users\Dick'
  File "", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in 
position 0-2: truncated \U escape


This fails because the \U is not followed by any valid hex digits. So in 
Python 3, you should expect a different syntax error.




--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Puzzled again

2011-08-03 Thread Steven D'Aprano

Richard D. Moores wrote:

Puzzled again. Why the error. Line 36 is the line just above "import
os.path". I have many other functions in mycalc.py with examples
formatted exactly the same way.

def convertPath(path):
"""
Given a path with backslashes, return that path with forward slashes.

By Steven D'Aprano  07/31/2011 on Tutor list
>>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'


Are you aware that this is not a raw string? It's wrapped inside another 
non-raw string, so it is merely a sub-string containing the letters r 
single-quote C colon backslash-U etc. Now, as it turns out, backslash-U 
and friends don't have any special meanings, so it will work fine, but 
that's an accident of the characters in the path. If it were backslash-n 
(say) instead, things would be different.


(P.S. the docstring itself can be a raw string. Just start it with r""" 
instead of """.)





>>> convertPath(path)
'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf'
"""
import os.path
separator = os.path.sep
if separator != '/':
path = path.replace(os.path.sep, '/')
return path


from mycalc import convertPath

Traceback (most recent call last):
  File "", line 36, in 
Syntax Error: """: c:\Python32\lib\site-packages\mycalc.py, line 36-1



Is this the actual traceback you received? I would expect that importing 
mycalc.py would be fine, but that trying to run doctest over it *may* 
play up, probably with a SyntaxError.


It works fine for me when I paste your code directly into an interactive 
session, and the docstring looks as expected:



>>> print(convertPath.__doc__)

Given a path with backslashes, return that path with forward slashes.

By Steven D'Aprano  07/31/2011 on Tutor list
>>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'
>>> convertPath(path)
'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf'


In general, expect to have fun and games getting doctests to do the 
right thing with backslashes. The interaction of doctests (which uses 
exec under the hood) and backslashes is rather ugly. But I don't know if 
that's the problem here.



Other than that, I'm afraid I can't reproduce your error. Perhaps there 
is some invisible character in the original file, such as a DOS "End of 
File" ctrl-Z, which was messing things up for you, you've eventually, 
and accidentally, deleted it. Because there's nothing obvious to explain 
why you get the error you get, or why it goes away when it does.





--
Steven

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Puzzled again

2011-08-03 Thread Dave Angel

On 08/03/2011 02:07 AM, Richard D. Moores wrote:

On Tue, Aug 2, 2011 at 21:59, Dave Angel  wrote:


When I paste that from your email into a file and run Python 2.7 on it, it
behaves fine with no errors.  That's in Linux.


I should have said that I'm using Wing IDE Professional 4.0.3-1 (rev
24721), Windows Vista, and Python 3.2.1.


But the easiest explanation is that you perhaps used a funny character for
your triple-quotes.  And when you retyped them on a new line, you typed
regular ones.

For example, I've seen that sort of thing when someone wrote code in a
Windows word processor that had "smart quotes."


No, no funny characters with Wing.

Thanks for your guess, Dave.

But here's a try using the regular command line:

C:\Windows\System32>python
Python 3.2.1 (default, Jul 10 2011, 20:02:51) [MSC v.1500 64 bit
(AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

from mycalc import convertPath

Traceback (most recent call last):
   File "", line 1, in
   File "C:\Python32\lib\site-packages\mycalc.py", line 36
 """
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes
in position 149-151: truncated \UXXX
X escape




Dick

OK, so it's no longer a guess, it's a certainty.  You can't get that 
error unless you have a non-ASCII character there.  So take a look at 
the file with a hex viewer, and look at offset 149.  Somewhere there's a 
character above hex 7f



--

DaveA
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Puzzled again

2011-08-02 Thread Andre Engels
On Wed, Aug 3, 2011 at 8:07 AM, Richard D. Moores wrote:

> On Tue, Aug 2, 2011 at 21:59, Dave Angel  wrote:
>
> > When I paste that from your email into a file and run Python 2.7 on it,
> it
> > behaves fine with no errors.  That's in Linux.
>
> I should have said that I'm using Wing IDE Professional 4.0.3-1 (rev
> 24721), Windows Vista, and Python 3.2.1.
>
> > But the easiest explanation is that you perhaps used a funny character
> for
> > your triple-quotes.  And when you retyped them on a new line, you typed
> > regular ones.
> >
> > For example, I've seen that sort of thing when someone wrote code in a
> > Windows word processor that had "smart quotes."
>
> No, no funny characters with Wing.
>
> Thanks for your guess, Dave.
>
> But here's a try using the regular command line:
>
> C:\Windows\System32>python
> Python 3.2.1 (default, Jul 10 2011, 20:02:51) [MSC v.1500 64 bit
> (AMD64)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> from mycalc import convertPath
> Traceback (most recent call last):
>   File "", line 1, in 
>  File "C:\Python32\lib\site-packages\mycalc.py", line 36
>"""
> SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes
> in position 149-151: truncated \UXXX
> X escape
> >>>
>

That says that there is some character in that line that is not valid
Unicode. Remove the line (and perhaps the ones above and below it at the
same time, in case it's around the line feed character(s)) and type it in
again. It's likely to be as easy as that.

-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Puzzled again

2011-08-02 Thread Richard D. Moores
On Tue, Aug 2, 2011 at 21:59, Dave Angel  wrote:

> When I paste that from your email into a file and run Python 2.7 on it, it
> behaves fine with no errors.  That's in Linux.

I should have said that I'm using Wing IDE Professional 4.0.3-1 (rev
24721), Windows Vista, and Python 3.2.1.

> But the easiest explanation is that you perhaps used a funny character for
> your triple-quotes.  And when you retyped them on a new line, you typed
> regular ones.
>
> For example, I've seen that sort of thing when someone wrote code in a
> Windows word processor that had "smart quotes."

No, no funny characters with Wing.

Thanks for your guess, Dave.

But here's a try using the regular command line:

C:\Windows\System32>python
Python 3.2.1 (default, Jul 10 2011, 20:02:51) [MSC v.1500 64 bit
(AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from mycalc import convertPath
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python32\lib\site-packages\mycalc.py", line 36
"""
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes
in position 149-151: truncated \UXXX
X escape
>>>

Dick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Puzzled again

2011-08-02 Thread Dave Angel

On 08/02/2011 10:36 PM, Richard D. Moores wrote:

Puzzled again. Why the error. Line 36 is the line just above "import
os.path". I have many other functions in mycalc.py with examples
formatted exactly the same way.

def convertPath(path):
 """
 Given a path with backslashes, return that path with forward slashes.

 By Steven D'Aprano  07/31/2011 on Tutor list
 >>>  path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'
 >>>  convertPath(path)
 'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf'
 """
 import os.path
 separator = os.path.sep
 if separator != '/':
 path = path.replace(os.path.sep, '/')
 return path


from mycalc import convertPath

Traceback (most recent call last):
   File "", line 36, in
Syntax Error: """: c:\Python32\lib\site-packages\mycalc.py, line 36-1

def convertPath(path):
 """
 Given a path with backslashes, return that path with forward slashes.

 By Steven D'Aprano  07/31/2011 on Tutor list
 >>>  path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'
 >>>  convertPath(path)
 'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf'
 """
 import os.path
 separator = os.path.sep
 if separator != '/':
 path = path.replace(os.path.sep, '/')
When I paste that from your email into a file and run Python 2.7 on it, 
it behaves fine with no errors.  That's in Linux.


But the easiest explanation is that you perhaps used a funny character 
for your triple-quotes.  And when you retyped them on a new line, you 
typed regular ones.


For example, I've seen that sort of thing when someone wrote code in a 
Windows word processor that had "smart quotes."


--

DaveA

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] puzzled by Python 3's print()

2010-07-01 Thread Richard D. Moores
On Thu, Jul 1, 2010 at 16:18, Steven D'Aprano  wrote:
> On Fri, 2 Jul 2010 05:18:00 am Eike Welk wrote:
>
>> As you are using long integers (and you were previously writing about
>> prime numbers) the precision of floating point numbers might not be
>> enough for your purposes.
>
> It certainly won't be once you get to large enough primes!
>
>> Therefore you should probably use the integer division operator: "//"
>
> And the reminder (or modulo) operator %, together with the combination
> function divmod(a, b) which returns (a//b, a%b). The advantage of
> divmod is that it is faster than calling a//b followed by a%b.

Thanks to you and Eike, Steven, I was able to write this little
function that does the job for me, and more:

>>> def divide_large_ints(n, div):
x = divmod(n, div)
return str(x[0]) + str(x[1]/div).lstrip('0')


>>> n = 200033
>>> div = 2
>>> divide_large_ints(n, div)
'100016.5'
>>>

Dick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] puzzled by Python 3's print()

2010-07-01 Thread Steven D'Aprano
On Fri, 2 Jul 2010 05:18:00 am Eike Welk wrote:

> As you are using long integers (and you were previously writing about
> prime numbers) the precision of floating point numbers might not be
> enough for your purposes.

It certainly won't be once you get to large enough primes!

> Therefore you should probably use the integer division operator: "//"

And the reminder (or modulo) operator %, together with the combination 
function divmod(a, b) which returns (a//b, a%b). The advantage of 
divmod is that it is faster than calling a//b followed by a%b.


-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] puzzled by Python 3's print()

2010-07-01 Thread Richard D. Moores
On Thu, Jul 1, 2010 at 12:18, Eike Welk  wrote:

> Therefore you should probably use the integer division operator: "//"

>>> x = 200033
>>> x//2
100016

I can live with THAT error!

Thanks, Eike!

But I will press on with Mark's


Dick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] puzzled by Python 3's print()

2010-07-01 Thread Mark Lawrence

On 01/07/2010 20:18, Eike Welk wrote:

Hello Richard!

On Thursday July 1 2010 15:11:21 Richard D. Moores wrote:

Thanks to yours and others responses, I've learned some things I
didn't know, but remember, I'm starting with long ints such as


Also note that in Python 3 the "/" (division) operator returns a floating
point number when you divide integers. This is one of the changes that Python
3 introduces.

As you are using long integers (and you were previously writing about prime
numbers) the precision of floating point numbers might not be enough for your
purposes.

Therefore you should probably use the integer division operator: "//"


The following (edited) snippet from IPython demonstrates "//" and the loss of
precision when using "/":


...
Python 2.6.2 (r262:71600, Mar 29 2010, 15:30:01)
Type "copyright", "credits" or "license" for more information.

IPython 0.10 -- An enhanced Interactive Python.
...

In [1]: from __future__ import  division

In [2]: a = 12

In [3]: a
Out[3]: 12L

In [4]: a//2
Out[4]: 50001L

In [5]: a/2
Out[5]: 4.9994e+56

In [6]: long(a/2)
Out[6]: 499937061060126016582882140297920412594995200L


Eike.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



Drat, drat and double drat, I believe Dick Dastardly from the Wacky 
Races cartoons.  I meant to mention this, got side-tracked and 
completely forgot, sorry.


Kindest regards.

Mark Lawrence.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] puzzled by Python 3's print()

2010-07-01 Thread Eike Welk
Hello Richard!

On Thursday July 1 2010 15:11:21 Richard D. Moores wrote:
> Thanks to yours and others responses, I've learned some things I
> didn't know, but remember, I'm starting with long ints such as

Also note that in Python 3 the "/" (division) operator returns a floating 
point number when you divide integers. This is one of the changes that Python 
3 introduces.

As you are using long integers (and you were previously writing about prime 
numbers) the precision of floating point numbers might not be enough for your 
purposes.

Therefore you should probably use the integer division operator: "//"


The following (edited) snippet from IPython demonstrates "//" and the loss of 
precision when using "/":


...
Python 2.6.2 (r262:71600, Mar 29 2010, 15:30:01)
Type "copyright", "credits" or "license" for more information.

IPython 0.10 -- An enhanced Interactive Python.
...

In [1]: from __future__ import  division

In [2]: a = 12

In [3]: a
Out[3]: 12L

In [4]: a//2
Out[4]: 50001L

In [5]: a/2
Out[5]: 4.9994e+56

In [6]: long(a/2)
Out[6]: 499937061060126016582882140297920412594995200L


Eike.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] puzzled by Python 3's print()

2010-07-01 Thread Richard D. Moores
On Thu, Jul 1, 2010 at 09:25, Mark Lawrence  wrote:

> Take a look at section 7.1.3 here.
>
> http://docs.python.org/py3k/library/string.html#string-formatting
>
> This is the recommended way to format strings in Python 3.

Thanks, Mark. Looks good, if cryptic. I don't have time to dig into it
 now, but I will later and report back.

Dick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] puzzled by Python 3's print()

2010-07-01 Thread Mark Lawrence

On 01/07/2010 14:11, Richard D. Moores wrote:

On Thu, Jul 1, 2010 at 04:57, Steven D'Aprano  wrote:

On Thu, 1 Jul 2010 06:26:21 pm Richard D. Moores wrote:

x = 2034
x/2

1017.0


print(x/2)

1e+15

I was expecting, in fact needing, 117 or
117.0

1e+15 is unsatisfactory. Am I forced to use the decimal module?


This is not an issue with print, this is an issue with floats -- they
produced a rounded, approximate value when converted to a string. print
merely prints that string:


x = 1e15 +17
x

1017.0

print(x)

1e+15

str(x)

'1e+15'


If you want more control over the string conversion, you can do
something like this:


print(repr(x))

1017.0

print('%.5f' % x)

1017.0


Thanks to yours and others responses, I've learned some things I
didn't know, but remember, I'm starting with long ints such as
x = 2034, cutting it in half, and hoping to print
1017 or 1017.0
(I also need to divide odd ints like 2033 and print
1017.5)

(In my initial post, I used a smaller x, x = 2034.  I
should have made it longer, to reflect the ints I'm dealing with (big
primes and their near neighbors).

I'm still hoping to be saved from the decimal module :)  .


I think that we can manage that. :)



Dick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



Take a look at section 7.1.3 here.

http://docs.python.org/py3k/library/string.html#string-formatting

This is the recommended way to format strings in Python 3.

Kindest regards.

Mark Lawrence.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] puzzled by Python 3's print()

2010-07-01 Thread Richard D. Moores
On Thu, Jul 1, 2010 at 04:57, Steven D'Aprano  wrote:
> On Thu, 1 Jul 2010 06:26:21 pm Richard D. Moores wrote:
>> >>> x = 2034
>> >>> x/2
>> 1017.0
>>
>> >>> print(x/2)
>> 1e+15
>>
>> I was expecting, in fact needing, 117 or
>> 117.0
>>
>> 1e+15 is unsatisfactory. Am I forced to use the decimal module?
>
> This is not an issue with print, this is an issue with floats -- they
> produced a rounded, approximate value when converted to a string. print
> merely prints that string:
>
 x = 1e15 +17
 x
> 1017.0
 print(x)
> 1e+15
 str(x)
> '1e+15'
>
>
> If you want more control over the string conversion, you can do
> something like this:
>
 print(repr(x))
> 1017.0
 print('%.5f' % x)
> 1017.0

Thanks to yours and others responses, I've learned some things I
didn't know, but remember, I'm starting with long ints such as
x = 2034, cutting it in half, and hoping to print
1017 or 1017.0
(I also need to divide odd ints like 2033 and print
1017.5)

(In my initial post, I used a smaller x, x = 2034.  I
should have made it longer, to reflect the ints I'm dealing with (big
primes and their near neighbors).

I'm still hoping to be saved from the decimal module :)  .

Dick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] puzzled by Python 3's print()

2010-07-01 Thread Steven D'Aprano
On Thu, 1 Jul 2010 06:26:21 pm Richard D. Moores wrote:
> >>> x = 2034
> >>> x/2
> 1017.0
>
> >>> print(x/2)
> 1e+15
>
> I was expecting, in fact needing, 117 or
> 117.0
>
> 1e+15 is unsatisfactory. Am I forced to use the decimal module?

This is not an issue with print, this is an issue with floats -- they 
produced a rounded, approximate value when converted to a string. print 
merely prints that string:

>>> x = 1e15 +17
>>> x
1017.0
>>> print(x)
1e+15
>>> str(x)
'1e+15'


If you want more control over the string conversion, you can do 
something like this:

>>> print(repr(x))
1017.0
>>> print('%.5f' % x)
1017.0


-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] puzzled by Python 3's print()

2010-07-01 Thread Evert Rol
 x = 2034
 x/2
> 1017.0
 print(x/2)
> 1e+15
> 
> I was expecting, in fact needing, 117 or 117.0
> 
> 1e+15 is unsatisfactory. Am I forced to use the decimal module?

Can't you use string formatting? Eg:
>>> print("{0:15.0f}".format(x/2))
1017


print uses __str__()/str(), which I assume was deemed unsatisfactory in Python 
2: it's supposed to show a 'simple, nice' representation of anything, while 
__repr__() (or the repr() function) shows a more exact representation (or 
rather, repr() shows an object that can be used to recreate a new identical 
object: float(repr(x/2)) gives back the correct float, while float(str(x/2)) 
wouldn't). 
So they've apparently changed __str__() to make things somewhat more readable. 
__repr__()/repr() is what you get with just using x/2 on the command line:

>>> x/2
1017.0
>>> repr(x/2)
1017.0


And you could actually use:

>>> print(repr(x/2))
1017.0


I would go for the format statement, though. But that may depend on your 
precise needs.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] puzzled by Python 3's print()

2010-07-01 Thread Shantanoo
without using decimal module:

>>> x = 2034
>>> print('%d'%(x/2))
1017


On Thu, Jul 1, 2010 at 13:56, Richard D. Moores  wrote:
 x = 2034
 x/2
> 1017.0
 print(x/2)
> 1e+15
>
> I was expecting, in fact needing, 117 or 117.0
>
> 1e+15 is unsatisfactory. Am I forced to use the decimal module?
>
> Dick Moores
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Puzzled

2008-08-29 Thread Kent Johnson
On Fri, Aug 29, 2008 at 6:15 PM, ammar azif <[EMAIL PROTECTED]> wrote:
> Thanks for the explanation. Btw, How can I get the size of python primitive
> data types in bytes? Is it defined somewhere in a file that I can look at?

Not really. sys.maxint gives the largest int, from which you can infer the size.

Here is a (complex) recipe that reports sizes:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/546530

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Puzzled

2008-08-29 Thread ammar azif
Thanks for the explanation. Btw, How can I get the size of python primitive 
data types in bytes? Is it defined somewhere in a file that I can look at? 

--- On Fri, 8/29/08, Kent Johnson <[EMAIL PROTECTED]> wrote:
From: Kent Johnson <[EMAIL PROTECTED]>
Subject: Re: [Tutor] Puzzled
To: [EMAIL PROTECTED]
Cc: tutor@python.org
Date: Friday, August 29, 2008, 4:41 PM

On Fri, Aug 29, 2008 at 5:13 PM, ammar azif <[EMAIL PROTECTED]> wrote:
> I wrote a python program that used time() function from the time module to
> retrieve time in seconds since Epoch. After the value was retrieved which
I
> checked is a float by using type(),  the value was then written into a
file
> in binary format. Then another C program that I wrote opened the file and
> converted the value into a time_t variable but it was totally different
from
> the correct value. Then I found that the time_t size is actually 4 byte
> integer which is not the same with 8-byte float value returned by
> time.time(). Why is this so? Being written with C library, isn't
python
> suppose to work well with it?

The C time_t type is very loosely specified; in ANSI C it is only
required to be an arithmetic type. According to Wikipedia
(http://en.wikipedia.org/wiki/Time_t), Posix-compliant systems still
have latitude to implement it as 32 or 64 bits.

Python tries to be bit higher level, giving you fractional seconds if
the implementation supports it and a common data type across
implementations. So there is not an exact match in functionality.

If you want to write data to file in a format that can be read by
another program, you should look at the struct module.

Kent



  ___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Puzzled

2008-08-29 Thread Kent Johnson
On Fri, Aug 29, 2008 at 5:13 PM, ammar azif <[EMAIL PROTECTED]> wrote:
> I wrote a python program that used time() function from the time module to
> retrieve time in seconds since Epoch. After the value was retrieved which I
> checked is a float by using type(),  the value was then written into a file
> in binary format. Then another C program that I wrote opened the file and
> converted the value into a time_t variable but it was totally different from
> the correct value. Then I found that the time_t size is actually 4 byte
> integer which is not the same with 8-byte float value returned by
> time.time(). Why is this so? Being written with C library, isn't python
> suppose to work well with it?

The C time_t type is very loosely specified; in ANSI C it is only
required to be an arithmetic type. According to Wikipedia
(http://en.wikipedia.org/wiki/Time_t), Posix-compliant systems still
have latitude to implement it as 32 or 64 bits.

Python tries to be bit higher level, giving you fractional seconds if
the implementation supports it and a common data type across
implementations. So there is not an exact match in functionality.

If you want to write data to file in a format that can be read by
another program, you should look at the struct module.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Puzzled by print lst.sort()

2006-10-01 Thread Liam Clarke
Dick Moores wrote:
> At 01:37 PM 9/30/2006, Shantanoo Mahajan wrote:
>   
>> Maybe following is helpful:
>>
>> 
> a=[3,2,1]
> b=a[:]
> b.sort()
> c=sorted(a)
> print a,b,c
> [3, 2, 1] [1, 2, 3] [1, 2, 3]
>
>   
>> Shantanoo
>> 
>
> Sorry to be dense, but I don't see what showing what happens to a 
> copy of list a adds to the explanation:
>  >>> a = [3,2,1]
>  >>> b = a[:]
>  >>> b.sort()
>  >>> b
> [1, 2, 3]
>  >>>
>
> given that:
>
>  >>> a = [3,2,1]
>  >>> a.sort()
>  >>> a
> [1, 2, 3]
>  >>>
>
> I suppose I've misunderstood how you were trying to assist me.
>
> Thanks,
>
> Dick
>
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   
I think what Shantanoo was getting at was the reference thing, i.e.,

 >>> a = [3,2,1]
 >>> b = a[:]
 >>> b.sort()
 >>> a
[3, 2, 1]
 >>> b
[1, 2, 3]
 >>>

As opposed to

 >>> a = [3,2,1]
 >>> b = a
 >>> b.sort()
 >>> a
[1, 2, 3]
 >>> b
[1, 2, 3]
 >>>

You may not always have access to Python 2.4.

Regards,

Liam Clarke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Puzzled by print lst.sort()

2006-10-01 Thread Dick Moores
At 01:37 PM 9/30/2006, Shantanoo Mahajan wrote:
>Maybe following is helpful:
>
> >>> a=[3,2,1]
> >>> b=a[:]
> >>> b.sort()
> >>> c=sorted(a)
> >>> print a,b,c
> >>> [3, 2, 1] [1, 2, 3] [1, 2, 3]
> >>>
>
>Shantanoo

Sorry to be dense, but I don't see what showing what happens to a 
copy of list a adds to the explanation:
 >>> a = [3,2,1]
 >>> b = a[:]
 >>> b.sort()
 >>> b
[1, 2, 3]
 >>>

given that:

 >>> a = [3,2,1]
 >>> a.sort()
 >>> a
[1, 2, 3]
 >>>

I suppose I've misunderstood how you were trying to assist me.

Thanks,

Dick




___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Puzzled by print lst.sort()

2006-09-30 Thread Shantanoo Mahajan
+++ Dick Moores [30-09-06 10:47 -0700]:
| At 05:07 AM 9/30/2006, Liam Clarke wrote:
| >Dick Moores wrote:
| > > At 03:22 AM 9/30/2006, Liam Clarke wrote:
| > >> Dick Moores wrote:
| 
| > >> A Python list sort is destructive, as you can see - it has modified
| > >> lst. So, to emphasise that it is destructive, it returns None. You'll
| > >> find this in most destructive methods and functions in Python.
| > >
| > > OK, but returning the new list would seem to make more sense. Is the
| > > reason sort() doesn't, really only that it is better to emphasize that
| > > it is destructive?
| >
| >Hi Dick,
| >
| >According to the guy who runs Python, yup. Got to remember the downside
| >to destructive functions is that everything in Python is a reference.
| >For example:
| >
| >  >>> a = [3,2,1]
| >  >>> b = a
| >  >>> b.sort()
| >  >>> print a
| >[1, 2, 3]
| >
| >If you could use
| >
| >y = x.sort()
| >
| >to get a copy of the sorted list, you'd find that subtle bugs would
| >appear and frustrate you. In functional languages like Common Lisp or
| >Scheme, destructive functions are very clearly marked as such, (in
| >Scheme, they use exclamation marks - (sort! x) to indicate a destructive
| >version of (sort x).) as a key part of the functional paradigm is
| >reducing side effects.
| >
| >I believe sorting in place has performance advantages too.
| >
| >It's covered in the official FAQ:
| >
| 
>http://www.python.org/doc/faq/general/#why-doesn-t-list-sort-return-the-sorted-list
| 
| Thanks for the further enlightenment, Liam.

Maybe following is helpful:

>>> a=[3,2,1]
>>> b=a[:]
>>> b.sort()
>>> c=sorted(a)
>>> print a,b,c
>>> [3, 2, 1] [1, 2, 3] [1, 2, 3]
>>>

Shantanoo
-- 
The world we have created is a product of our thinking; it cannot be
changed without changing our thinking.  ~Albert Einstein
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Puzzled by print lst.sort()

2006-09-30 Thread Dick Moores
At 05:07 AM 9/30/2006, Liam Clarke wrote:
>Dick Moores wrote:
> > At 03:22 AM 9/30/2006, Liam Clarke wrote:
> >> Dick Moores wrote:

> >> A Python list sort is destructive, as you can see - it has modified
> >> lst. So, to emphasise that it is destructive, it returns None. You'll
> >> find this in most destructive methods and functions in Python.
> >
> > OK, but returning the new list would seem to make more sense. Is the
> > reason sort() doesn't, really only that it is better to emphasize that
> > it is destructive?
>
>Hi Dick,
>
>According to the guy who runs Python, yup. Got to remember the downside
>to destructive functions is that everything in Python is a reference.
>For example:
>
>  >>> a = [3,2,1]
>  >>> b = a
>  >>> b.sort()
>  >>> print a
>[1, 2, 3]
>
>If you could use
>
>y = x.sort()
>
>to get a copy of the sorted list, you'd find that subtle bugs would
>appear and frustrate you. In functional languages like Common Lisp or
>Scheme, destructive functions are very clearly marked as such, (in
>Scheme, they use exclamation marks - (sort! x) to indicate a destructive
>version of (sort x).) as a key part of the functional paradigm is
>reducing side effects.
>
>I believe sorting in place has performance advantages too.
>
>It's covered in the official FAQ:
>
>http://www.python.org/doc/faq/general/#why-doesn-t-list-sort-return-the-sorted-list

Thanks for the further enlightenment, Liam.

Dick



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Puzzled by print lst.sort()

2006-09-30 Thread Liam Clarke
Dick Moores wrote:
> At 03:22 AM 9/30/2006, Liam Clarke wrote:
>> Dick Moores wrote:
>>>
>>>  >>> lst = [5,3,7,6,2]
>>>  >>> lst.sort()
>>>  >>> lst
>>> [2, 3, 5, 6, 7]
>>>  >>> lst = [5,3,7,6,2]
>>>  >>> print lst.sort()
>>> None
>>>  >>> lst
>>> [2, 3, 5, 6, 7]
>>>
>>> I'm wondering why "print lst.sort()" doesn't print the newly
>>> sorted 
>>> list, but instead prints "None". In fact, the sorting has taken
>>> place 
>>> because of "print lst.sort()". Is this behavior a Good Thing in
>>> Python?
>>>
>>> Dick
>>>
>>> ___
>>> Tutor maillist  - 
>>> Tutor@python.org 
>>>
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>>   
>> Hi Dick,
>>
>> A Python list sort is destructive, as you can see - it has modified 
>> lst. So, to emphasise that it is destructive, it returns None. You'll 
>> find this in most destructive methods and functions in Python.
>
> OK, but returning the new list would seem to make more sense. Is the 
> reason sort() doesn't, really only that it is better to emphasize that 
> it is destructive?
>
>> However, as of Python 2.4, there's a new built-in function that has 
>> the functionality you want:
>>
>> >>> x = [3,1,2]
>> >>> y = sorted(x)
>> >>> print y
>> [1, 2, 3]
>> >>> print x
>> [3, 1, 2]
>>
>> You'll note that sorted() is *not *destructive - that is, x is not 
>> modified. 
>
> Didn't know about sorted(). Thanks, Liam.
>
> Dick
>
>
> 
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>   

Oh, and PS - you'll find that list.reverse() also returns None.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Puzzled by print lst.sort()

2006-09-30 Thread Liam Clarke
Dick Moores wrote:
> At 03:22 AM 9/30/2006, Liam Clarke wrote:
>> Dick Moores wrote:
>>>
>>>  >>> lst = [5,3,7,6,2]
>>>  >>> lst.sort()
>>>  >>> lst
>>> [2, 3, 5, 6, 7]
>>>  >>> lst = [5,3,7,6,2]
>>>  >>> print lst.sort()
>>> None
>>>  >>> lst
>>> [2, 3, 5, 6, 7]
>>>
>>> I'm wondering why "print lst.sort()" doesn't print the newly
>>> sorted 
>>> list, but instead prints "None". In fact, the sorting has taken
>>> place 
>>> because of "print lst.sort()". Is this behavior a Good Thing in
>>> Python?
>>>
>>> Dick
>>>
>>> ___
>>> Tutor maillist  - 
>>> Tutor@python.org 
>>>
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>>   
>> Hi Dick,
>>
>> A Python list sort is destructive, as you can see - it has modified 
>> lst. So, to emphasise that it is destructive, it returns None. You'll 
>> find this in most destructive methods and functions in Python.
>
> OK, but returning the new list would seem to make more sense. Is the 
> reason sort() doesn't, really only that it is better to emphasize that 
> it is destructive?

Hi Dick,

According to the guy who runs Python, yup. Got to remember the downside 
to destructive functions is that everything in Python is a reference. 
For example:

 >>> a = [3,2,1]
 >>> b = a
 >>> b.sort()
 >>> print a
[1, 2, 3]

If you could use

y = x.sort()

to get a copy of the sorted list, you'd find that subtle bugs would 
appear and frustrate you. In functional languages like Common Lisp or 
Scheme, destructive functions are very clearly marked as such, (in 
Scheme, they use exclamation marks - (sort! x) to indicate a destructive 
version of (sort x).) as a key part of the functional paradigm is 
reducing side effects.

I believe sorting in place has performance advantages too.

It's covered in the official FAQ:

http://www.python.org/doc/faq/general/#why-doesn-t-list-sort-return-the-sorted-list

Regards,

Liam Clarke
>> However, as of Python 2.4, there's a new built-in function that has 
>> the functionality you want:
>>
>> >>> x = [3,1,2]
>> >>> y = sorted(x)
>> >>> print y
>> [1, 2, 3]
>> >>> print x
>> [3, 1, 2]
>>
>> You'll note that sorted() is *not *destructive - that is, x is not 
>> modified. 
>
> Didn't know about sorted(). Thanks, Liam.
>
> Dick
>
>
> 
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>   

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Puzzled by print lst.sort()

2006-09-30 Thread Dick Moores


At 03:22 AM 9/30/2006, Liam Clarke wrote:
Dick Moores wrote: 

 >>> lst = [5,3,7,6,2]
 >>> lst.sort()
 >>> lst
[2, 3, 5, 6, 7]
 >>> lst = [5,3,7,6,2]
 >>> print lst.sort()
None
 >>> lst
[2, 3, 5, 6, 7]

I'm wondering why "print lst.sort()" doesn't print the newly
sorted 
list, but instead prints "None". In fact, the sorting has taken
place 
because of "print lst.sort()". Is this behavior a Good Thing in
Python?

Dick

___
Tutor maillist  - 
Tutor@python.org

http://mail.python.org/mailman/listinfo/tutor

  Hi
Dick, 
A Python list sort is destructive, as you can see - it has modified lst.
So, to emphasise that it is destructive, it returns None. You'll find
this in most destructive methods and functions in
Python.
OK, but returning the new list would seem to make more sense. Is the
reason sort() doesn't, really only that it is better to emphasize that it
is destructive?
However, as of Python 2.4,
there's a new built-in function that has the functionality you
want:
>>> x = [3,1,2]
>>> y = sorted(x)
>>> print y
[1, 2, 3]
>>> print x
[3, 1, 2]
You'll note that sorted() is not destructive - that is, x is not
modified. 
Didn't know about sorted(). Thanks, Liam.
Dick




___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Puzzled by print lst.sort()

2006-09-30 Thread Liam Clarke




Dick Moores wrote:

   >>> lst = [5,3,7,6,2]
 >>> lst.sort()
 >>> lst
[2, 3, 5, 6, 7]
 >>> lst = [5,3,7,6,2]
 >>> print lst.sort()
None
 >>> lst
[2, 3, 5, 6, 7]

I'm wondering why "print lst.sort()" doesn't print the newly sorted 
list, but instead prints "None". In fact, the sorting has taken place 
because of "print lst.sort()". Is this behavior a Good Thing in Python?

Dick

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

  

Hi Dick, 

A Python list sort is destructive, as you can see - it has modified
lst. So, to emphasise that it is destructive, it returns None. You'll
find this in most destructive methods and functions in Python.

However, as of Python 2.4, there's a new built-in function that has the
functionality you want:

>>> x = [3,1,2]
>>> y = sorted(x)
>>> print y
[1, 2, 3]
>>> print x
[3, 1, 2]

You'll note that sorted() is not destructive - that is, x is
not modified. 

Regards, 

Liam Clarke


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] puzzled again by decimal module

2006-08-18 Thread Tim Peters
[Tim Peters]
>> You would in this case, and that would be wrong.  In fp you'd get an
>> approximation to the exact n * (1./5 + 1./5**2 + ...)  == n/4. (use
>> the rule for the sum of an infinite geometric series).  For example,
>> that way you'd compute that 4! == 24 has 4/4 == 1 trailing zero,
>> instead of the correct 4 // 5 == 0 trailing zeroes, and that 9! ==
>> 362880 has 9/4 == 2.25 trailing zeroes instead of the correct 9 // 5
>> == 1 trailing zero.

[Christian Tschabuschnig]
> well ... you're right, of course.

Of course -- but you should still do the exercise ;-)

>> Nope again.  Count the number of trailing zeros in 100! more carefully.

> since i'm not able to count further than to 10 past midnight, i used
> echo -n "" | wc -c
> to do the work. and because i'm a confused person i forgot the "-n" :-)

This is a danger in trying to use tools other than Python -- never
touch them :-)

>>> prod = 1
>>> for i in xrange(2, 101):
... prod *= i
>>> s = str(prod)
>>> s[-25:]
'4'
>>> s.endswith('0' * 25)
False
>>> s.endswith('0' * 24)
True

or the ever-popular :-):

>>> from itertools import groupby
>>> firstkey, firstgroup = groupby(reversed(s)).next()
>>> firstkey
'0'
>>> len(list(firstgroup))
24
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] puzzled again by decimal module

2006-08-18 Thread Christian Tschabuschnig
[Tim Peters]
> You would in this case, and that would be wrong.  In fp you'd get an
> approximation to the exact n * (1./5 + 1./5**2 + ...)  == n/4. (use
> the rule for the sum of an infinite geometric series).  For example,
> that way you'd compute that 4! == 24 has 4/4 == 1 trailing zero,
> instead of the correct 4 // 5 == 0 trailing zeroes, and that 9! ==
> 362880 has 9/4 == 2.25 trailing zeroes instead of the correct 9 // 5
> == 1 trailing zero.

well ... you're right, of course.

> Nope again.  Count the number of trailing zeros in 100! more carefully.

since i'm not able to count further than to 10 past midnight, i used
echo -n "" | wc -c
to do the work. and because i'm a confused person i forgot the "-n" :-)

good night,
christian


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] puzzled again by decimal module

2006-08-18 Thread Tim Peters
[Tim Peters]
>> For a fun :-) exercise, prove that the number of trailing zeroes in n!
>> is the sum, from i = 1 to infinity, of n // 5**i (of course as soon as
>> you reach a value of i such that n < 5**i, the quotient is 0 at that i
>> and forever after).
>>
>> In this case,
>>
>> 100 // 5 + 100 // 25 + 100 // 125 + ... =
>>
>> 20 + 4 + 0 + ... =
>>
>> 24

[Christian Tschabuschnig]
> you should do that with floating-point, so that the quotient never get's
> zero and the "i=1 to infinity" makes sense.

Definitely not.  You didn't do the exercise ;-)  Hint:  n // m is the
number of integers in 1 through n divisible by m.

> This way you (might) get 25

You would in this case, and that would be wrong.  In fp you'd get an
approximation to the exact n * (1./5 + 1./5**2 + ...)  == n/4. (use
the rule for the sum of an infinite geometric series).  For example,
that way you'd compute that 4! == 24 has 4/4 == 1 trailing zero,
instead of the correct 4 // 5 == 0 trailing zeroes, and that 9! ==
362880 has 9/4 == 2.25 trailing zeroes instead of the correct 9 // 5
== 1 trailing zero.

> which is correct; not 24.

Nope again.  Count the number of trailing zeros in 100! more carefully.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] puzzled again by decimal module

2006-08-18 Thread Christian Tschabuschnig
Tim Peters wrote:
> [Dick Moores, computes 100 factorial as
>  
> 9332621544394415268169923885626670049071596826438162146859296389521753229915608941463976156518286253697920827223758251185210916864
> 
>  but worries about all the trailing zeros]
> 
>>  Yes, I'm sure you are. I'd forgotten about all those factors
>> of 100! that end in zero (10, 20, 30, ..., 100).
> 
> And others, like 2 and 5 whose product is 10, or 4 and 25 whose product is 
> 100.
> 
> For a fun :-) exercise, prove that the number of trailing zeroes in n!
> is the sum, from i = 1 to infinity, of n // 5**i (of course as soon as
> you reach a value of i such that n < 5**i, the quotient is 0 at that i
> and forever after).
> 
> In this case,
> 
> 100 // 5 + 100 // 25 + 100 // 125 + ... =
> 
> 20 + 4 + 0 + ... =
> 
> 24

you should do that with floating-point, so that the quotient never get's
zero and the "i=1 to infinity" makes sense. This way you (might) get 25
which is correct; not 24.

but i'm just guessing - i have no way to prove it ;-)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] puzzled again by decimal module

2006-08-18 Thread Tim Peters
[Dick Moores, computes 100 factorial as
 
9332621544394415268169923885626670049071596826438162146859296389521753229915608941463976156518286253697920827223758251185210916864

 but worries about all the trailing zeros]

>  Yes, I'm sure you are. I'd forgotten about all those factors
> of 100! that end in zero (10, 20, 30, ..., 100).

And others, like 2 and 5 whose product is 10, or 4 and 25 whose product is 100.

For a fun :-) exercise, prove that the number of trailing zeroes in n!
is the sum, from i = 1 to infinity, of n // 5**i (of course as soon as
you reach a value of i such that n < 5**i, the quotient is 0 at that i
and forever after).

In this case,

100 // 5 + 100 // 25 + 100 // 125 + ... =

20 + 4 + 0 + ... =

24
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] puzzled again by decimal module

2006-08-18 Thread Dick Moores
At 04:50 PM 8/18/2006, Christian Tschabuschnig wrote:
> >> 
> 9332621544394415268169923885626670049071596826438162146859296389521753229915608941463976156518286253697920827223758251185210916864
> >>> Still not exactly correct! I'm bewildered.
> >>>
> >> The results look the same to me
> >> why do you think they're not correct?
> >> what is the result supposed to be?
> >
> > An integer not ending in 26 zeroes?
>
>The result is correct. I checked it with Mathematica.

 Yes, I'm sure you are. I'd forgotten about all those factors 
of 100! that end in zero (10, 20, 30, ..., 100).

Thanks to all.

Dick



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] puzzled again by decimal module

2006-08-18 Thread Christian Tschabuschnig
>> 9332621544394415268169923885626670049071596826438162146859296389521753229915608941463976156518286253697920827223758251185210916864
>>> Still not exactly correct! I'm bewildered.
>>>
>> The results look the same to me
>> why do you think they're not correct?
>> what is the result supposed to be?
> 
> An integer not ending in 26 zeroes?

The result is correct. I checked it with Mathematica.

Christian


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] puzzled again by decimal module

2006-08-18 Thread Dick Moores
At 04:24 PM 8/18/2006, Luke Paireepinart wrote:
>Dick Moores wrote:
> > But here's the revised precisionFactorial.py:
> >
> > 
> > # 1precisionFactorial.py
> >
> > import decimal
> >
> > def d(x):
> >  return decimal.Decimal(str(x))
> >
> > def fact(n):
> >  product = 1
> >  dec_n = d(n)
> >  while dec_n > 1:
> >  product *= dec_n
> >  dec_n -= 1
> >  return product
> >
> > n = 100
> > decimal.getcontext().prec = 200
> > print fact(n)
> > 
> >
> > 
> 9332621544394415268169923885626670049071596826438162146859296389521753229915608941463976156518286253697920827223758251185210916864
> >
> > Still not exactly correct! I'm bewildered.
> >
>The results look the same to me
>why do you think they're not correct?
>what is the result supposed to be?

An integer not ending in 26 zeroes?

Dick



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] puzzled again by decimal module

2006-08-18 Thread Luke Paireepinart
Dick Moores wrote:
> At 02:41 PM 8/18/2006, Bob Gailer wrote:
>   
>> Dick Moores wrote:
>> 
>>> As an exercise that I thought would help me understand the decimal 
>>> module, I've been trying write a script (precisionFactorial.py) 
>>> that uses a modified fact(n) to compute precise factorials
>>>   
>> What do you mean by "precise factorials"? Python's long integer 
>> should handle this just fine.
>> 
>
> Well, actually, my old fact(100) produces 
> 9332621544394415268169923885626670049071596826438162146859296389521753229915608941463976156518286253697920827223758251185210916864
> Not exactly correct.
>
>   
>>> [snip]
>>>
>>>   
>>> # precisionFactorial.py
>>>
>>> import decimal
>>>
>>> def d(x):
>>>  return decimal.Decimal(str(x))
>>>
>>> def fact(n):
>>>  product = 1
>>>  while d(n) > 1:
>>>  product *= n
>>>  d(n) -= 1
>>>   
>> d(n) -= 1 is shorthand for d(n) = d(n) - 1. This will fail, since 
>> d(n) is a function call, which is not valid as as assignment target. 
>> Instead you should should:
>>
>> def fact(n):
>> product = 1
>> dec_n = d(n)
>> while dec_n > 1:
>> product *= n
>> dec_n -= 1 return product
>> 
>
> Ah, a notation problem. Thanks!
>
> But here's the revised precisionFactorial.py:
>
> 
> # 1precisionFactorial.py
>
> import decimal
>
> def d(x):
>  return decimal.Decimal(str(x))
>
> def fact(n):
>  product = 1
>  dec_n = d(n)
>  while dec_n > 1:
>  product *= dec_n
>  dec_n -= 1
>  return product
>
> n = 100
> decimal.getcontext().prec = 200
> print fact(n)
> 
>
> 9332621544394415268169923885626670049071596826438162146859296389521753229915608941463976156518286253697920827223758251185210916864
>
> Still not exactly correct! I'm bewildered.
>   
The results look the same to me
why do you think they're not correct?
what is the result supposed to be?
> Dick
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] puzzled again by decimal module

2006-08-18 Thread Dick Moores
At 02:41 PM 8/18/2006, Bob Gailer wrote:
>Dick Moores wrote:
>>As an exercise that I thought would help me understand the decimal 
>>module, I've been trying write a script (precisionFactorial.py) 
>>that uses a modified fact(n) to compute precise factorials
>What do you mean by "precise factorials"? Python's long integer 
>should handle this just fine.

Well, actually, my old fact(100) produces 
9332621544394415268169923885626670049071596826438162146859296389521753229915608941463976156518286253697920827223758251185210916864
Not exactly correct.

>>[snip]
>>
>
>># precisionFactorial.py
>>
>>import decimal
>>
>>def d(x):
>>  return decimal.Decimal(str(x))
>>
>>def fact(n):
>>  product = 1
>>  while d(n) > 1:
>>  product *= n
>>  d(n) -= 1
>d(n) -= 1 is shorthand for d(n) = d(n) - 1. This will fail, since 
>d(n) is a function call, which is not valid as as assignment target. 
>Instead you should should:
>
>def fact(n):
> product = 1
> dec_n = d(n)
> while dec_n > 1:
> product *= n
> dec_n -= 1 return product

Ah, a notation problem. Thanks!

But here's the revised precisionFactorial.py:


# 1precisionFactorial.py

import decimal

def d(x):
 return decimal.Decimal(str(x))

def fact(n):
 product = 1
 dec_n = d(n)
 while dec_n > 1:
 product *= dec_n
 dec_n -= 1
 return product

n = 100
decimal.getcontext().prec = 200
print fact(n)


9332621544394415268169923885626670049071596826438162146859296389521753229915608941463976156518286253697920827223758251185210916864

Still not exactly correct! I'm bewildered.

Dick

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] puzzled again by decimal module

2006-08-18 Thread Bob Gailer
Dick Moores wrote:
> As an exercise that I thought would help me understand the decimal 
> module, I've been trying write a script (precisionFactorial.py) that 
> uses a modified fact(n) to compute precise factorials 
What do you mean by "precise factorials"? Python's long integer should 
handle this just fine.
> [snip]
>   

> # precisionFactorial.py
>
> import decimal
>
> def d(x):
>  return decimal.Decimal(str(x))
>
> def fact(n):
>  product = 1
>  while d(n) > 1:
>  product *= n
>  d(n) -= 1 
>   
 d(n) -= 1 is shorthand for d(n) = d(n) - 1. This will fail, since d(n) 
is a function call, which is not valid as as assignment target. Instead 
you should should:

def fact(n):
 product = 1
 dec_n = d(n)
 while dec_n > 1:
 product *= n
 dec_n -= 1 
 return product


[snip]
But as I mentioned there is no value in using decimal here.

-- 
Bob Gailer
510-978-4454

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor