[Tutor] Interactive escape sequences

2014-01-14 Thread Christian Alexander
Hello Tutorians,

Why does the interactive prompt not recognize escape sequences in strings?
 It only works correctly if I use the print function in python 3.

>>> "Hello\nWorld"
"Hello\nWorld"

-- 
Regards,

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


[Tutor] iPython notebook In [*]: numbering

2014-01-14 Thread Krischu
Hi,

I'm new to python and ipython. After the first steps I did I found that the
numbering scheme in the Webapp (notebook) is kind of unpredicatble.
 
When I started I had In [0]:, In[1] etc.

Now the notebook starts with In [2]:, In [3]: then In [9]:

Yesterday before storing and leaving the notebook I suddenly had all In[]'s
marked like In [*]:

Is there a method behind this? Can one reorder/garbage collect the notebook?

Thanks

--
Christoph




--
View this message in context: 
http://python.6.x6.nabble.com/iPython-notebook-In-numbering-tp5043985.html
Sent from the Python - tutor mailing list archive at Nabble.com.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Interactive escape sequences

2014-01-14 Thread Alan Gauld

On 14/01/14 07:42, Christian Alexander wrote:


Why does the interactive prompt not recognize escape sequences in
strings?  It only works correctly if I use the print function in python 3.

 >>> "Hello\nWorld"
"Hello\nWorld"


That depends on how you define "correctly"...

When you evaluate an expression at the Python prompt Python prints the 
repr() of the value. For strings that includes the quotes and the \n 
characters  and any other special characters it finds. The print 
function on the other hand prints the str() of the value and that 
interprets the quotes etc out


In general repr() is more useful for debugging since it shows any 
'hidden' whitespace characters. repr() by convention should return a 
value that can be evaluated and assigned to a variable, although it 
doesn't always do that for miore complex types.


hth
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos

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


Re: [Tutor] Interactive escape sequences

2014-01-14 Thread Dave Angel
 Alan Gauld  Wrote in message:
> On 14/01/14 07:42, Christian Alexander wrote:
> 
>> Why does the interactive prompt not recognize escape sequences in
>> strings?  It only works correctly if I use the print function in python 3.
>>
>>  >>> "Hello\nWorld"
>> "Hello\nWorld"
> 
> That depends on how you define "correctly"...
> 
> When you evaluate an expression at the Python prompt Python prints the 
> repr() of the value. For strings that includes the quotes and the \n 
> characters  and any other special characters it finds. The print 
> function on the other hand prints the str() of the value and that 
> interprets the quotes etc out
> 
> In general repr() is more useful for debugging since it shows any 
> 'hidden' whitespace characters. repr() by convention should return a 
> value that can be evaluated and assigned to a variable, although it 
> doesn't always do that for miore complex types.
> 

I'd like to elaborate,  Christian.   The escape sequence in the
 literal string has been processed by the interpreter in either
 case by the time the string object has been created. What makes
 the repr logic important is that it adds the quotation marks, and
 turns unprintables into escape sequences.  It has absolutely no
 access to the literal you started with.

See for example

"""this
one"""

or

"\x41"




-- 
DaveA



Android NewsGroup Reader
http://www.piaohong.tk/newsgroup

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


Re: [Tutor] Interactive escape sequences

2014-01-14 Thread Peter Otten
Christian Alexander wrote:

> Hello Tutorians,
> 
> Why does the interactive prompt not recognize escape sequences in strings?
>  It only works correctly if I use the print function in python 3.
> 
 "Hello\nWorld"
> "Hello\nWorld"

The way python shows objects in the interactive interpreter has been found 
the most useful for the intended purpose -- to explore python objects and to 
provide a debugging aid. But you can customise the behaviour by defining 
your own displayhook:

>>> import builtins
>>> import sys
>>> def dh(obj):
... if obj is not None:
... builtins._ = obj
... print(obj)
... 
>>> sys.displayhook = dh
>>> "hello\nworld"
hello
world


For a more robust version as a possible starting point for your own efforts 
see:

http://docs.python.org/dev/library/sys.html#sys.displayhook

Personally, I recommend that you use the interactive interpreter as is some 
more -- it'll grow on you. 

You may also give IPython  a try.

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


Re: [Tutor] Interactive escape sequences

2014-01-14 Thread eryksun
On Tue, Jan 14, 2014 at 2:42 AM, Christian Alexander
 wrote:
>
> Why does the interactive prompt not recognize escape sequences in strings?
> It only works correctly if I use the print function in python 3.
>
 "Hello\nWorld"
> "Hello\nWorld"

Let's manually compile the following source string:

src = r'"Hello\n"'

Here's how the input would look when typed at the prompt:

>>> print(src)
"Hello\n"

Compile it with the dummy filename of '' and in 'single' mode,
as is done for the interactive prompt:

>>> code = compile(src, '', 'single')

Then disassemble the code object:

>>> dis.dis(code)
  1   0 LOAD_CONST   0 ('Hello\n')
  3 PRINT_EXPR
  4 LOAD_CONST   1 (None)
  7 RETURN_VALUE

The string literal is constant 0 in the code object. Constants are
stored in the code's `co_consts` tuple. Let's map `ord` to the string:

>>> print(*[(c, ord(c)) for c in code.co_consts[0]], sep='\n')
('H', 72)
('e', 101)
('l', 108)
('l', 108)
('o', 111)
('\n', 10)

As you can see, '\n' is used to represent the linefeed control
character, which has Unicode ordinal 10 (0x0A). It's a convenient
representation that you can actually evaluate using `eval` or `exec`.
Not all object representations have this evaluation property. For
example, the representation of an io file object can't be evaluated.
But simple types usually support this ability.

Refer back to the disassembled code object. It loads the string
constant onto the stack. Then it executes the instruction PRINT_EXPR.
This instruction in turn calls `sys.displayhook`, which defaults to a
built-in function that prints the representation of the object and
stores a reference to it as `_` in the builtins namespace.

Feel free to replace the `sys.displayhook` function if you don't like
the default output. Off the top of my head, here's a function that
uses `print` instead, and stores previously printed results in a list:

def mydisplayhook(obj):
import builtins
if not (hasattr(builtins, '_') and
isinstance(builtins._, list)):
builtins._ = []
if obj is not None and obj is not builtins._:
builtins._.append(obj)
print(obj) # usr str instead of repr

>>> import sys
>>> sys.displayhook = mydisplayhook

>>> "Hello\n"
Hello

>>> 1
1
>>> 2
2
>>> 3
3
>>> _
['Hello\n', 1, 2, 3]
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Interactive escape sequences

2014-01-14 Thread Steven D'Aprano
On Tue, Jan 14, 2014 at 02:42:07AM -0500, Christian Alexander wrote:
> Hello Tutorians,
> 
> Why does the interactive prompt not recognize escape sequences in strings?
>  It only works correctly if I use the print function in python 3.
> 
> >>> "Hello\nWorld"
> "Hello\nWorld"

I'm afraid that you are misinterpreting what you are seeing. Regardless 
of whether you use the interactive prompt or not, or whether you print 
the string, the string "Hello\nWorld" contains the words "Hello" and 
"World" separated by a newline.

What happens when you display the string?

When you use print, it gets printed to the screen, which means that 
newline actually causes a new line. In addition, tabs cause the text to 
be indented. So:

py> s = "Hello\nWorld\t!"
py> print s
Hello
World   !


But in addition to just printing the string, we can print the 
*representation* of the string, which shows control characters in 
escaped form and includes quotation marks:

py> print repr(s)
'Hello\nWorld\t!'


You'll notice that the repr() of the string is just like what you typed 
as a string literal, except that I typed double quotes " and Python uses 
single quotes ' by default.

What happens if we don't use print, but just enter the string?

py> s
'Hello\nWorld\t!'


The interactive interpreter chooses to display the repr() of the string, 
rather than print the string. The reason for this is that, in general, 
it is more useful to see the repr() while debugging or experimenting 
interactively, and if you wish to the see the printed version of the 
string, it's easy enough to use print.


Note: my examples above are using Python 2. In Python 3, you need to 
use round brackets after the print, e.g. "print(s)".



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


Re: [Tutor] iPython notebook In [*]: numbering

2014-01-14 Thread eryksun
On Tue, Jan 14, 2014 at 3:22 AM, Krischu  wrote:
> When I started I had In [0]:, In[1] etc.
>
> Now the notebook starts with In [2]:, In [3]: then In [9]:
>
> Yesterday before storing and leaving the notebook I suddenly had all In[]'s
> marked like In [*]:
>
> Is there a method behind this? Can one reorder/garbage collect the notebook?

Did you try restarting the kernel and then recalculating the cells?

Kernel => Restart
  Cell => Run All
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Problems using odeint

2014-01-14 Thread Joel Goldstick
On Tue, Jan 14, 2014 at 1:40 PM, Grace Roberts
 wrote:
> Hi,
>
> I'm a python beginner, currently using scipy's 'odeint' to compute to a set
> of ODEs (obtained by splitting Newton's law of gravity ma=-Gm1m2r/r^3 in two
> ordinary differentials). The idea is that I'm modelling the orbit of a
> satellite as it approaches Mars.
>
> I have two problems:
> -For certain initial conditions the programme displays impossible orbits,
> showing the satellite making immediate sharp turns or jumping up and down in
> velocity. The exact same code can also end up displaying different graphs
> when run multiple times. For example when initial conditions are set at:
> xx0=[1000.,1.,1000.,1.].
> -Often when run an error message appears saying: "Excess work done on this
> call (perhaps wrong Dfun type). Run with full_output = 1 to get quantitative
> information." You can see that as part of the odeint function I tried to
> stop the excess work by increasing the maxstep and I also tried to run with
> full_output =1. It's quite possible I haven't done this right. If I have,
> what else can I do to stop this message from appearing?
>
> I've attached a quick print-screen of the code.
>
> Any help is much appreciated.
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

Sorry I can't help you, but the way it works best here is that you
actually cut and paste your code in your email.  Use text mode, not
html.  Then run your code, and cut and paste the traceback to your
email.

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


Re: [Tutor] Problems using odeint

2014-01-14 Thread Steven D'Aprano
Hi Grace, and welcome,

My reply is interleaved with your comments.

On Tue, Jan 14, 2014 at 06:40:03PM +, Grace Roberts wrote:
> Hi,
> I'm a python beginner, currently using scipy's 'odeint' to compute to 
> a set of ODEs (obtained by splitting Newton's law of gravity 
> ma=-Gm1m2r/r^3 in two ordinary differentials). The idea is that I'm 
> modelling the orbit of a satellite as it approaches Mars. 

Unfortunately, I don't think there is anyone here who is very familiar 
with scipy. Including me. I'll try my best to give some helpful 
comments, but take them with a grain of salt.


> I have two 
> problems:-For certain initial conditions the programme displays 
> impossible orbits, showing the satellite making immediate sharp turns 
> or jumping up and down in velocity.

I'm not an expert on numeric code, but my first instinct on reading this 
is to think that you're suffering numerical instability in your ODEs. 
It's been too many years since I've done ODEs to be much help to you 
here, but can you double check that the ODE you are using is 
mathematically correct and any constants are expressed to sufficient 
accuracy?


> The exact same code can also end 
> up displaying different graphs when run multiple times. For example 
> when initial conditions are set at: 
> xx0=[1000.,1.,1000.,1.].

If what you say is accurate, that strongly suggests that the system you 
are modelling is chaotic, and tiny changes in initial conditions lead to 
major changes in the output. This problem may be inherent in the 
physical system.


> -Often when run an error message 
> appears saying: "Excess work done on this call (perhaps wrong Dfun 
> type). Run with full_output = 1 to get quantitative information." You 
> can see that as part of the odeint function I tried to stop the excess 
> work by increasing the maxstep and I also tried to run with 
> full_output =1. It's quite possible I haven't done this right. If I 
> have, what else can I do to stop this message from appearing? I've 
> attached a quick print-screen of the code. Any help is much 
> appreciated.

Unfortunately print-screen is not so helpful here. What we really need 
is your code copy and pasted as text, if possible directly in the body 
of your email. If it is more than a hundred lines or so, it will 
probably be better to attach your .py file to the email.

I will try to find a program that will let me view your .docx file (like 
many of us here, I'm a Linux user and don't have access to Microsoft 
Office) so I can at least see the print-screen, but being able to access 
it as text rather than just a screenshot would make it much easier to 
help you.

Regards,


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


Re: [Tutor] Problems using odeint

2014-01-14 Thread Danny Yoo
Hi Grace,


I see that you're asking about the behavior of scipy.integrate.odeint():

   
http://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.odeint.html#scipy.integrate.odeint

Unfortunately this might be too domain specific of a question for
folks here at Tutor.  I don't see anything in the source code
screenshot that is ringing any warnings in my head.

(As Joel notes, please do a copy-and-paste of the textual content of
your program into the email next time.  Screenshots are significantly
harder for people to look at.)


You may want to ask your question on a mailing list specific to SciPy;
the audience there may have more familiarity with the gotcha you're
running into.  You can find out about the SciPy-user mailing list at:

http://www.scipy.org/scipylib/mailing-lists.html#mailing-lists
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Problems using odeint

2014-01-14 Thread Steven D'Aprano
On Tue, Jan 14, 2014 at 06:40:03PM +, Grace Roberts wrote:
[...]
> I've attached a quick print-screen of the code.

I've managed to have a look at the screenshot, there are no obvious 
problems, but I'm not a Scipy expert. If you do get an answer from a 
Scipy mailing list, I would really appreciate it if you were to write 
back here with an explanation.

In the meantime, I have a couple of comments about your code. You 
initialise some constants like this:

G = -6.67*10**-11
Mm = 6.4*10**23

You can write them more compactily as:

G = -6.67e-11
Mm = 6.4e23


Notice that you have made G a negative value? That is unusual, normally 
G is quoted as a positive quantity, G = 6.67e-11 m³/(kg*s²), or the same 
value with units N (m/kg)². Either way, G is given a positive value. 
Possibly making G a negative quantity is causing the problems?


Another minor comment on your code, in the f(x, t) function you have a
line taking a square root:

r = (x[0]**2 + x[2]**2)**0.5


You can improve the accuracy of that radius calculation by using 
the hypot function. First, at the top of the file, import 
the math module:

import math


Then inside the f(x,t) function change the calculation of r to this:

r = math.hypot(x[0], x[2])


Hope this is helpful,



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


Re: [Tutor] Problems using odeint

2014-01-14 Thread eryksun
On Tue, Jan 14, 2014 at 1:40 PM, Grace Roberts
 wrote:
>
> -For certain initial conditions the programme displays impossible orbits,
> showing the satellite making immediate sharp turns or jumping up and down in
> velocity. The exact same code can also end up displaying different graphs
> when run multiple times. For example when initial conditions are set at:
> xx0=[1000.,1.,1000.,1.].

The trajectory is decaying into the planet. In real life it hits the
surface. In the model it continues until the radius is 0. As the
radius approaches zero, odeint will have problems converging.

I ran your calculation for Phobos, assuming a perfectly circular
orbit. I started with `Rsx == Rxy` and `Vsx = -Vsy`. It steps through
a cycle in the expected time.

https://en.wikipedia.org/wiki/Phobos_%28moon%29

Output Plot:
http://i.imgur.com/Jh0sbnT.png


import numpy as np
from scipy import integrate
import matplotlib.pyplot as plt

G = 6.674e-11
Mm = 6.4185e23  # Mars mass
Rs = 9.376e6# Phobos orbit semi-major axis
Vs = 2.138e3# Phobos orbit average velocity
Ts = 2.7554e4   # Phobos orbit period

def f(y, t):
rx, ry, vx, vy = y
r = np.hypot(rx, ry)
ax = -G * Mm * rx / r ** 3
ay = -G * Mm * ry / r ** 3
return vx, vy, ax, ay

Rsx = Rsy = (Rs ** 2 / 2) ** 0.5
Vsy = (Vs ** 2 / 2) ** 0.5
Vsx = -Vsy
y0 = [Rsx, Rsy, Vsx, Vsy]

t = np.linspace(0, Ts, Ts * 10)

y, info = integrate.odeint(f, y0, t, full_output=1)
rx, ry, vx, vy = y.T

plt.subplot(211)
plt.title('Position')
plt.plot(t, rx, t, ry)
plt.grid(); plt.axis('tight')
plt.subplot(212)
plt.title('Velocity')
plt.plot(t, vx, t, vy)
plt.grid(); plt.axis('tight')
plt.show()
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor