[Edu-sig] reviewing the context manager construct

Vernon D. Cole vernondcole at gmail.com
Fri Mar 28 14:04:55 CET 2014


You are working too hard in creating your string literal.

The *Python Language Reference Manual*  says:

> 2.4.2. String literal concatenation Multiple adjacent string literals
> (delimited by whitespace), possibly using different quoting conventions,
> are allowed, and their meaning is the same as their concatenation. Thus,
> "hello" 'world' is equivalent to "helloworld". This feature can be used
> to reduce the number of backslashes needed, to split long strings
> conveniently across long lines, [...]
>

Also, the output is hard to really comprehend.  So, may I humbly submit...

 from __future__ import print_function
>
> digits =
> "1.61803398874989484820458683436563811772030917980576286213544862270526046281890"
> \
> "244970720720418939113748475408807538689175212663386222353693179318006076672635"
> \
> "443338908659593958290563832266131992829026788067520876689250171169620703222104"
> \
> "321626954862629631361443814975870122034080588795445474924618569536486444924104"
> \
> "432077134494704956584678850987433944221254487706647809158846074998871240076521"
> \
> "705751797883416625624940758906970400028121042762177111777805315317141011704666"
> \
> "599146697987317613560067087480710131795236894275219484353056783002287856997829"
> \
>
> "778347845878228911097625003026961561700250464338243776486102838312683303724292"
>
> import decimal
>
> def compress_print(d):
>     s = str(d)
>     reps = 0
>     digit = s[2]
>     i = 3
>     while s[i] == digit:
>         i += 1
>         reps += 1
>     return '{} and {} more "{}"s then {}'.format(s[:3], reps, digit, s[i:])
>
> with decimal.localcontext() as context:
>     context.prec = len(digits)-1
>     phi = decimal.Decimal(digits)
>     id1 = phi**2 + phi**-2    # Identity 1 (== 3)
>     id2 = 8 * phi**2 - phi**6 # Identity 2 (== 3)
>     print('Phi is {} digits long, {}...{}'.format(len(digits) - 1,
> digits[:5], digits[-5:]))
>     print('The 1st identity is', compress_print(id1))
>     print('The 2nd identity is', compress_print(id2))
>     print('Equal?', id1 == id2)
>     print('The difference is=', id2 - id1)
>
> Phi is 624 digits long, 1.618...24292
The 1st identity is 2.9 and 621 more "9"s then 8
The 2nd identity is 3.0 and 620 more "0"s then 2
Equal? False
The difference is= 2.2E-622
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/edu-sig/attachments/20140328/aa59e487/attachment.html>


More information about the Edu-sig mailing list