Question about output different with command dis.dis(code)

2015-11-26 Thread fl
Hi,

I see the following from a previous post:


Python 1.5.2 (#1, Aug 27 2012, 09:09:18)  [GCC 4.1.2 20080704 (Red Hat 
4.1.2-52)] on linux2 
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam 
>>> import dis 
>>> code = compile("(1, 2, 3)", "", "eval") 
>>> dis.dis(code) 
  0 SET_LINENO  0 
  3 LOAD_CONST  0 (1) 
  6 LOAD_CONST  1 (2) 
  9 LOAD_CONST  2 (3) 
 12 BUILD_TUPLE 3 
 15 RETURN_VALUE 


When I run the above three line code, I get the following:

dis.dis(code)
  1   0 LOAD_CONST   3 ((1, 2, 3))
  3 RETURN_VALUE


on my Windows 7 PC Canopy. Are there something, my input or Python difference
make the output different?

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


What use is this class?

2015-11-29 Thread fl
Hi,

When I search around tutorial about None, I came across this link:

http://jaredgrubb.blogspot.ca/2009/04/python-is-none-vs-none.html

I don't understand what use of this class example:



>>> class Zero(): # a class that is zero
...def __nonzero__(self):
...   return False


I can only get the following code running:

cz1=Zero()
cz1.__nonzero__()
Out[119]: False


Here are my questions:
1. Is there any other means to use class Zero?
2. What connection to None on the original author's intention?


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


variable vs. object

2015-11-29 Thread fl
Hi,

I read several parts on line about Python that everything in Python is an 
object. Yes, it is a key difference with other languages. Then, I read a page
it says variables: global and local variable at:

http://www.tutorialspoint.com/python/python_functions.htm


I have a question that whether variables are objects?

For example,

a=10

'a' is an integer. Is it an object too?

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


Question about code writing '% i, callback'

2015-11-30 Thread fl
Hi,

I come across the following code snippet.





for i in range(10):
def callback():
print "clicked button", i
UI.Button("button %s" % i, callback)




The content inside parenthesis in last line is strange to me. 

"button %s" % i, callback


That is, the writing looks like recognized as three items when I try with a
class definition (it can run with this):

class buibutton():
print 'sd'
def __nonzero__(self):
   return False
   
def Button(str, ii, callbackk):

return


Could you explain it to me?

The link is here:

http://effbot.org/zone/default-values.htm

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


Re: Question about code writing '% i, callback'

2015-11-30 Thread fl
On Monday, November 30, 2015 at 11:44:44 AM UTC-5, fl wrote:
> Hi,
> 
> I come across the following code snippet.
> 
> 
> 
> 
> 
> for i in range(10):
> def callback():
> print "clicked button", i
> UI.Button("button %s" % i, callback)
> 
> 
> 
> 
> The content inside parenthesis in last line is strange to me. 
> 
> "button %s" % i, callback
> 
> 
> That is, the writing looks like recognized as three items when I try with a
> class definition (it can run with this):
> 
> class buibutton():
> print 'sd'
> def __nonzero__(self):
>return False
>
> def Button(str, ii, callbackk):
> 
> return
> 
> 
> Could you explain it to me?
> 
> The link is here:
> 
> http://effbot.org/zone/default-values.htm
> 
> Thanks,

Thanks for the replies. Now, I have the following code:



class buibutton():
print 'sd'
def __nonzero__(self):
   return False
   
def Button(self, ii, callbackk):
callbackk()
return
UI=buibutton()


for i in range(10):
def callback():
print "clicked button", i
UI.Button("button %s" % i, callback)


To my surprise, the output is not the original link expected. i.e. it is 
the same with binding to the current values:

for i in range(10):
def callback(i=i):


I have the output for both:


%run "C:/Users/CCS6_1_Tiva_C/Python_prj0/uibutton1.py"
sd
clicked button 0
clicked button 1
clicked button 2
clicked button 3
clicked button 4
clicked button 5
clicked button 6
clicked button 7
clicked button 8
clicked button 9

%run "C:\Users\CCS6_1_Tiva_C\Python_prj0\uibutton0.py"
sd
clicked button 0
clicked button 1
clicked button 2
clicked button 3
clicked button 4
clicked button 5
clicked button 6
clicked button 7
clicked button 8
clicked button 9

I don't know why it does not have the not expected format output:

sd
clicked button 9
clicked button 9
clicked button 9
clicked button 9
clicked button 9
clicked button 9
clicked button 9
clicked button 9
clicked button 9
clicked button 9


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


Re: Question about code writing '% i, callback'

2015-11-30 Thread fl
On Monday, November 30, 2015 at 12:37:52 PM UTC-5, Terry Reedy wrote:
> On 11/30/2015 11:44 AM, fl wrote:
> 
> > I come across the following code snippet.
> 
> > for i in range(10):
> >  def callback():
> >  print "clicked button", i
> >  UI.Button("button %s" % i, callback)
> 
> > http://effbot.org/zone/default-values.htm
> 
> Note that the above is an intentional example of common buggy code.  It 
> is followed by a version that works, with 'i=i' added to the callback 
> header.
> 
> -- 
> Terry Jan Reedy

With the following code, there is no bug as the original author said.


class buibutton():
print 'sd'
def __nonzero__(self):
   return False
   
def Button(self, ii, callbackk):
callbackk()
return

for i in range(10):
def callback():
print "clicked button", i
UI.Button("button %s" % i, callback)

only to find that all callbacks print the same value (most likely 9, in this 
case). 

Why does it have no bug?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Question about code writing '% i, callback'

2015-11-30 Thread fl
On Monday, November 30, 2015 at 12:02:57 PM UTC-5, Ian wrote:
> On Mon, Nov 30, 2015 at 10:44 AM, fl  wrote:
> > I come across the following code snippet.
> >
> > for i in range(10):
> > def callback():
> > print "clicked button", i
> > UI.Button("button %s" % i, callback)
> >
> > The content inside parenthesis in last line is strange to me.
> >
> > "button %s" % i, callback
> 
> These are the arguments being passed to UI.Button. The first argument is:
> 
> "button %s" % i
> 
> This is an example of printf-style string formatting. See the link
> that Zachary posted.
> 
> The second argument is the function named callback.
> 
> > That is, the writing looks like recognized as three items when I try with a
> > class definition (it can run with this):
> >
> > class buibutton():
> > print 'sd'
> > def __nonzero__(self):
> >return False
> >
> > def Button(str, ii, callbackk):
> >
> > return
> >
> >
> > Could you explain it to me?
> 
> How is this related to the example above?
> 
> Here, Button is defined as a method of a class. Since it's a method,
> the first parameter is the "self" parameter, which will implicitly
> take the value of the class instance that you're calling the Button
> method on. If you're trying to call this like above, then the second
> parameter "ii" will take the value of the string from the example
> above, and callbackk will take the value of the callback argument from
> above.
> 
> Thus, the method that you've defined has three parameters but only
> takes two explicit arguments.

"How is this related to the example above? 

Here, Button is defined as a method of a class. Since it's a method, 
the first parameter is the "self" parameter, which will implicitly 
take the value of the class instance that you're calling the Button 
method on."

Thanks Ian. I created the class because I want to use the original example
line 

 UI.Button("button %s" % i, callback)

Is there another way to use the above line without my class definition?
I do feel that my created class does not match well with the above line
because the first item "button %s" does not fit __self__ in the class.
My understanding about the above line code may not correct. This may further
result in not the original bug pops up.

Thanks,


 


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


Re: Could you explain this rebinding (or some other action) on "nums = nums"?

2015-11-30 Thread fl
On Wednesday, June 24, 2015 at 8:17:08 PM UTC-4, Chris Angelico wrote:
> On Thu, Jun 25, 2015 at 9:52 AM, fl  wrote:
> > The reason is that list implements __iadd__ like this (except in C, not 
> > Python):
> >
> > class List:
> > def __iadd__(self, other):
> > self.extend(other)
> > return self
> > When you execute "nums += more", you're getting the same effect as:
> >
> > nums = nums.__iadd__(more)
> > which, because of the implementation of __iadd__, acts like this:
> >
> > nums.extend(more)
> > nums = nums
> > So there is a rebinding operation here, but first, there's a mutating 
> > operation, and the rebinding operation is a no-op.
> 
> It's not a complete no-op, as can be demonstrated if you use something
> other than a simple name:
> 
> >>> tup = ("spam", [1, 2, 3], "ham")
> >>> tup[1]
> [1, 2, 3]
> >>> tup[1].extend([4,5])
> >>> tup[1] = tup[1]
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: 'tuple' object does not support item assignment
> >>> tup
> ('spam', [1, 2, 3, 4, 5], 'ham')
> >>> tup[1] += [6,7]
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: 'tuple' object does not support item assignment
> >>> tup
> ('spam', [1, 2, 3, 4, 5, 6, 7], 'ham')
> 
> The reason for the rebinding is that += can do two completely
> different things: with mutable objects, like lists, it changes them in
> place, but with immutables, it returns a new one:
> 
> >>> msg = "Hello"
> >>> msg += ", world!"
> >>> msg
> 'Hello, world!'
> 
> This didn't change the string "Hello", because you can't do that.
> Instead, it rebound msg to "Hello, world!". For consistency, the +=
> operator will *always* rebind, but in situations where that's not
> necessary, it rebinds to the exact same object.
> 
> Does that answer the question?
> 
> ChrisA

I have revisit the past post. In the example code snippet:

type(tup[1])
Out[162]: list

'list' is mutable. Why does the following line have errors?
In practical Python code, error is not acceptable. Then, what purpose is
for the following code here to show?

Thanks,


>>> tup[1] += [6,7] 
Traceback (most recent call last): 
  File "", line 1, in  
TypeError: 'tuple' object does not support item assignment 
-- 
https://mail.python.org/mailman/listinfo/python-list


Question about python package numpy

2015-03-01 Thread fl
Hi,

It is difficult to install numpy package for my PC Windows 7, 64-bit OS. In
the end, I install Enthought Canopy, which is recommended on line because it 
does install numpy automatically. Now, I can test it with

import numpy

it succeeds. On http://wiki.scipy.org/Cookbook, it shows some interesting
code example snippet, such as Cookbook / ParticleFilter, Markov chain etc.

I don't know how I can access these code examples, because I don't know where
Enthought Canopy installs these package.

Could you help me on using numpy examples?


Thanks,

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


Re: Question about python package numpy

2015-03-01 Thread fl
On Sunday, March 1, 2015 at 1:25:59 PM UTC-8, Andrea D'Amore wrote:
> On 2015-03-01 20:32:34 +, fl said:
> 
> > import numpy
> > it succeeds. On http://wiki.scipy.org/Cookbook, it shows some interesting
> > code example snippet, such as Cookbook / ParticleFilter, Markov chain etc.
> 
> > I don't know how I can access these code examples, because I don't know 
> > where
> > Enthought Canopy installs these package.
> 
> Did you check Canopy's documentation?
> 
> Are you sure the examples in cookbook are installed with the package?
> You can print numpy.__file__ to know where the package is installed.
> 
> At [1] I see "You can get the source code for this tutorial here: 
> tandemqueue.py" with link to the file, why don't you get the source 
> files for the example from their pages?
> 
> 
> [1] http://wiki.scipy.org/Cookbook/Solving_Large_Markov_Chains
> 
> -- 
> Andrea

Thanks for your reply. I learned Python for about one week ago. The link 
in your reply does look like executable. But the second snippet about 
particle filter, see below please, looks award. i.e. I do not see the 
connection between the first and the second code snippet. I should save
them to one .py file? Or save to two files? What name should be for the
second file?


Thanks again.



...
http://wiki.scipy.org/Cookbook/ParticleFilter

The following code shows the tracker operating on a test sequence featuring 
a moving square against a uniform background.
Toggle line numbers
   1 if __name__ == "__main__":
   2   from pylab import *
   3   from itertools import izip
   4   import time
   5   ion()
-- 
https://mail.python.org/mailman/listinfo/python-list


Question about 'x' in pymc.invlogit(a+b*x)

2015-03-07 Thread fl
Hi,

I once learnt Python for a few weeks. Now, I try to using a Python package
pymc. It has the following example code:




import pymc
import numpy as np
n = 5*np.ones(4,dtype=int)
x = np.array([-.86,-.3,-.05,.73])
alpha = pymc.Normal('alpha',mu=0,tau=.01)
beta = pymc.Normal('beta',mu=0,tau=.01)
@pymc.deterministic
def theta(a=alpha, b=beta):
 """theta = logit^{-1}(a+b)"""
 return pymc.invlogit(a+b*x)



d = pymc.Binomial('d', n=n, p=theta, value=np.array([0.,1.,3.,5.]),\
observed=True)




I don't understand the 'x' in pymc.invlogit(a+b*x). Could you help me on it?


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


What use for reversed()?

2015-05-31 Thread fl
Hi,

I have a string b='1234'. I run: br=reversed(b)

I hope that I can print out '4321' by:

for br in b

but it complains:
SyntaxError: invalid syntax


My questions:
1. What use for reversed(). I do not find an example on web.

2. If reversed() is wrong the my purpose, what method can do it? i.e. '4321'
out.


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


Are there any other better ways to access a single bit of string of digits?

2015-05-31 Thread fl
Hi,

I am new to Python. I would manipulate a string of hex numbers. If the first
digit is bigger than 7, the first two digits are required to add 4.

For example, '8022_3345' will be changed to '8422_3345'. The 
underscore between two 4-digit's was generated previously (i.e.
it is already in the .txt file).

I have not tried to read the .txt file to a list yet. I just try the
following:

tmp
['12345678', '23456789', '3456789a', '456789ab']

Each 8-digit hex number is assigned to a variable, such as:

digit8=tmp[0]

 
I can compare digit8[0] with 7, and so on...



The underscore, I think, can be removed by first a string replace.

My question here is:

Do you have better ways than my tmp, digit8 operation?


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


Re: Are there any other better ways to access a single bit of string of digits?

2015-05-31 Thread fl
On Sunday, May 31, 2015 at 12:53:19 PM UTC-7, Denis McMahon wrote:
> On Sun, 31 May 2015 11:36:35 -0700, fl wrote:
> > I am new to Python. I would manipulate a string of hex numbers. If the
> > first digit is bigger than 7, the first two digits are required to add
> > 4.
> What happens if the first two digits are ff, does it become 103 or 03.
> If you have __
> Do you want to create 103ff_103ff_103ff
> or
> 03ff_03ff_03ff
> or
> newnums = [ bing(x) for x in oldnums ]
> 
> It could probably be done as a single list comprehension, but it might 
> get a bit messy.
> 
> -- 
> Denis McMahon, denismfmcma...@gmail.com

Thanks for your reply. In fact, these data are from a 256 entries table. 
There is no extreme big data, such as F. 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What use for reversed()?

2015-05-31 Thread fl
On Sunday, May 31, 2015 at 4:23:19 PM UTC-7, Tim Delaney wrote:
> On 1 June 2015 at 05:40, fl  wrote:
> Hi,
> 
> The for statement must have a colon at the end of line e.g. a complete for 
> statement and block is:
> 
> for br in b:
>     print br
> 
> This will output the characters one per line (on Python 3.x), since that is 
> what the reversed() iterator will return. You will need to do something else 
> to get it back to a single string.
> 
> 
> Have you read through the python tutorials?
> 
> https://docs.python.org/3/tutorial/
> 
> 
> or for Python 2.x:
> 
> https://docs.python.org/2/tutorial/
> 
> Tim Delaney 

Thank all of you. This is the third time I learn Python. Even though I had
learnt two times, I haven't grasp it. I hope that I can gain a big jump now.
I had read the help tutorial, but forgot it since the long time. But your
reminding does make me remember these stuff.
-- 
https://mail.python.org/mailman/listinfo/python-list


Where is 'palindrome' defined?

2015-05-31 Thread fl
Hi,

When I search solution of reverse a string/number, I came across a short
function online:

>>> def palindrome(num):
return str(num) == str(num)[::-1]

I thought that it is a general function. And with the following variable:

>>> a
'1234_'

>>> parlindrome(a)

Traceback (most recent call last):
  File "", line 1, in 
parlindrome(a)
NameError: name 'parlindrome' is not defined


Then, I find that parlindrome is a special checking mirrored word.
I use Python 2.7.9. Why does the error message show   

name 'parlindrome' is not defined



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


Re: What use for reversed()?

2015-05-31 Thread fl
On Sunday, May 31, 2015 at 12:59:47 PM UTC-7, Denis McMahon wrote:
> On Sun, 31 May 2015 12:40:19 -0700, fl wrote:
> reversed returns an iterator, not a list, so it returns the reversed list 
> of elements one at a time. You can use list() or create a list from 
> reversed and then join the result:
> 
> $ python
> Python 2.7.3 (default, Dec 18 2014, 19:10:20) 
> [GCC 4.6.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> "".join(list(reversed("fred")))
> 'derf'
> >>> "".join([x for x in reversed("fred")])
> 'derf'
> 
> So reversed can do it, but needs a little help
> 
> -- 
> Denis McMahon,

I follow your reply with these trials:

>>>>list_r=(reversed("fred"))
>>> list(list_r)
['d', 'e', 'r', 'f']
>>> list_r



I have searched about list, but I still don't know what list_r is.
It looks like an index in other language. 
What else can it be used besides list(list_r)?
I want to show list_r content. This is possibly an illegal question.

Thanks, 

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


A simple print cannot run in Python Shell

2015-06-01 Thread fl
Hi,

When I try the following (They are saved in a main.py file)

#!/usr/bin/python
print r'C:\\nowhere'


It works as the tutorial, i.e. it echoes in a Windows 7
command console:


C:\\nowhere








When I run the following command in a Python 2.7.9 Shell on Windows 7,


print r'C:\\nowhere'



It has error:

>>> print r'C:\\nowhere'
SyntaxError: invalid syntax




What is the problem? Why does it behave different at .py file
and Python Shell?


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


Re: Where is 'palindrome' defined?

2015-06-01 Thread fl
On Sunday, May 31, 2015 at 9:46:56 PM UTC-7, fl wrote:
> Hi,
> 
> When I search solution of reverse a string/number, I came across a short
> function online:
> 
> >>> def palindrome(num):
>   return str(num) == str(num)[::-1]
> 
> I thought that it is a general function. And with the following variable:
> 
> >>> a
> '1234_'
> 
> >>> parlindrome(a)
> 
> Traceback (most recent call last):
>   File "", line 1, in 
> parlindrome(a)
> NameError: name 'parlindrome' is not defined
> 
> 
> Then, I find that parlindrome is a special checking mirrored word.
> I use Python 2.7.9. Why does the error message show   
> 
> name 'parlindrome' is not defined
> 
> 
> 
> Thanks,

Thanks, I realize that it was spelled wrong. Now, with the correct spelling
the result is a 'False'. I have expected it gives reversed string. Is the 
function behaves correct or not?


Thanks,




>>> a='1234'
>>> def palindrome(num):
return str(num) == str(num)[::-1]
>>> palindrome(a)
False
>>> palindrome("fread")
False
-- 
https://mail.python.org/mailman/listinfo/python-list


How to use an iterator?

2015-06-01 Thread fl
Hi,


I read the online tutorial on iterator:

https://docs.python.org/2/library/itertools.html

I have no idea on how to use this one:

itertools.count(start=0, step=1)

BTW, I am using Python 2.7.9 on Windows 7.



I even input the following:

def count(start=0, step=1):
# count(10) --> 10 11 12 13 14 ...
# count(2.5, 0.5) -> 2.5 3.0 3.5 ...
n = start
while True:
yield n
n += step


>>> xc=count(10)
>>> xc



How to use this generator? 


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


What use of string module?

2015-06-01 Thread fl
Hi,

I read the online help about string. It lists string constants, string 
formatting, template strings and string functions. After reading these,
I am still puzzled about how to use the string module. 

Could you show me a few example about this module?

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


How to understand '_' in these tests?

2015-06-01 Thread fl
Hi,

I just know that '_' is the last result in the Python interpreter. I feel that
it is like 'ans' in Matlab. When I run the following commands. The result of
'_' are always '4'.


Because I have tried several commands, such as reversed('fred'), xx and rx,
 '4' are always there.

What is your explanation about the following?


Thanks,






>>> reversed('fred')

>>> _
'4'
>>> _
'4'
>>> xx
33223
>>> _
'4'
>>> rx=reversed('fred')
>>> _
'4'
>>> xx
33223
>>> _
'4'
>>> 
-- 
https://mail.python.org/mailman/listinfo/python-list


How to access the low digits of a list

2015-06-02 Thread fl
Hi,

I have a list:






>>> lines
['12', '42', '49', '156', '225', '36', '49', '164', '11181', '3100']



I want to access the last two digits. That is:

['12', '42', '49', '56', '25', '36', '49', '64', '81', '00']


When I try to use lines[3][0] is '1'
lines[3][1] is '5'
lines[3][2] is '6'


I don't know whether there is a way to know the length of lines[3]. Then, I
can use a -1 step to get the last two digits. Or, you may have much better 
ways to do that. Python is really too versatile I feel.

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


Could you explain lambda function to me?

2015-06-02 Thread fl
Hi,

I see the description of lambda at the online tutorial, but I cannot 
understand it. '42' is transferred to the function. What 'x' value should
be? I do not see it says that it is '0'. And, what is 'x'?








>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43


The second lambda example is even more obscure to me:

>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]


Could you explain 'key=lambda pair: pair[1]' to me?

Python grammar seems too succinct to me.


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


Please help on this sorted function

2015-06-02 Thread fl
Hi,

I try to learn sorted(). With the tutorial example:




>>> ff=sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})
>>> ff
[1, 2, 3, 4, 5]



I don't see what sorted does in this dictionary, i.e. the sequence of 
1..5 is unchanged. Could you explain it to me?


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


Re: Please help on this sorted function

2015-06-02 Thread fl
On Tuesday, June 2, 2015 at 1:20:40 PM UTC-7, fl wrote:
> Hi,
> 
> I try to learn sorted(). With the tutorial example:
> 
> 
> 
> 
> >>> ff=sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})
> >>> ff
> [1, 2, 3, 4, 5]
> 
> 
> 
> I don't see what sorted does in this dictionary, i.e. the sequence of 
> 1..5 is unchanged. Could you explain it to me?
> 
> 
> Thanks,

Excuse me. After a small modification, it can see the effect.


>>> ff=sorted({1: 'D', 2: 'B', 5: 'B', 4: 'E', 3: 'A'})
>>> ff
[1, 2, 3, 4, 5]


I am still new to Python. How to get the sorted dictionary output:

{1: 'D', 2: 'B', 3: 'A', 4: 'E', 5: 'B'}
-- 
https://mail.python.org/mailman/listinfo/python-list


Can Python function return multiple data?

2015-06-02 Thread fl
Hi,

I just see the tutorial says Python can return value in function, it does 
not say multiple data results return situation. In C, it is possible.
How about Python on a multiple data return requirement?


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


What is the difference between list() and list?

2015-06-02 Thread fl
Hi,

I find the following results are interesting, but I don't know the difference
between list() and list.






>>> nums=list()
>>> nums
[]
>>> xx=list
>>> xx

>>> nums
[]
>>> print(xx)

>>> print(nums)
[]
>>> 



Could you tell me that?

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


Re: Can Python function return multiple data?

2015-06-06 Thread fl
On Saturday, June 6, 2015 at 9:39:19 AM UTC-7, Amir Arsalan wrote:
> you can use yield structure in python for multiple return. ex:
> 
> 
> def func(a):
>     yield a*2
>     print "a*2"
>     yield a*3
>     print "a*3"
>     ...
> 
> 
> data = func(5) --> data = (10,15,... )
> 
> 
> On Wed, Jun 3, 2015 at 1:57 AM, fl  wrote:
> Hi,
> 
> 
> 
> I just see the tutorial says Python can return value in function, it does
> 
> not say multiple data results return situation. In C, it is possible.
> 
> How about Python on a multiple data return requirement?
> 
> 
> 
> 
> 
> Thanks,
> 
> --
> 
> https://mail.python.org/mailman/listinfo/python-list

Excuse me. I input the following according to your idea, but I do not 
understand how to use it from the echo. It does not show how to use
the multiple output results. I am a new Python user. Please give a little
more explanation if you could.


Thanks,

>>> def func(a):
yield a*2
print "a*2"
yield a*3
print "a*3"

>>> data=func(5)
>>> data

>>> list(data)
a*2
a*3
[10, 15]
-- 
https://mail.python.org/mailman/listinfo/python-list


Why does the unit test fail of the pyPDF2 package?

2015-06-24 Thread fl
Hi,
I want to learn some coding on PDF. After I download and install pyPDF2,
it cannot pass unit test, which is coming from the package.

I put a screen shot link here to show the console message:

http://tinypic.com/view.php?pic=fbdpg0&s=8#.VYre8_lVhBc

[IMG]http://i57.tinypic.com/fbdpg0.png[/IMG]


This Windows 7 PC has both Python 2.7 and Enthought Canopy (3.4?) installed.

I don't know whether it has conflicts or not.


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


Re: Why does the unit test fail of the pyPDF2 package?

2015-06-24 Thread fl
On Wednesday, June 24, 2015 at 9:54:12 AM UTC-7, fl wrote:
> Hi,
> I want to learn some coding on PDF. After I download and install pyPDF2,
> it cannot pass unit test, which is coming from the package.
> 
> I put a screen shot link here to show the console message:
> 
> http://tinypic.com/view.php?pic=fbdpg0&s=8#.VYre8_lVhBc
> 
> [IMG]http://i57.tinypic.com/fbdpg0.png[/IMG]
> 
> 
> This Windows 7 PC has both Python 2.7 and Enthought Canopy (3.4?) installed.
> 
> I don't know whether it has conflicts or not.
> 
> 
> Thanks,

Thanks, Steven. I don't know how to copy command console window contents 
to the forum post. I even try redirection hoping to screen contents to a 
text file, but it fails.


Yes, there are extra '\n' in the extracted, but I don't know how to suppress
it. Does anyone know how to make it the same of the expected?

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


Re: Why does the unit test fail of the pyPDF2 package?

2015-06-24 Thread fl
On Wednesday, June 24, 2015 at 9:54:12 AM UTC-7, fl wrote:
> Hi,
> I want to learn some coding on PDF. After I download and install pyPDF2,
> it cannot pass unit test, which is coming from the package.
> 
> I put a screen shot link here to show the console message:
> 
> http://tinypic.com/view.php?pic=fbdpg0&s=8#.VYre8_lVhBc
> 
> [IMG]http://i57.tinypic.com/fbdpg0.png[/IMG]
> 
> 
> This Windows 7 PC has both Python 2.7 and Enthought Canopy (3.4?) installed.
> 
> I don't know whether it has conflicts or not.
> 
> 
> Thanks,

You can make a rectangular selection by dragging over the console 
 window the mouse pointer. 

Excuse me. I don't understand your idea. On the command window, there is
no content copied through a mouse click/drag (even no screen difference).
Do you mean using Snipping Tool? That will be an image, which is not
advised as a previous poster.
Thanks,
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why does the unit test fail of the pyPDF2 package?

2015-06-24 Thread fl
On Wednesday, June 24, 2015 at 9:54:12 AM UTC-7, fl wrote:
> Hi,
> I want to learn some coding on PDF. After I download and install pyPDF2,
> it cannot pass unit test, which is coming from the package.
> 
> I put a screen shot link here to show the console message:
> 
> http://tinypic.com/view.php?pic=fbdpg0&s=8#.VYre8_lVhBc
> 
> [IMG]http://i57.tinypic.com/fbdpg0.png[/IMG]
> 
> 
> This Windows 7 PC has both Python 2.7 and Enthought Canopy (3.4?) installed.
> 
> I don't know whether it has conflicts or not.
> 
> 
> Thanks,

Thanks for the trick! I know now how new I am to the Windows.

Below is the installation message, and the unittest message.

Suspecting there are differences between Linux and Windows on '\n', I
 install pyPDF2 on Ubuntu. It has the same error. What the hell of pyPDF2
 is? I don't know what use/purpose of its test script for. This process is
 also for my learning on Python. Does anyone have the same or different 
 experiences on pyPDF2?

Thanks again.



/






ImportError: No module named Tests

C:\Python27\Tools\PyPDF2-master\Tests>cd ..

C:\Python27\Tools\PyPDF2-master>C:\python27\python.exe setup.py install
running install
running build
running build_py
creating build
creating build\lib
creating build\lib\PyPDF2
copying PyPDF2\filters.py -> build\lib\PyPDF2
copying PyPDF2\generic.py -> build\lib\PyPDF2
copying PyPDF2\merger.py -> build\lib\PyPDF2
copying PyPDF2\pagerange.py -> build\lib\PyPDF2
copying PyPDF2\pdf.py -> build\lib\PyPDF2
copying PyPDF2\utils.py -> build\lib\PyPDF2
copying PyPDF2\xmp.py -> build\lib\PyPDF2
copying PyPDF2\_version.py -> build\lib\PyPDF2
copying PyPDF2\__init__.py -> build\lib\PyPDF2
running install_lib
creating C:\python27\Lib\site-packages\PyPDF2
copying build\lib\PyPDF2\filters.py -> C:\python27\Lib\site-packages\PyPDF2
copying build\lib\PyPDF2\generic.py -> C:\python27\Lib\site-packages\PyPDF2
copying build\lib\PyPDF2\merger.py -> C:\python27\Lib\site-packages\PyPDF2
copying build\lib\PyPDF2\pagerange.py -> C:\python27\Lib\site-packages\PyPDF2
copying build\lib\PyPDF2\pdf.py -> C:\python27\Lib\site-packages\PyPDF2
copying build\lib\PyPDF2\utils.py -> C:\python27\Lib\site-packages\PyPDF2
copying build\lib\PyPDF2\xmp.py -> C:\python27\Lib\site-packages\PyPDF2
copying build\lib\PyPDF2\_version.py -> C:\python27\Lib\site-packages\PyPDF2
copying build\lib\PyPDF2\__init__.py -> C:\python27\Lib\site-packages\PyPDF2
byte-compiling C:\python27\Lib\site-packages\PyPDF2\filters.py to filters.pyc
byte-compiling C:\python27\Lib\site-packages\PyPDF2\generic.py to generic.pyc
byte-compiling C:\python27\Lib\site-packages\PyPDF2\merger.py to merger.pyc
byte-compiling C:\python27\Lib\site-packages\PyPDF2\pagerange.py to pagerange.py
c
byte-compiling C:\python27\Lib\site-packages\PyPDF2\pdf.py to pdf.pyc
byte-compiling C:\python27\Lib\site-packages\PyPDF2\utils.py to utils.pyc
byte-compiling C:\python27\Lib\site-packages\PyPDF2\xmp.py to xmp.pyc
byte-compiling C:\python27\Lib\site-packages\PyPDF2\_version.py to _version.pyc
byte-compiling C:\python27\Lib\site-packages\PyPDF2\__init__.py to __init__.pyc
running install_egg_info
Writing C:\python27\Lib\site-packages\PyPDF2-1.24-py2.7.egg-info











C:\Python27\Tools\PyPDF2-master>C:\python27\python.exe -m unittest Tests.tests >
> logt
F
==
FAIL: test_PdfReaderFileLoad (Tests.tests.PdfReaderTestCases)
Test loading and parsing of a file. Extract text of the file and compare to expe
cted
--
Traceback (most recent call last):
  File "Tests\tests.py", line 35, in test_PdfReaderFileLoad
% (pdftext, ipdf_p1_text.encode('utf-8', errors='ignore')))
AssertionError: PDF extracted text differs from expected value.

Expected:

'TheCrazyOnesOctober14,1998Herestothecrazyones.Themis\xcb\x9dts.Therebels.Thetro
ublemakers.Theroundpegsinthesquareholes.Theoneswhoseethingsdi\xcb\x99erently.The
yrenotfondofrules.Andtheyhavenorespectforthestatusquo.Youcanquotethem,disagreewi
ththem,glorifyorvilifythem.Abouttheonlythingyoucantdoisignorethem.Becausetheycha
ngethings.Theyinvent.Theyimagine.Theyheal.Theyexplore.Theycreate.Theyinspire.The
ypushthehumanraceforward.Maybetheyhavetobecrazy.Howelsecanyoustareatanemptycanva
sandseeaworkofart?Orsitinsilenceandhearasongthatsneverbeenwritten?Orgazeataredpl
anetandseealaboratoryonwheels?Wemaketoolsforthesekindsofpeople.Whilesomeseethema
sthecrazyones,weseegenius.Becausethepeoplewhoarecrazyenoughtothinktheycanchanget
heworld,aretheoneswhodo.'

Extracted:

'TheCrazyOnes\nOctober14,1998\nHerestothecrazyones.Themis\xcb\x9dts.Therebels.Th
etroublemakers.\nTheroundpegsinthesquareholes.\nTheoneswhoseethingsdi\xcb\x99ere
ntly.Theyrenotfondofrules.And\ntheyhavenorespec

Could you explain this rebinding (or some other action) on "nums = nums"?

2015-06-24 Thread fl
Hi,

I read a blog written by Ned and find it is very interesting, but I am still
unclear it in some parts. In the following example, I am almost lost at the
last line: 

nums = num


Could anyone explain it in a more detail to me?

Thanks,





...
The reason is that list implements __iadd__ like this (except in C, not Python):

class List:
def __iadd__(self, other):
self.extend(other)
return self
When you execute "nums += more", you're getting the same effect as:

nums = nums.__iadd__(more)
which, because of the implementation of __iadd__, acts like this:

nums.extend(more)
nums = nums
So there is a rebinding operation here, but first, there's a mutating 
operation, and the rebinding operation is a no-op.
-- 
https://mail.python.org/mailman/listinfo/python-list


Could you explain why this program runs?

2015-06-25 Thread fl
Hi,

I download and install pyPDF2 library online. It says the test can run by:


python -m unittest Tests.tests


tests.py is under folder PyPDF2-master\Tests\


The above command line does run and give output message, but I don't 
understand why it run after I read tests.py:


///
import os, sys, unittest

# Configure path environment
TESTS_ROOT = os.path.abspath(os.path.dirname(__file__))
PROJECT_ROOT = os.path.dirname(TESTS_ROOT)
RESOURCE_ROOT = os.path.join(PROJECT_ROOT, 'Resources')

sys.path.append(PROJECT_ROOT)

# Test imports
import unittest
from PyPDF2 import PdfFileReader


class PdfReaderTestCases(unittest.TestCase):

def test_PdfReaderFileLoad(self):
''' Test loading and parsing of a file. Extract text of the 
file and compare to expected
textual output. Expected outcome: file loads, text 
matches expected.
'''
with open(os.path.join(RESOURCE_ROOT, 'crazyones.pdf'), 'rb') 
as inputfile:

# Load PDF file from file
ipdf = PdfFileReader(inputfile)
ipdf_p1 = ipdf.getPage(0)

# Retrieve the text of the PDF
pdftext_file = open(os.path.join(RESOURCE_ROOT, 
'crazyones.txt'), 'r')
pdftext = pdftext_file.read()
ipdf_p1_text = ipdf_p1.extractText()

# Compare the text of the PDF to a known source
self.assertEqual(ipdf_p1_text.encode('utf-8', 
errors='ignore'), pdftext,
msg='PDF extracted text differs from expected 
value.\n\nExpected:\n\n%r\n\nExtracted:\n\n%r\n\n'
% (pdftext, 
ipdf_p1_text.encode('utf-8', errors='ignore')))
//

It only gives a class PdfReaderTestCases() substantiation. I have read
usage on class, but I have not found the answer.
Can you help me on why the command line can run the test?

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


Re: Could you explain why this program runs?

2015-06-25 Thread fl
On Thursday, June 25, 2015 at 8:20:52 AM UTC-7, fl wrote:
> Hi,
> 
> I download and install pyPDF2 library online. It says the test can run by:
> 
> 
> python -m unittest Tests.tests
> 
> 
> tests.py is under folder PyPDF2-master\Tests\
> 
> 
> The above command line does run and give output message, but I don't 
> understand why it run after I read tests.py:
> 
> 
> ///
> import os, sys, unittest
> 
> # Configure path environment
> TESTS_ROOT = os.path.abspath(os.path.dirname(__file__))
> PROJECT_ROOT = os.path.dirname(TESTS_ROOT)
> RESOURCE_ROOT = os.path.join(PROJECT_ROOT, 'Resources')
> 
> sys.path.append(PROJECT_ROOT)
> 
> # Test imports
> import unittest
> from PyPDF2 import PdfFileReader
> 
> 
> class PdfReaderTestCases(unittest.TestCase):
> 
>   def test_PdfReaderFileLoad(self):
>   ''' Test loading and parsing of a file. Extract text of the 
> file and compare to expected
>   textual output. Expected outcome: file loads, text 
> matches expected.
>   '''
>   with open(os.path.join(RESOURCE_ROOT, 'crazyones.pdf'), 'rb') 
> as inputfile:
>   
>   # Load PDF file from file
>   ipdf = PdfFileReader(inputfile)
>   ipdf_p1 = ipdf.getPage(0)
>   
>   # Retrieve the text of the PDF
>   pdftext_file = open(os.path.join(RESOURCE_ROOT, 
> 'crazyones.txt'), 'r')
>   pdftext = pdftext_file.read()
>   ipdf_p1_text = ipdf_p1.extractText()
>   
>   # Compare the text of the PDF to a known source
>   self.assertEqual(ipdf_p1_text.encode('utf-8', 
> errors='ignore'), pdftext,
>   msg='PDF extracted text differs from expected 
> value.\n\nExpected:\n\n%r\n\nExtracted:\n\n%r\n\n'
>   % (pdftext, 
> ipdf_p1_text.encode('utf-8', errors='ignore')))
> //
> 
> It only gives a class PdfReaderTestCases() substantiation. I have read
> usage on class, but I have not found the answer.
> Can you help me on why the command line can run the test?
> 
> Thanks,

Thanks for reading. I make it out that it is a feature of unittest module.
-- 
https://mail.python.org/mailman/listinfo/python-list


Could you explain "[1, 2, 3].remove(2)" to me?

2015-06-25 Thread fl
Hi,

I see a code snippet online:

[1, 2, 3].remove(42)

after I modify it to:

[1, 2, 3].remove(2)

and

aa=[1, 2, 3].remove(2)


I don't know where the result goes. Could you help me on the question?

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


Could you give me the detail process of 'make_incrementor(22)(33)'?

2015-06-25 Thread fl
Hi,

I read a tutorial on lambda on line. I don't think that I am clear about
the last line in its example code. It gives two parameters (22, 23). 
Is 22 for n, and 23 for x? Or, it creates two functions first. Then,
each function gets 22 while the other function gets 23?


Please help me on this interesting problem. Thanks,






>>> def make_incrementor (n): return lambda x: x + n
>>> 
>>> f = make_incrementor(2)
>>> g = make_incrementor(6)
>>> 
>>> print f(42), g(42)
44 48
>>> 
>>> print make_incrementor(22)(33)
-- 
https://mail.python.org/mailman/listinfo/python-list


Can anybody explain the '-' in a 2-D creation code?

2015-06-25 Thread fl
Hi,

I read Ned's tutorial on Python. It is very interesting. On its last
example, I cannot understand the '_' in:



board=[[0]*8 for _ in range(8)]


I know  '_' is the precious answer, but it is still unclear what it is
in the above line. Can you explain it to me?


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


Re: Can anybody explain the '-' in a 2-D creation code?

2015-06-25 Thread fl
On Thursday, June 25, 2015 at 6:24:07 PM UTC-7, Mark Lawrence wrote:
> On 26/06/2015 02:07, fl wrote:
> > Hi,
> >
> > I read Ned's tutorial on Python. It is very interesting. On its last
> > example, I cannot understand the '_' in:
> >
> >
> >
> > board=[[0]*8 for _ in range(8)]
> >
> >
> > I know  '_' is the precious answer, but it is still unclear what it is
> > in the above line. Can you explain it to me?
> >
> >
> > Thanks,
> >
> 
> Lots of people could carry on explaining things to you, but you don't 
> appear to be making any attempt to do some research before posing your 
> questions, so how about using a search engine?
> 
> -- 
> My fellow Pythonistas, ask not what our language can do for you, ask
> what you can do for our language.
> 
> Mark Lawrence

Excuse me. On one hand, I am busying on cram these Python stuff quickly for
a position. On the other hand, the search seems to me needing a little 
skill to get the goal I hope. I would really appreciate if someone can give
an example on what phrase to use in the search. I am not a lazy guy.
Thanks to all the response.
-- 
https://mail.python.org/mailman/listinfo/python-list


How to get 'od' run?

2015-11-11 Thread fl
Hi,

I am learning python. I see a previous post has such code:





   >>> data = '"binääridataa"\n'.encode('utf-8') 
   >>> f = open('roska.txt', 'wb') 
   >>> f.write(data) 
   17 
   >>> f.close() 

The .encode methods produced a bytestring, which Python likes to display 
as ASCII characters where it can and in hexadecimal where it cannot: 

   >>> data 
   b'"bin\xc3\xa4\xc3\xa4ridataa"\n' 

An "octal dump" in characters (where ASCII, otherwise apparently octal) 
and the corresponding hexadecimal shows that it is, indeed, these bytes 
that ended up in the file: 

$ od -t cx1 roska.txt 


When I run the above line with python 2.7, it does not recognize 'od'.

Is it from a package? Or some internal function?

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


What is wrong in this example code?

2015-11-12 Thread fl
Hi,

I run a code snippet from link:
http://www.python-course.eu/inheritance_example.php

It is found that there is an error in this loop:

for i in xrange(1):
x.tick()
print(x)
SyntaxError: invalid syntax


I have modified it to:
for i in x range(1):
x.tick()
print(x)
SyntaxError: invalid syntax

it still has an error. What could be wrong?

Thanks,



class Clock(object):

def __init__(self,hours=0, minutes=0, seconds=0):
self.__hours = hours
self.__minutes = minutes
self.__seconds = seconds

def set(self,hours, minutes, seconds=0):
self.__hours = hours
self.__minutes = minutes
self.__seconds = seconds

def tick(self):
""" Time will be advanced by one second """
if self.__seconds == 59:
self.__seconds = 0
if (self.__minutes == 59):
self.__minutes = 0
self.__hours = 0 if self.__hours==23  else self.__hours+1
else:
self.__minutes += 1;
else:
self.__seconds += 1;

def display(self):
print("%d:%d:%d" % (self.__hours, self.__minutes, self.__seconds))

def __str__(self):
return "%2d:%2d:%2d" % (self.__hours, self.__minutes, self.__seconds)

x = Clock()
print(x)
for i in xrange(1):
x.tick()
print(x)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is wrong in this example code?

2015-11-12 Thread fl
On Thursday, November 12, 2015 at 8:58:33 AM UTC-5, fl wrote:
> Hi,
> 
> I run a code snippet from link:
> http://www.python-course.eu/inheritance_example.php
> 
> It is found that there is an error in this loop:
> 
> for i in xrange(1):
> x.tick()
> print(x)
> SyntaxError: invalid syntax
> 
> 
> I have modified it to:
> for i in x range(1):
> x.tick()
> print(x)
> SyntaxError: invalid syntax
> 
> it still has an error. What could be wrong?
> 
> Thanks,
> 
> 
> 
> class Clock(object):
> 
> def __init__(self,hours=0, minutes=0, seconds=0):
> self.__hours = hours
> self.__minutes = minutes
> self.__seconds = seconds
> 
> def set(self,hours, minutes, seconds=0):
> self.__hours = hours
> self.__minutes = minutes
> self.__seconds = seconds
> 
> def tick(self):
> """ Time will be advanced by one second """
> if self.__seconds == 59:
> self.__seconds = 0
> if (self.__minutes == 59):
> self.__minutes = 0
> self.__hours = 0 if self.__hours==23  else self.__hours+1
>   else:
>   self.__minutes += 1;
>   else:
> self.__seconds += 1;
> 
> def display(self):
> print("%d:%d:%d" % (self.__hours, self.__minutes, self.__seconds))
> 
> def __str__(self):
> return "%2d:%2d:%2d" % (self.__hours, self.__minutes, self.__seconds)
> 
> x = Clock()
> print(x)
> for i in xrange(1):
> x.tick()
> print(x)

Solved it by this:
print(x)
for i in range(1, 1):
 x.tick()
print(x)

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


Why does 'as' not recognized?

2015-11-12 Thread fl
Hi,

When I try the following, python does not know 'as'. Why doesn't it?
Thanks,



>>> cats = ['Tom', 'Snappy', 'Kitty', 'Jessie', 'Chester']
>>> 
>>> type(cats)

>>> cats[2]
'Kitty'
>>> as=cats[2]
SyntaxError: invalid syntax
>>> as=cats
SyntaxError: invalid syntax
>>> as
SyntaxError: invalid syntax
-- 
https://mail.python.org/mailman/listinfo/python-list


Is it useful for re.M in this example?

2015-11-12 Thread fl
Hi,

I follow a web site on learning Python re. I have read the function
 description of re.m, as below.


re.MMakes $ match the end of a line (not just the end of the string) and
 makes ^ match the start of any line (not just the start of the string).

But I don't see the reason to put re.M in the example project:



#!/usr/bin/python
import re

line = "Cats are smarter than dogs";

matchObj = re.match( r'dogs', line, re.M|re.I)
if matchObj:
   print "match --> matchObj.group() : ", matchObj.group()
else:
   print "No match!!"


The tutorial (http://www.tutorialspoint.com/python/python_reg_expressions.htm)
is for a beginner as I. Is there something I don't see in the example?

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


Can Canopy Express (Free) allow install a new package (PyBayes) to it?

2015-11-13 Thread fl
I am using Canopy Express (Free) version. I want to install PyBayes package,
 but I don't see it in Package Manager of Canopy. Can I install PyBayes to
 Canopy?

Now, Canopy is the default Python on my Windows 7 PC. If Canopy does not allow
 to install PyBayes into it, can I install PyBayes to the plain Python 2.7
 (downloaded from Python website, which was installed before I installed
 Canopy), and use Python 2.7 IDLE with PyBayes? (I am concern about  Canopy
 makes the Windows Python 2.7 not the same way as before?

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


What is '@' for

2015-11-13 Thread fl
Hi,

I read the following code snippet. A question is here about '@'.
I don't find the answer online yet.

What function is it here?

BTW, below is for printing out?
"""theta = logit^{-1}(a+b)"""

but I don't see it is printed when the following could have been called.

Are you sure it would be printed out?


Thanks,





.
import pymc
import numpy as np

n = 5*np.ones(4,dtype=int)
x = np.array([-.86,-.3,-.05,.73])
alpha = pymc.Normal('alpha',mu=0,tau=.01)
beta = pymc.Normal('beta',mu=0,tau=.01)

@pymc.deterministic
def theta(a=alpha, b=beta):
"""theta = logit^{-1}(a+b)"""
return pymc.invlogit(a+b*x)

d = pymc.Binomial('d', n=n, p=theta, value=np.array([0.,1.,3.,5.]),\
observed=True)
-- 
https://mail.python.org/mailman/listinfo/python-list


Where is decorator in this example code?

2015-11-14 Thread fl
Hi,

I am learning decorator following this link:

http://thecodeship.com/patterns/guide-to-python-function-decorators/

When I read decorator on class, I don't see decorator taking in effect.
In the following code snippet, there is the same print out if I comment out
two lines 'def p_decorate(func):' and '@p_decorate'.

Can you tell me what role of decorator in this code?


Thanks,

..
def p_decorate(func):
   def func_wrapper(self):
   return "{0}".format(func(self))
   return func_wrapper

class Person(object):
def __init__(self):
self.name = "John"
self.family = "Doe"

@p_decorate
def get_fullname(self):
return self.name+" "+self.family

my_person = Person()
print my_person.get_fullname()
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Where is decorator in this example code?

2015-11-14 Thread fl
On Saturday, November 14, 2015 at 7:11:11 AM UTC-5, fl wrote:
> Hi,
> 
> I am learning decorator following this link:
> 
> http://thecodeship.com/patterns/guide-to-python-function-decorators/
> 
> When I read decorator on class, I don't see decorator taking in effect.
> In the following code snippet, there is the same print out if I comment out
> two lines 'def p_decorate(func):' and '@p_decorate'.
> 
> Can you tell me what role of decorator in this code?
> 
> 
> Thanks,
> 
> ..
> def p_decorate(func):
>def func_wrapper(self):
>return "{0}".format(func(self))
>return func_wrapper
> 
> class Person(object):
> def __init__(self):
> self.name = "John"
> self.family = "Doe"
> 
> @p_decorate
> def get_fullname(self):
> return self.name+" "+self.family
> 
> my_person = Person()
> print my_person.get_fullname()

My OP may not be clear enough. Here is the key question. After the function
definition, there is no obvious decorator application in the function call:

my_person = Person()
print my_person.get_fullname()

Where is the difference between the non-decorator and decorator in this 
example?

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


Re: Where is decorator in this example code?

2015-11-14 Thread fl
On Saturday, November 14, 2015 at 7:38:09 AM UTC-5, Chris Warrick wrote:
> On 14 November 2015 at 13:13, fl  wrote:
> > On Saturday, November 14, 2015 at 7:11:11 AM UTC-5, fl wrote:
> >> Hi,
> >>
> >> I am learning decorator following this link:
> >>
> >> http://thecodeship.com/patterns/guide-to-python-function-decorators/
> >>
> >> When I read decorator on class, I don't see decorator taking in effect.
> >> In the following code snippet, there is the same print out if I comment out
> >> two lines 'def p_decorate(func):' and '@p_decorate'.
> >>
> >> Can you tell me what role of decorator in this code?
> [snip code]
> >
> > My OP may not be clear enough. Here is the key question. After the function
> > definition, there is no obvious decorator application in the function call:
> >
> > my_person = Person()
> > print my_person.get_fullname()
> >
> > Where is the difference between the non-decorator and decorator in this
> > example?
> >
> > Thanks,
> > --
> > https://mail.python.org/mailman/listinfo/python-list
> 
> Have you tried executing the code with and without the decorator?
> 
> $ python2 without-decorator.py
> John Doe
> $ python2 with-decorator.py
> John Doe
> 
> Basically, the decorator wraps the output of your get_fullname
> function with HTML  tags.
> 
> (Running code examples is a great way to understand them.)
> 
> -- 
> Chris Warrick <https://chriswarrick.com/>
> PGP: 5EAAEA16

Thanks. I did run the code, but I did not check the difference carefully
between them.

A following problem now is about the args in class decorate. I do not see
args and kwargs are transferred by get_fullname(self).


If I change 

return "{0}".format(func(*args, **kwargs))

to

return "{0}".format(func(*args))

The outputs are the same.

But it is quite different if it is changed to:

return "{0}".format(func)

What roles are args and kwargs? I know C language.
For Python here, I don't see some rules on the args. 

Thanks again.


/
def p_decorate(func):
   def func_wrapper(*args, **kwargs):
   return "{0}".format(func(*args, **kwargs))
   return func_wrapper

class Person(object):
def __init__(self):
self.name = "John"
self.family = "Doe"

@p_decorate
def get_fullname(self):
return self.name+" "+self.family

my_person = Person()

print my_person.get_fullname()
-- 
https://mail.python.org/mailman/listinfo/python-list


What is wrong this wrapper (decorator)?

2015-11-14 Thread fl
Hi,

I follow a tutorial to learn decorator:

http://simeonfranklin.com/blog/2012/jul/1/python-decorators-in-12-steps/

I use Enthought Canopy to run the following code.
It is really strange that the wrapper does not take effect. 
In fact, I go back to the basic way (not with @):

wrapper(sub(two, one))
Out[38]: 


When I use the non-wrapper mode, it has Coord print out.
If I use wrapper, it has nothing to print out.
Due to no debug mode help, I don't see anything wrong yet.


(add(two, one))
  # nothing print out
(sub(two, three))
Out[43]: Coord:-- {'y': 300, 'x': 400}# correct is here


Anyone can help?
Thanks,




class Coordinate(object):
def __init__(self, y, x):
self.y = y
self.x = x
def __repr__(self):
return "Coord:-- " + str(self.__dict__)

def add(a, b):
return Coordinate(a.x + b.x, a.y + b.y)

def sub(a, b):
return Coordinate(a.x - b.x, a.y - b.y)

def wrapper(func):
def checker(a, b): # 1
if a.x < 0 or a.y < 0:
a = Coordinate(a.x if a.x > 0 else 0, a.y if a.y > 0 else 0)
if b.x < 0 or b.y < 0:
b = Coordinate(b.x if b.x > 0 else 0, b.y if b.y > 0 else 0)
ret = func(a, b)
if ret.x < 0 or ret.y < 0:
ret = Coordinate(ret.x if ret.x > 0 else 0, ret.y if ret.y > 0 
else 0)
return ret
return checker

one = Coordinate(100, 200)
two = Coordinate(300, 200)
three = Coordinate(-100, -100)

add = wrapper(add)
#sub = wrapper(sub)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is wrong this wrapper (decorator)?

2015-11-14 Thread fl
On Saturday, November 14, 2015 at 12:23:50 PM UTC-5, fl wrote:
> Hi,
> 
> I follow a tutorial to learn decorator:
> 
> http://simeonfranklin.com/blog/2012/jul/1/python-decorators-in-12-steps/
> 
> I use Enthought Canopy to run the following code.
> It is really strange that the wrapper does not take effect. 
> In fact, I go back to the basic way (not with @):
> 
> wrapper(sub(two, one))
> Out[38]: 
> 
> 
> When I use the non-wrapper mode, it has Coord print out.
> If I use wrapper, it has nothing to print out.
> Due to no debug mode help, I don't see anything wrong yet.
> 
> 
> (add(two, one))
>   # nothing print out
> (sub(two, three))
> Out[43]: Coord:-- {'y': 300, 'x': 400}# correct is here
> 
> 
> Anyone can help?
> Thanks,
> 
> 
> 
> 
> class Coordinate(object):
> def __init__(self, y, x):
> self.y = y
> self.x = x
> def __repr__(self):
> return "Coord:-- " + str(self.__dict__)
> 
> def add(a, b):
> return Coordinate(a.x + b.x, a.y + b.y)
> 
> def sub(a, b):
> return Coordinate(a.x - b.x, a.y - b.y)
> 
> def wrapper(func):
> def checker(a, b): # 1
> if a.x < 0 or a.y < 0:
> a = Coordinate(a.x if a.x > 0 else 0, a.y if a.y > 0 else 0)
> if b.x < 0 or b.y < 0:
> b = Coordinate(b.x if b.x > 0 else 0, b.y if b.y > 0 else 0)
> ret = func(a, b)
> if ret.x < 0 or ret.y < 0:
> ret = Coordinate(ret.x if ret.x > 0 else 0, ret.y if ret.y > 
> 0 else 0)
> return ret
> return checker
> 
> one = Coordinate(100, 200)
> two = Coordinate(300, 200)
> three = Coordinate(-100, -100)
> 
> add = wrapper(add)
> #sub = wrapper(sub)

Excuse me. I just realize that the indent made the logic incorrect.
It is different from other language. Thanks.
-- 
https://mail.python.org/mailman/listinfo/python-list


What is the right way to import a package?

2015-11-14 Thread fl
Hi,

I want to use a code snippet found on-line. It has such content:

from numpy import *
dt = 0.1
# Initialization of state matrices
X = array([[0.0], [0.0], [0.1], [0.1]])

# Measurement matrices
Y = array([[X[0,0] + abs(randn(1)[0])], [X[1,0] + abs(randn(1)[0])]])



When the above content is inside a .py document and running, there will be
 an error:

---> 15 Y = array([[X[0,0] + abs(randn(1)[0])], [X[1,0] + abs(randn(1)[0])]])
 16 #Y = ([[X[0,0]], [X[1,0] + 0]])

NameError: name 'randn' is not defined 


But when I run the above line by line at the console (Canopy), there will be
no error for the above line.

My question is: 

The import and the following are wrong. 

X = array([[0.0], [0.0], [0.1], [0.1]])

It should be:

import numpy as np
...
Y = np.array([[X[0,0] + abs(np.randn(1)[0])], [X[1,0] + abs(np.randn(1)[0])]])

This looks like the code I once saw. But the file when running has such
 error:

---> 15 Y = np.array([[X[0,0] + abs(np.randn(1)[0])], [X[1,0] + 
abs(np.randn(1)[0])]])

AttributeError: 'module' object has no attribute 'randn'

When it is run line by line at the console, it has the same error.

It is strange that the same content has errors depends on inside a file, or
at CLI console.

What is missing I don't realize? Thanks,


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


What meaning is of '#!python'?

2015-11-14 Thread fl
Hi,

I see an example Python code has such a line at the file beginning:

#!python


Is there some meaning about it?

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


Re: What meaning is of '#!python'?

2015-11-14 Thread fl
On Saturday, November 14, 2015 at 8:58:57 PM UTC-5, Chris Angelico wrote:
> On Sun, Nov 15, 2015 at 12:54 PM, fl  wrote:
> > I see an example Python code has such a line at the file beginning:
> >
> > #!python
> >
> >
> > Is there some meaning about it?
> 
> It probably didn't look exactly like that. Please, when you're asking
> questions, COPY AND PASTE rather than retyping some approximation of
> what you saw.
> 
> As it happens, I can tell what you're asking about - it's called a
> shebang - but I very much doubt that it was exactly what you wrote.
> 
> ChrisA

Excuse me. Below is copied from the .py file:

#!python
from numpy import *
from numpy.random import *


def resample(weights):
  n = len(weights)
  indices = []


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


What function is 'u0, j = random(), 0'?

2015-11-14 Thread fl
Hi,

When I read the below code, I cannot make the last line (with ##) out.



def res(weights):
  n = len(weights)
  indices = []
  C = [0.] + [sum(weights[:i+1]) for i in range(n)]
  u0, j = random(), 0  ##


If I run below code on console, it will say an error.

uu, 0.1, 0


What difference is between these two example lines?

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


Question about yield

2015-11-14 Thread fl
Hi,
I have read a couple of tutorial on yield. The following code snippet still
gives me a shock. I am told yield is a little like return. I only see one 
yield in the tutorial examples. Here it has two yields. And there are three
variables following keyword yield.
I have not tried debug function to get the running states yet.
Could you give me some explanation on this yield usage?
Or are there some high relevant tutorial on this?

Thanks, 



def pfr(sequence, pos, stepsize, n):
  seq = iter(sequence)
  x = ones((n, 2), int) * pos   # position
  f0 = seq.next()[tuple(pos)] * ones(n) # model
  yield pos, x, ones(n)/n   # weights
  for im in seq:
x += uniform(-stepsize, stepsize, x.shape)  # 
x  = x.clip(zeros(2), array(im.shape)-1).astype(int) # 
f  = im[tuple(x.T)] # s
w  = 1./(1. + (f0-f)**2)# distance
w /= sum(w) # w
yield sum(x.T*w, axis=1), x, w  # weights
if 1./sum(w**2) < n/2.: # degenerate:
  x  = x[res(w),:] # to weights
-- 
https://mail.python.org/mailman/listinfo/python-list


What meaning is 'a[0:10:2]'?

2015-11-15 Thread fl
hi,

When I learn slice, I have a new question on the help file. If I set:

pp=a[0:10:2]

pp is array([1, 3])

I don't know how a[0:10:2] gives array([1, 3]).

I know matlab a lot, but here it seems quite different. Could you tell me
what meaning a[0:10:2] is?


Thanks,



class slice(object)
 |  slice(stop)
 |  slice(start, stop[, step])
 |  
 |  Create a slice object.  This is used for extended slicing (e.g. a[0:10:2]).
-- 
https://mail.python.org/mailman/listinfo/python-list


Help on savefig parameters

2015-11-17 Thread fl
Hi,
I find the parameters of savefig function has the similar format of that of
main(*argc, **argv) in C. I have tried with savefig("temp.pdf", format='pdf'),
and it works. I get the help content of savefig() as below.
But I cannot understand why they also give: 

savefig(fname, dpi=None, facecolor='w', edgecolor='w', ...

For me, it looks like the first item, i.e. 'args' is missing.
Could you explain it to me?

Thanks,


savefig(*args, **kwargs)
Save the current figure.

Call signature::

  savefig(fname, dpi=None, facecolor='w', edgecolor='w',
  orientation='portrait', papertype=None, format=None,
  transparent=False, bbox_inches=None, pad_inches=0.1,
  frameon=None)
-- 
https://mail.python.org/mailman/listinfo/python-list


Is there any reason to introduce this intermediate variable (sz)?

2015-11-17 Thread fl
Hi,

I find the following code snippet, which is useful in my project:


n_iter = 50
sz = (n_iter,) # size of array
x = -0.37727 
z = np.random.normal(x,0.1,size=sz) 

Q = 1e-5 # process variance

# allocate space for arrays
xhat=np.zeros(sz)  
P=np.zeros(sz) 


I learn Python now and the above code seems from an experienced author.
The curious thing to me is the variable 'sz'. I have check np.zeros(shape, ..)

shape : int or sequence of ints


The introduced 'sz' is a tuple. If n_iter function is similar to a constant
in C, I don't see the reason for 'sz'. In fact, 'n_iter' is an int, which fits
the below 

np.zeros(shape)

correctly. Could you see something useful with variable 'sz'?

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


Re: Is there any reason to introduce this intermediate variable (sz)?

2015-11-17 Thread fl
On Tuesday, November 17, 2015 at 4:03:05 PM UTC-5, John Gordon wrote:
> In  fl <@gmail.com> 
> writes:
> 
> > correctly. Could you see something useful with variable 'sz'?
> 
> 'sz' is fewer characters than '(n_iter,)', which may make your code easier
> to read.
> 
> The np.zeros() function explicitly accepts an 'int or sequence of ints',
> so you don't specifically need a sequence.  Is the same true for the
> 'size' keyword argument of np.random.normal()?
> 
> -- 
> John Gordon   A is for Amy, who fell down the stairs
> @panix.com  B is for Basil, assaulted by bears
> -- Edward Gorey, "The Gashlycrumb Tinies"

Hi, I get the following for the third parameter of np.random.normal():
size : int or tuple of ints, optional

I still don't see the necessity of 'sz'. Thanks,
-- 
https://mail.python.org/mailman/listinfo/python-list


What is a function parameter =[] for?

2015-11-18 Thread fl
Hi,

I have tried the below function and find that it can remember the previous
setting value to 'val'. I think the second parameter has something on this 
effect, but I don't know the name and function of '=[]' in this application.

Could you explain a little to me?
Thanks,


def eList(val, list0=[]):
list0.append(val)
return list0
list1 = eList(12)
list1 = eList('a')
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is a function parameter =[] for?

2015-11-18 Thread fl
On Wednesday, November 18, 2015 at 5:12:44 PM UTC-5, Ian wrote:
> On Wed, Nov 18, 2015 at 2:08 PM, fl  wrote:
> > Hi,
> >
> > I have tried the below function and find that it can remember the previous
> > setting value to 'val'. I think the second parameter has something on this
> > effect, but I don't know the name and function of '=[]' in this application.
> >
> > Could you explain a little to me?
> > Thanks,
> >
> >
> > def eList(val, list0=[]):
> > list0.append(val)
> > return list0
> > list1 = eList(12)
> > list1 = eList('a')
> 
> The list0 parameter has a default value, which is [], an initially
> empty list. The default value is evaluated when the function is
> defined, not when it is called, so the same list object is used each
> time and changes to the list are consequently retained between calls.

Thanks. The amazing thing to me is that the following two line codes:
list1 = eList(12) 
list2 = eList('a')

will have both list1 and list2 the same cascaded values:

list1
Out[2]: [12, 'a']

list2
Out[3]: [12, 'a']

I have known object concept in Python.
1. Why do they have the same list value?
 Function eList must be for this purpose?
2. If I want to have two separate lists, how to avoid the above result?
 Function eList is not for this purpose?

Thanks again.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is a function parameter =[] for?

2015-11-18 Thread fl
On Wednesday, November 18, 2015 at 5:38:45 PM UTC-5, fl wrote:
> On Wednesday, November 18, 2015 at 5:12:44 PM UTC-5, Ian wrote:
> > On Wed, Nov 18, 2015 at 2:08 PM, fl  wrote:
> > > Hi,
> > >
> > > I have tried the below function and find that it can remember the previous
> > > setting value to 'val'. I think the second parameter has something on this
> > > effect, but I don't know the name and function of '=[]' in this 
> > > application.
> > >
> > > Could you explain a little to me?
> > > Thanks,
> > >
> > >
> > > def eList(val, list0=[]):
> > > list0.append(val)
> > > return list0
> > > list1 = eList(12)
> > > list1 = eList('a')
> > 
> > The list0 parameter has a default value, which is [], an initially
> > empty list. The default value is evaluated when the function is
> > defined, not when it is called, so the same list object is used each
> > time and changes to the list are consequently retained between calls.
> 
> Thanks. The amazing thing to me is that the following two line codes:
> list1 = eList(12) 
> list2 = eList('a')
> 
> will have both list1 and list2 the same cascaded values:
> 
> list1
> Out[2]: [12, 'a']
> 
> list2
> Out[3]: [12, 'a']
> 
> I have known object concept in Python.
> 1. Why do they have the same list value?
>  Function eList must be for this purpose?
> 2. If I want to have two separate lists, how to avoid the above result?
>  Function eList is not for this purpose?
> 
> Thanks again.

After several trials, I find that the cascade list is caused by the second
function parameter absent. It is interesting. Thanks.
-- 
https://mail.python.org/mailman/listinfo/python-list


Could you explain why the following generates 4 same elements list?

2015-11-18 Thread fl
Hi,

I cannot reason out why the code:

def mpl():
return [lambda x : i * x for i in range(4)]

print [m(2) for m in mpl()]
/

has result:

[6, 6, 6, 6]


I have tried to simplify the above code to an easy understanding form,
but fails. Either the modified code does not work, or it does not show
relation to the original code.
 
Could you explore it a little for me to understand it easier?

Thanks in advance.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is a function parameter =[] for?

2015-11-18 Thread fl
On Wednesday, November 18, 2015 at 7:15:05 PM UTC-5, Chris Angelico wrote:
> On Thu, Nov 19, 2015 at 11:02 AM, Ian Kelly  wrote:
> > On Wed, Nov 18, 2015 at 4:22 PM, Chris Angelico  wrote:
> >> On Thu, Nov 19, 2015 at 10:14 AM, BartC  wrote:
> >>> So, looking at some source code, a default value for certain types is only
> >>> certain to be that value for the very first call of that function?
> >>
> >> On the contrary, it is certain always to be that exact object.
> >
> > "Certain" may be a bit overly strong.
> >
>  def f(x=42):
> > ...   return x
> > ...
>  f()
> > 42
>  f.__defaults__ = (43,)
>  f()
> > 43
> 
> I'll raise you one.
> 
> >>> def f(x=42):
> ... return x
> ...
> >>> f()
> 42
> >>> import ctypes
> >>> ctypes.c_int.from_address(id(43)+ ctypes.sizeof(ctypes.c_size_t) + 
> >>> ctypes.sizeof(ctypes.c_voidp)).value=42
> >>> f.__defaults__ = (43,)
> >>> f()
> 42
> >>>
> 
> Nothing is certain in Python. And two wrongs can make a... hmm... no,
> this is not a right. It is not a privilege either. It is a dastardly
> trick played on people's minds.
> 
> ChrisA

After I try with

list1 = eList(12, [2])

and

list1 = eList(12)

it gives me new surprises. Even though I delete list1, the subsequent
list1 = eList(12)
will remember the number of '12' of the previous sequence. This is my new
question: What does 'del' do? It does not look like a thorough list deletion
 from the effect.

Thanks,

.
list1 = eList(12, [2])

list1
Out[57]: [2, 12]

list1 = eList(12)

list1
Out[59]: [12, 12, 12]

list1 = eList(12, [2])

list1
Out[61]: [2, 12]

list1 = eList(12, [2])

list1
Out[63]: [2, 12]

list1 = eList(12, [2])

list1
Out[65]: [2, 12]

list1 = eList(12)

list1
Out[67]: [12, 12, 12, 12]

list1 = eList(12)

list1
Out[69]: [12, 12, 12, 12, 12]

list1 = eList(12, [2])

list1
Out[71]: [2, 12]

list1 = eList(12)

list1
Out[73]: [12, 12, 12, 12, 12, 12]

del list1

list1 = eList(12, [2])

list1 = eList(12)

list1
Out[77]: [12, 12, 12, 12, 12, 12, 12]

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


Question about 'print' in a loop

2015-11-18 Thread fl
Hi,

>From previous post, I get many helpful replies. Now I have a new question
when I run this example code:


-
sq=[]
for xx in range(5):
print 'here'
sq.append(lambda:xx**2)

here
here
here
here
here

xx
Out[150]: 4

sq[2]()
Out[151]: 16

sq[3]()
Out[152]: 16
/

There are only one time 5 'here' printed out, but there is no 'here' print
out in thereafter call sq[2]() etc. How to understand this phenomenon?

Thanks,

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


Re: Question about 'print' in a loop

2015-11-18 Thread fl
On Wednesday, November 18, 2015 at 10:11:24 PM UTC-5, Chris Angelico wrote:
> On Thu, Nov 19, 2015 at 1:55 PM, fl  wrote:
> > There are only one time 5 'here' printed out, but there is no 'here' print
> > out in thereafter call sq[2]() etc. How to understand this phenomenon?
> 
> Code does what code should.
> 
> Before you ask for comprehension of "this phenomenon", why don't you
> tell us what you expect your code to do, and why? I just asked my
> non-programmer sister and she was completely unsurprised by what
> Python did here.
> 
> ChrisA

Excuse me. That is my unclear question.
I expect that each call sq will have one print 'here', as I suppose that
print 'here' is inside the loop.

Oh, I just realize that it is not a function. It constructs list sq.
When the loop (function as a constructor (not necessarily correct called),
it print 5 'here'.

Thanks for you feedback.
-- 
https://mail.python.org/mailman/listinfo/python-list


Is there an meaning of '[[]]' in a list?

2015-11-19 Thread fl
Hi,
In the previous exercises, I see list:
cc=[[],[],[]]

Then, I can have this:

ccc=[[[]],[[]],[[]]]

I can also have

ccc[0]
Out[158]: [[]]

ccc[0]='o'

ccc
Out[163]: ['o', [[]], [[]]]


I have question: Is there any difference between [[]] and []?
[[]] can have deeper assignment and use than 

ccc[0]='o'


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


Re: Why is it different about '\s' Matches whitespace and Equivalent to [\t\n\r\f]?

2014-07-10 Thread fl
On Thursday, July 10, 2014 7:18:01 AM UTC-4, MRAB wrote:
> On 2014-07-10 11:05, r...@gmail.com wrote:
> 
> It's equivalent to [ \t\n\r\f], i.e. it also includes a space, so
> 
> either the tutorial is wrong, or you didn't look closely enough. :-)
> 
> 
> The string starts with ' ', not '\t'.
> 
> 
> 
> 
> 
> The string starts with ' ', which isn't in the character set.
> 
> 
The '\s' description is on link:

http://www.tutorialspoint.com/python/python_reg_expressions.htm


Could you give me an example to use the equivalent pattern?

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


What does (A ``quote'' is the character used to open the string, i.e. either ' or ".) mean?

2014-07-10 Thread fl
Hi,

For me, it is difficult to understand the last line of the paragraph below in 
parenthesis (A ``quote'' is the character used to open the string, 
i.e. either ' or ".)

It talks about triple-quoted strings. Where is ``quote'' from? It has two ` and 
'.
What this different ` and ' do for here?

The link is here:
https://docs.python.org/2.0/ref/strings.html

Thank you for helping me to learn Python.



In plain English: String literals can be enclosed in matching single quotes (') 
or
double quotes ("). They can also be enclosed in matching groups of three single 
or double quotes (these are generally referred to as triple-quoted strings). The
backslash (\) character is used to escape characters that otherwise have a 
special eaning, such as newline, backslash itself, or the quote character. 
String literals 
may optionally be prefixed with a letter `r' or `R'; such strings are called raw
strings and use different rules for backslash escape sequences.

In triple-quoted strings, unescaped newlines and quotes are allowed (and are
retained), except that three unescaped quotes in a row terminate the string. (A
``quote'' is the character used to open the string, i.e. either ' or ".)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What does (A ``quote'' is the character used to open the string, i.e. either ' or ".) mean?

2014-07-10 Thread fl
On Thursday, July 10, 2014 10:14:14 AM UTC-4, Chris "Kwpolska" Warrick wrote:
> >
> 
> 
> Please don't learn from this link.  It's from 2001.  You should learn
> 
> from modern documentation: https://docs.python.org/ (if not running
> 
> 3.4.x, change the version in the top)
> 
> 
> 
> You also should not read the language reference, it's meant for people
> 
> who really care about what's under the hood.  The official tutorial is
> 
> better for learning: https://docs.python.org/3/tutorial/index.html
> 
> 
Thank you for your advice. My OP was originated from a question from this link:
https://wiki.python.org/moin/RegularExpression

It has several useful examples. Several of them are not clear to me. Please 
explain it to me. 

Is '\A' the same with '^'?
Is '\Z' the same with '$'?

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


How to decipher :re.split(r"(\(\([^)]+\)\))" in the example

2014-07-10 Thread fl
Hi,

This example is from the link:

https://wiki.python.org/moin/RegularExpression


I have thought about it quite a while without a clue yet. I notice that it uses
double quote ", in contrast to ' which I see more often until now.
It looks very complicated to me. Could you simplified it to a simple example?


Thanks,





import re
split_up = re.split(r"(\(\([^)]+\)\))",
"This is a ((test)) of the ((emergency broadcasting 
station.))")


...which produces:


["This is a ", "((test))", " of the ", "((emergency broadcasting station.))" ]
-- 
https://mail.python.org/mailman/listinfo/python-list


I am confused about ' and "

2014-07-10 Thread fl
Hi,

It is still in the Regular expression operations concept, this link:

has example using single quote mark: '

https://docs.python.org/2/library/re.html#re.split


While in this link:

https://docs.python.org/3/howto/regex.html


It gives table with quote: "

Regular String  Raw string
"ab*"   r"ab*"
"section"   r"\\section"
"\\w+\\s+\\1"   r"\w+\s+\1"


and link:

https://docs.python.org/2/library/re.html


m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")


Please tell me because I have looked it around for one hour about it.

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


How to extract digit from a number?

2014-07-21 Thread fl
Hi,

I see the following example on line, but it does not work. I do not know what is
wrong. Could you correct it for me?


Thanks,




I'm not sure what [1, 1, 0, 0, 0, 0, ...] has to do with 128, but if you want 
the 
base 10 digits:

>>> a = 1234
>>> [int(d) for d in str(a)]
>>> [1, 2, 3, 4]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to extract digit from a number?

2014-07-21 Thread fl
On Monday, July 21, 2014 4:26:25 PM UTC-4, Tim Chase wrote:
> On 2014-07-21 13:14, fl wrote:
> You don't specify *what* is wrong or what constitutes "does not
> work".  If you provide an example of what you *do* want, folks here
> can help you get closer to the code you need to do what you intend.
> 
> -tkc

The original source input is:
>>> a = 1234
>>> [int(d) for d in str(a)] 

He hopes the output is:
>>> [1, 2, 3, 4] 

In fact, I get the output is:

>>> a = 1234
>>> [int(d) for d in str(a)] 
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'str' object is not callable

BTW, I just add input:
>>> import string

The error is still there. 
Why does it say :"TypeError: 'str' object is not callable"?
-- 
https://mail.python.org/mailman/listinfo/python-list


How to use string constant?

2014-07-21 Thread fl
Hi,

I learn string constant on Python tutorial at: 
https://docs.python.org/2/library/string.html

Although it gives explanation, it does not show me any example usage.

Could you give me an example on using these options?


string.digits

string.ascii_letters



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


Question about Pass-by-object-reference?

2014-07-22 Thread fl
Hi,
I learn Python function call on tutorial. There is a link on this subject.
http://robertheaton.com/2014/02/09/pythons-pass-by-object-reference-as-explained-by-philip-k-dick/

Although it explains clearly, the figure makes me puzzled.

""Python is different. As we know, in Python, "Object references are passed by 
value".

A function receives a reference to (and will access) the same object in memory 
as
used by the caller. However, it does not receive the box that the caller is
storing this object in; as in pass-by-value, the function provides its own box 
and
creates a new variable for itself. Let's try appending again:""

On the figure, it shows that the result is [0, 1]  (Am I right on the figure?)


When I enter the command lines on my computer:
>>> list=[0]
>>> append(list)
>>> print(list)
[0]

How to understand my result and that figure?



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


Re: Question about Pass-by-object-reference?

2014-07-22 Thread fl
On Tuesday, July 22, 2014 3:04:09 PM UTC-4, fl wrote:
Hi, 
Excuse me. I find that the OP misses some info. I rewrite it again:

I learn Python function call on tutorial. There is a link on this subject. 
http://robertheaton.com/2014/02/09/pythons-pass-by-object-reference-as-explained-by-philip-k-dick/
 

Although it explains clearly, the figure makes me puzzled. 

""Python is different. As we know, in Python, "Object references are passed by 
value". 

A function receives a reference to (and will access) the same object in memory 
as used by the caller. However, it does not receive the box that the caller is
storing this object in; as in pass-by-value, the function provides its own box 
and creates a new variable for itself. Let's try appending again:"" 

On the figure, I understand the figure about append function. Here is the lines:

When I enter the command lines on my computer: 
>>> def append(list):
... list.append(1)
... 
>>> list=[0]
>>> append(list)
>>> print(list)
[0, 1]



But I don't understand the reassign function result:

>>> def reassign(list):
... list=[0,1]
... 
>>> list=[0]
>>> reassign(list)
>>> print list
[0]

Questions:
1. From the tutorial explanation, both function append and reassign use 
pass-by-object-reference. Is it right?

2. The tutorial says: "The caller doesn't care if you reassign the function's 
box. Different boxes, same content." about the reassign function. I don't
understand "Different boxes, same content". It uses different boxes (I agree).
But the results are different for the caller ([0]) and the function reassign 
([0, 1]).


What is wrong with my understanding? 



Thanks a lot, 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Question about Pass-by-object-reference?

2014-07-22 Thread fl
On Tuesday, July 22, 2014 3:32:19 PM UTC-4, Ned Batchelder wrote:
> On 7/22/14 3:04 PM, fl wrote:
> it is here: http://nedbatchelder.com/text/names.html
> > When I enter the command lines on my computer:
> I recommend putting the code into a .py file, and 
> running it all at once.  Then if it doesn't do what you expect, 
> Ned Batchelder, http://nedbatchelder.com


Thanks Ned. You give a great helpful link. And your advice on .ph file is the
key problem of my OP (Thus I rewrite my post again).

Your link makes complicate things much easier. I read it carefully.
-- 
https://mail.python.org/mailman/listinfo/python-list


Why does not pprint work?

2014-07-22 Thread fl
Hi,

I read web tutorial at: 

http://nedbatchelder.com/blog/201308/names_and_values_making_a_game_board.html

I enter the example lines of that website:


import pprint
board = [ [0]*8 ] * 8
pprint(board)


It echos error with Python 2.7:

Traceback (most recent call last):
  File "C:\Python27\Lib\SITE-P~1\PYTHON~2\pywin\framework\scriptutils.py", 
line 323, in RunScript
debugger.run(codeObject, __main__.__dict__, start_stepping=0)
  File "C:\Python27\Lib\SITE-P~1\PYTHON~2\pywin\debugger\__init__.py", 
line 60, in run
_GetCurrentDebugger().run(cmd, globals,locals, start_stepping)
  File "C:\Python27\Lib\SITE-P~1\PYTHON~2\pywin\debugger\debugger.py", 
line 655, in run
exec cmd in globals, locals
  File "C:\cygwin64\home\Jeff\Python_lesson\ppn.py", line 1, in 
import pprint
TypeError: 'module' object is not callable

It has similar error with Python 3.4.1.


Why does pprint not work?


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


Re: Why does not pprint work?

2014-07-22 Thread fl
On Tuesday, July 22, 2014 5:51:07 PM UTC-4, emile wrote:
> On 07/22/2014 02:42 PM, fl wrote:
> pprint is a module name -- you need to invoke the pprint function from 
> within the pprint module:
> pprint.pprint(board)

Thanks. I am curious about the two pprint. Is it the first pprint the name of 
the
module? The second pprint is the function name?

Then, how can I list all the function of pprint?

And, is there a way to list the variables I create in Python?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Question about Pass-by-object-reference?

2014-07-22 Thread fl
On Tuesday, July 22, 2014 4:46:25 PM UTC-4, emile wrote:
> On 07/22/2014 01:35 PM, Peter Pearson wrote:
> def reassign(mylist):  # no reason to shadow the list builtin
>  mylist[:] = [0,1]
> mylist = [1]
> reassign(mylist)
> mylist
> Emile

Thanks for your example. I do not find the explanation of [:] on line. Could you
explain it to me, or where can I find it on line?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Question about Pass-by-object-reference?

2014-07-22 Thread fl
On Tuesday, July 22, 2014 4:46:25 PM UTC-4, emile wrote:
> On 07/22/2014 01:35 PM, Peter Pearson wrote:
> def reassign(mylist):  # no reason to shadow the list builtin
>  mylist[:] = [0,1]
> 
> mylist = [1]
> reassign(mylist)
> mylist
> 
> Emile

I have a new question on the code. When I run it in a file on PythonWin, 
'mylist'
does not echo anything on the screen. While I enter the command line by line,
'mylist' shows the result:

>>> mylist
[0, 1]


What mechanism is involved?

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


Re: Question about Pass-by-object-reference?

2014-07-22 Thread fl
On Tuesday, July 22, 2014 4:35:33 PM UTC-4, Peter Pearson wrote:
> On Tue, 22 Jul 2014 12:34:51 -0700 (PDT), fl  wrote:
> When you say "def reassign(list)", that means "I'm defining a function
> to which the caller will pass one object, and within this function I'm
> going to refer to that object by the name 'list'."
> 
> 
> 
> Then, when you say "list=[0,1]", that means "Create the object [0,1],

The above is what rebind? see below I cite.

> and assign to it the name 'list'."  At this point, there is no longer
> any name that refers to the object that the caller passed.

Here is I find on-line about "Arguments are passed by assignment."
http://stackoverflow.com/questions/986006/python-how-do-i-pass-a-variable-by-reference

"If you pass a mutable object into a method, the method gets a reference to 
that 
same object and you can mutate it to your heart's delight, but if you rebind the
reference in the method, the outer scope will know nothing about it, and after
you're done, the outer reference will still point at the original object."

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


Re: Question about Pass-by-object-reference?

2014-07-22 Thread fl
On Tuesday, July 22, 2014 8:27:15 PM UTC-4, Terry Reedy wrote:
> When you call a function, Python binds function parameter names to 
> argument objects in the function's local namespace, the same as in name 
> assignments. Given
> def f(a, b): pass
> a call f(1, 'x') starts by executing
> a, b = 1, 'x'
> in the local namespace.  Nothing is being 'passed'.
> -- 
> Terry Jan Reedy

Thanks, but I don't understand your point yet. Could you give me another example
in which something is passed?




BTW, to a previous reply post. I have learned ':' in regular expression. But I 
am
still new to Python, I did not realize that it is the same ':' in the string
search/match.
-- 
https://mail.python.org/mailman/listinfo/python-list


Where is the function of Repr.repr1() in this example?

2014-07-23 Thread fl
Hi,
I run the example code below from website: 

https://docs.python.org/2/library/repr.html#repr.Repr.repr1

If I run these lines from an editor, it echoes:

>>> 
>>> dsfdsf # entered letters


If I only run the last line (hoping the same effect with running from the 
editor)
it simply echoes:

>>> print aRepr.repr(sys.stdin)

>>> 


I have these questions about this example code:

1. What purpose of the author wants from the example code? 
2. I do not see Repr.repr1() in the code snippet. Why did the author mention
that first?
3. Why is it different from running the last line directly in the Interactive 
Window, and within an editor file?


Thanks,



..
The use of dynamic dispatching by Repr.repr1() allows subclasses of Repr to add 
support for additional built-in object types or to modify the handling of types
already supported. This example shows how special support for file objects could
be added:

import repr as reprlib
import sys

class MyRepr(reprlib.Repr):
def repr_file(self, obj, level):
if obj.name in ['', '', '']:
return obj.name
else:
return repr(obj)

aRepr = MyRepr()
print aRepr.repr(sys.stdin)  # prints ''
-- 
https://mail.python.org/mailman/listinfo/python-list


How to install data analysis pandas toolkit?

2014-07-23 Thread fl
Hi,

I download data analysis pandas toolkit (Windows 32 version) to my PC:


pandas-0.14.0.win32-py2.7.exe


After I run it, I still cannot import the module:


>>> import pandas as pd
No module named numpy
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python27\lib\site-packages\pandas\__init__.py", line 6, in 
from . import hashtable, tslib, lib
  File "numpy.pxd", line 157, in init pandas.tslib (pandas\tslib.c:60843)
ImportError: No module named numpy
>>> 



I have check the pdf manual on installation, but do not find anything on Windows
version binary installation procedures. Could you tell me how I can get through
it?


Thanks,


http://pandas.pydata.org/pandas-docs/stable/install.html#all-platforms
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to install data analysis pandas toolkit?

2014-07-23 Thread fl
On Wednesday, July 23, 2014 8:30:00 PM UTC-4, fl wrote:

I have figured it out. It is installed under Cygwin. Although there are some 
errors in the process, it works now. Thanks,
-- 
https://mail.python.org/mailman/listinfo/python-list


What is the simplest method to get a vector result?

2014-07-24 Thread fl
Hi,
I have read a lot about Python, but it still has a problem now on a simple
exercise. For example, I want to generate a sine curve. First, I get a time 
sequence: 

index=range(100)

I import math module, try to calculate sine with

math.sin(index*math.pi/2)

but it fails.

It is possible to use a for loop, but I don't know how to save each result to an
array.

I have gone through several tutorial, but they are all about using print right
away. I want to get an array, or a series, then plot it with 

import matplotlib.pyplot as plt

I have installed plot module and it works already. I am a little hurry for an 
project interview and would like to ask here besides I continue search on 
tutorial.


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


How can I import unnecessary_math?

2014-07-24 Thread fl
Hi,
I want to write some test code. Some on-line tutorials have such codes:


from unnecessary_math import multiply

When it runs, it has errors:

>>> from unnecessary_math import multiply
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named unnecessary_math

I have not found anywhere to download it. What explanation about the module:

from unnecessary_math import multiply



Thanks,






from nose import with_setup # optional

from unnecessary_math import multiply

def setup_module(module):
print ("") # this is to get a newline after the dots
print ("setup_module before anything in this file")

def teardown_module(module):
print ("teardown_module after everything in this file")

def my_setup_function():
print ("my_setup_function")

def my_teardown_function():
print ("my_teardown_function")
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How can I import unnecessary_math?

2014-07-24 Thread fl
On Thursday, July 24, 2014 1:37:49 PM UTC-4, Chris Angelico wrote:
> On Fri, Jul 25, 2014 at 3:33 AM, fl  wrote:
> > Hi,
> > I want to write some test code. Some on-line tutorials have such codes:
> >
> >
> > from unnecessary_math import multiply
> Which tutorials? That's where you'll find the answer to your question.
> ChrisA

Thanks. The source of that snippet is from this link:

http://pythontesting.net/framework/nose/nose-introduction/


I do not find any idea on that module yet.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How can I import unnecessary_math?

2014-07-24 Thread fl
On Thursday, July 24, 2014 1:48:02 PM UTC-4, fl wrote:
> On Thursday, July 24, 2014 1:37:49 PM UTC-4, Chris Angelico wrote:
> 
> > On Fri, Jul 25, 2014 at 3:33 AM, fl  wrote:
> 
> Thanks. The source of that snippet is from this link:
> 
> 
> http://pythontesting.net/framework/nose/nose-introduction/
> 
> 
> I do not find any idea on that module yet.

It is also a question about the symbol '@' on that link.

I don't find an explanation about '@' yet. Could you tell me?

Thanks,



@with_setup(my_setup_function, my_teardown_function)
def test_numbers_3_4():
print 'test_numbers_3_4  < actual test code'
assert multiply(3,4) == 12

@with_setup(my_setup_function, my_teardown_function)
def test_strings_a_3():
print 'test_strings_a_3  < actual test code'
assert multiply('a',3) == 'aaa'
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How can I import unnecessary_math?

2014-07-24 Thread fl
On Thursday, July 24, 2014 1:58:45 PM UTC-4, Chris Angelico wrote:
> On Fri, Jul 25, 2014 at 3:54 AM, fl  wrote:
> > @with_setup(my_setup_function, my_teardown_function)
> > def test_numbers_3_4():
> > print 'test_numbers_3_4  < actual test code'
> > assert multiply(3,4) == 12
> 
> That's a function decorator. You can look them up on the web now that
> 
> you know what they're called. :)
> 
> 
> ChrisA

Thanks, I find the source of unnecessary_math at 
http://pythontesting.net/framework/doctest/doctest-introduction/
-- 
https://mail.python.org/mailman/listinfo/python-list


How to place several "import ...." lines in one .py file?

2014-07-24 Thread fl
Hi,

I have seen several kinds of module import examples, but most of the programs 
are
small and less content. They only have one or two module import.

I'll use the following modules in a small project. I would like to know whether
it is appropriate to put all of them at the file header, like this:



import pandas as pd
import numpy as np
import sci
import matplotlib.pyplot as plt
from pandas import DataFrame




Because some modules are used only at the beginning or the end, does it 
recommend
to separate to place the import lines just before the associated function lines.




import pandas as pd

.
..
...
import numpy as np

.
...
.
import sci
..
.
...
import matplotlib.pyplot as plt
from pandas import DataFrame



Or, it recommends to have separate files for each main functionality, such as
input, process and output (plot etc.)?



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


Re: What is the simplest method to get a vector result?

2014-07-24 Thread fl
On Thursday, July 24, 2014 10:25:52 AM UTC-4, Marko Rauhamaa wrote:
> #!/usr/bin/env python3
> 
> import math
> 
> for x in range(0, 361, 15):
> 
> print(int((math.sin(x / 180 * math.pi) + 1) * 30 + 0.5) * " " + "*")
> 
> 
> 
> 
> Marko

I like your method, but I get a column of '*'. Maybe you have other intentions
of your code. I am puzzled about the last part of your code and want to learn
from it ("   * " " + "*"   ").









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


How to index an array with even steps?

2014-07-25 Thread fl
Hi,

I have an array arr which is indexed from 0 to 999. I would like to construct a 
column in two steps. The first step is input from 200 data, evenly spread from 0
to 999 of the target array. Then, I want to use interpolate it from 200 to 1000
with interpolate method.

In Python, ':' is used to indicate range (while in Matlab I know it can be used
to control steps). How to index an array with 0, 5, 10, 15...995?


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


Re: How to index an array with even steps?

2014-07-25 Thread fl
On Friday, July 25, 2014 7:45:31 AM UTC-4, fl wrote:
> to 999 of the target array. Then, I want to use interpolate it from 200 to 
> 1000
> 
> with interpolate method.
> 
> In Python, ':' is used to indicate range (while in Matlab I know it can be 
> used
> to control steps). How to index an array with 0, 5, 10, 15...995?
> 
> Thanks,

Sorry, I got it.
 x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> x[1:7:2]
array([1, 3, 5])
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is the simplest method to get a vector result?

2014-07-25 Thread fl
On Thursday, July 24, 2014 9:49:14 AM UTC-4, Vlastimil Brom wrote:
> 2014-07-24 14:53 GMT+02:00 fl :
> internally):
> http://mpmath.org/
> Using the sensible defaults, the plotting of a function can be as simple as:
> 
> mpmath.plot(mpmath.sin)
> 
> As for your original question, you can use a library designed for
> working with this data:
> http://www.numpy.org/
> 
> numpy.arange(100) * numpy.pi
> 
> 
> hth,
> 
>vbr

I want to use your reply about numpy, but I find only the following works:

import numpy as numpy

Do you have other ways to import? (I find the above import a little more 
letters)

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


Re: What is the simplest method to get a vector result?

2014-07-25 Thread fl
On Friday, July 25, 2014 8:37:14 PM UTC-4, Ian wrote:
> On Fri, Jul 25, 2014 at 5:08 PM, fl  wrote:
> > Do you have other ways to import? (I find the above import a little more 
> > letters)
> 
> What's wrong with:
> 
> import numpy

I was wrong, maybe some careless key inputs. "import numpy" works.
-- 
https://mail.python.org/mailman/listinfo/python-list


  1   2   >