Re: [Tutor] Question about subprocess

2014-01-11 Thread eryksun
On Sat, Jan 11, 2014 at 12:51 AM, Steven D'Aprano  wrote:
>
>> However, when I writed it into a .py file and execute the .py file, it
>> blocked at "temp=p.readline()".
>
> Of course it does. You haven't actually called the .exe file, all you
> have done is created a Popen instance and then grabbed a reference to
> it's stdout. Then you sit and wait for stdout to contain data, which it
> never does.

Popen.__init__ calls Popen._execute_child, which on Windows is defined
to call _subprocess.CreateProcess. So the issue can't be that the OP
hasn't "called the .exe".
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question about subprocess

2014-01-11 Thread eryksun
On Sat, Jan 11, 2014 at 12:46 AM, Danny Yoo  wrote:
> There is a warning in the documentation on subprocess that might be
> relevant to your situation:
>
> Warning:
> Use communicate() rather than .stdin.write, .stdout.read or
> .stderr.read to avoid deadlocks due to any of the other OS pipe
> buffers filling up and blocking the child process.
>
> Reference: http://docs.python.org/2/library/subprocess.html
>
> It's possible that the process is deadlocking due to this situation.
> Do you run into this issue if you use communicate()?

If more than one standard file is piped (not the case for the OP),
`communicate` avoids deadlocks by using `poll` or `select` on POSIX.
On Windows, it uses the current thread to write to stdin and uses
separate threads to read from stdout and stderr.

If only one standard file is piped, then there's no deadlock. It's
just blocked while waiting for the buffer to fill. `communicate` does
nothing special in this case (at least prior to 3.3):

http://hg.python.org/cpython/file/3a1db0d2747e/Lib/subprocess.py#l767

In 3.3, the new `timeout` option for `communicate` also uses the
select/thread implementation.

stdout FILE stream buffering could be a problem if output is
intermittent and the program doesn't `fflush` the buffer. On Linux the
`stdbuf` program may be able to circumvent this. It injects code (i.e.
libstdbuf.so is added to LD_PRELOAD) that calls `setvbuf` before the
target's `main` runs. This allows you to set the stream to line
buffering mode (unless the program itself calls `setvbuf`). I don't
think a similar utility exists on Windows.

http://linux.die.net/man/1/stdbuf
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question about subprocess

2014-01-10 Thread Steven D'Aprano
On Sat, Jan 11, 2014 at 12:48:13PM +0800, daedae11 wrote:
> p = subprocess.Popen(['E:/EntTools/360EntSignHelper.exe', 
> 'E:/build/temp/RemoteAssistSetup.exe'],
>  stdout=subprocess.PIPE, shell=True).stdout
> temp = p.readline();
> print temp
> p.close()
> 
> When I run the above code in command line, it works formally.

What do you mean, "the above code"? Do you mean the *Python* code? Or do 
you mean calling the 360EntSignHelper.exe application from the command 
line? I'm going to assume you mean calling the .exe.


> However, when I writed it into a .py file and execute the .py file, it 
> blocked at "temp=p.readline()".

Of course it does. You haven't actually called the .exe file, all you 
have done is created a Popen instance and then grabbed a reference to 
it's stdout. Then you sit and wait for stdout to contain data, which it 
never does.

Instead, you can do this:

p = subprocess.Popen(['E:/EntTools/360EntSignHelper.exe', 
  'E:/build/temp/RemoteAssistSetup.exe'],
   stdout=subprocess.PIPE, shell=True)
output = p.communicate()[0]
print output


I think that should do what you expect.


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


Re: [Tutor] Question about subprocess

2014-01-10 Thread Danny Yoo
There is a warning in the documentation on subprocess that might be
relevant to your situation:

Warning:
Use communicate() rather than .stdin.write, .stdout.read or
.stderr.read to avoid deadlocks due to any of the other OS pipe
buffers filling up and blocking the child process.

Reference: http://docs.python.org/2/library/subprocess.html


It's possible that the process is deadlocking due to this situation.
Do you run into this issue if you use communicate()?



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


[Tutor] Question about subprocess

2014-01-10 Thread daedae11
p = subprocess.Popen(['E:/EntTools/360EntSignHelper.exe', 
'E:/build/temp/RemoteAssistSetup.exe'],
 stdout=subprocess.PIPE, shell=True).stdout
temp = p.readline();
print temp
p.close()

When I run the above code in command line, it works formally.

However, when I writed it into a .py file and execute the .py file, it blocked 
at "temp=p.readline()".

What's the problem?

Please help.


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


Re: [Tutor] Question about distribute in pypi

2013-12-27 Thread Oscar Benjamin
On 27 December 2013 13:53, Albert-Jan Roskam  wrote:
>  Subject: Re: [Tutor] Question about distribute in pypi
>  To: "daedae11" 
>  Cc: tutor@python.org
>  Date: Friday, December 27, 2013, 8:19 AM
>
>  On Thu, Dec 26, 2013 at 11:06 PM,
>  daedae11 
>  wrote:
>  > Are distribute 0.6.49 and distribute 0.7.3 the same
>  plugin's different
>  > version?
>
>  distribute is a fork of setuptools. The fork was merged
>  back, so for a
>  fresh installation of Python just install setuptools. The
>  0.7.3
>  package updates an existing distribute installation to the
>  latest
>  version of setuptools.
>
> ===> That's good to know. I always thought that setuptools had become sort of 
> obsolete (though still widely used).

At one point it was said to be obsolete. Over time it has become
apparent that it's really not possible at this stage to reorganise
pypi so that it is based on something radically different from
setuptools and there isn't much benefit in having a confusing array of
similar alternatives. The decision was made to focus all "official"
packaging development effort in one place: setuptools.

> So would it be fair to conclude that setuptools is now the winner of all 
> those packaging tools?
> http://stackoverflow.com/questions/6344076/differences-between-distribute-distutils-setuptools-and-distutils2

Yes.

> I checked distutils2 on pypi. Last updated March 2012 IIRC. Died during alpha 
> phase, it seems. I tried it once but experienced problems with a very basic 
> script.

Distutils2 and packaging are the same thing but one was for Python 3.x
and the other was a backport to Python 2.x. Both efforts are now
abandoned.

Likewise distribute has been merged into setuptools and abandoned.
Theoretically the most recent setuptools releases are an "upgrade"
compared with the most recent distribute releases. Development effort
for distribute is abandoned.

There are both good and bad things about setuptools but I think that
what the developers in these different efforts have now realised is
that it's just not currently possible to reorganise pypi because the
current setup couples too much unrelated functionality into the same
libraries: distutils and setuptools. Recent effort has been focussed
on providing PEPs and protocols for each part of the packaging process
so that it is possible for new packaging libraries/tools to be
interchangeable with existing ones.


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


Re: [Tutor] Question about distribute in pypi

2013-12-27 Thread Albert-Jan Roskam
 Subject: Re: [Tutor] Question about distribute in pypi
 To: "daedae11" 
 Cc: tutor@python.org
 Date: Friday, December 27, 2013, 8:19 AM
 
 On Thu, Dec 26, 2013 at 11:06 PM,
 daedae11 
 wrote:
 > Are distribute 0.6.49 and distribute 0.7.3 the same
 plugin's different
 > version?
 
 distribute is a fork of setuptools. The fork was merged
 back, so for a
 fresh installation of Python just install setuptools. The
 0.7.3
 package updates an existing distribute installation to the
 latest
 version of setuptools.
 
===> That's good to know. I always thought that setuptools had become sort of 
obsolete (though still widely used). So would it be fair to conclude that 
setuptools is now the winner of all those packaging tools?
http://stackoverflow.com/questions/6344076/differences-between-distribute-distutils-setuptools-and-distutils2

I checked distutils2 on pypi. Last updated March 2012 IIRC. Died during alpha 
phase, it seems. I tried it once but experienced problems with a very basic 
script.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question about distribute in pypi

2013-12-26 Thread eryksun
On Thu, Dec 26, 2013 at 11:06 PM, daedae11  wrote:
> Are distribute 0.6.49 and distribute 0.7.3 the same plugin's different
> version?

distribute is a fork of setuptools. The fork was merged back, so for a
fresh installation of Python just install setuptools. The 0.7.3
package updates an existing distribute installation to the latest
version of setuptools.

http://pythonhosted.org/setuptools/merge-faq.html#use-distribute-0-7

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


Re: [Tutor] Question about distribute in pypi

2013-12-26 Thread Danny Yoo
Hi Daedae,

I am not sure.

Do you have URLs to them from the Python Package index?  (PyPi)?

https://pypi.python.org/pypi

I see distribute 0.7.3 here:

https://pypi.python.org/pypi/distribute/0.7.3

and when I look at all versions of the software, it does appear that
0.6.49 was the previous version of the same library:

https://pypi.python.org/pypi/distribute


The package owners listed in the documentation appear to be the same
as well. So more likely than not, the answer to your question should
be "yes".  :P
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Question about distribute in pypi

2013-12-26 Thread daedae11
Hi,
Are distribute 0.6.49 and distribute 0.7.3 the same plugin's different version?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question about conditions and empty values

2013-10-28 Thread Alan Gauld

On 28/10/13 15:59, Shelby Martin wrote:

I use the Python GUI called IDLE. As far as I can tell, it doesn't show
me any error messages,


How are you running the program in IDLE?
When I type the code into a new edit window, save it and run it from 
within IDLE the error trace appears in the Python Shell window of IDLE.


Are you not seeing that?


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

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


Re: [Tutor] Question about conditions and empty values

2013-10-28 Thread Shelby Martin
I use the Python GUI called IDLE. As far as I can tell, it doesn't show me
any error messages, but when the program shuts down suddenly due to a
coding error, some sort of text pops up very briefly on the screen before
it shuts down. Sorry, I'm a complete newbie to Python :) And thanks for
your help.


On Sat, Oct 26, 2013 at 4:45 PM, Alan Gauld wrote:

> On 26/10/13 20:13, Shelby Martin wrote:
>
>  My question is this - the author of this exercise states the condition
>> is False if either zero or "empty" is the value. I'm assuming he means
>> that empty is just pressing Enter without entering a number?
>>
>
> Normally that would be correct but...
>
>
>
>> money = int(input("How many dollars do you slip the Maitre D'?"))
>>
>
> Here we try to convert the string to an int. and int() fails
> when given an empty string so your program never reaches the
> if test.
>
> Which begs the question: GHOw are you running your programs?
> If you used a console or an IDE it should have shown you the error message
> which would have explained what and where things went wrong.
>
> You would need to either use a try/except clause around the conversion or
> check for an empty string before converting. try/except is the preferred
> route but you may not have covered that yet.
>
>
>  if money:
>>  print("Ah, I am reminded of a table. Right this way.")
>> else:
>>  print("Please, sit. It may be a while.")
>>
>
> If you did get the error message then please, in future, include
> any such in their entirety in posts because they greatly simplify
> diagnosing more complex issues.
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.flickr.com/photos/**alangauldphotos
>
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/**mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question about conditions and empty values

2013-10-26 Thread Alan Gauld

On 26/10/13 20:13, Shelby Martin wrote:


My question is this - the author of this exercise states the condition
is False if either zero or "empty" is the value. I'm assuming he means
that empty is just pressing Enter without entering a number?


Normally that would be correct but...



money = int(input("How many dollars do you slip the Maitre D'?"))


Here we try to convert the string to an int. and int() fails
when given an empty string so your program never reaches the
if test.

Which begs the question: GHOw are you running your programs?
If you used a console or an IDE it should have shown you the error 
message which would have explained what and where things went wrong.


You would need to either use a try/except clause around the conversion 
or check for an empty string before converting. try/except is the 
preferred route but you may not have covered that yet.



if money:
 print("Ah, I am reminded of a table. Right this way.")
else:
 print("Please, sit. It may be a while.")


If you did get the error message then please, in future, include
any such in their entirety in posts because they greatly simplify 
diagnosing more complex issues.


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

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


[Tutor] Question about conditions and empty values

2013-10-26 Thread Shelby Martin
For the program below, if I enter "0" at the prompt, it provides the reply
"Please, sit. It may be a while". However, if I just press the Enter key,
it shuts the program down without a reply from the Maitre D'.

My question is this - the author of this exercise states the condition is
False if either zero or "empty" is the value. I'm assuming he means that
empty is just pressing Enter without entering a number?

He talks about testing for empty values, but I'm not seeing that entering
an empty value here yields the response he is talking about. Unless I'm
mistaken about something. Thanks in advance for your assistance!

#Maitre D'
#Demonstrates treating a value as a condition

print("Welcome to the Chateau D' Food")
print("It seems we are quite full this evening.\n")

money = int(input("How many dollars do you slip the Maitre D'?"))

if money:
print("Ah, I am reminded of a table. Right this way.")
else:
print("Please, sit. It may be a while.")

input("\n\nPress the enter key to exit.")
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question about Functions

2013-09-10 Thread Steven D'Aprano
On Tue, Sep 10, 2013 at 01:49:11PM -0400, novo shot wrote:

> When I declare a variable to be equal as the fucntion
> (result=theFunction("this either")) is Python also executing the
> function?

No, you have misunderstood. Equals in programming languages is not the 
same as equals in mathematics. Some languages, like Pascal, use := 
instead of = in order to avoid that misunderstanding.

In mathematics, "y = 3*x - 1" declares that y is equal to the equation 
on the right, no matter what value x happens to have.

But in programming, instead it *evaluates* the equation on the right, 
using the current value of x, and *assigns* the result to y.

So in your example above, result=theFunction("this either"), Python 
evaluates the function call theFunction("this either"), collects 
whatever result is returned (but not what is printed!), and assigns that 
to the variable "result".

Since theFunction prints some things, they will be printed but not 
assigned to anything. Only whatever is returned, using the "return" 
statement, will be assigned to variable "result".

[...]
> Can you help me understand? I can't move forward until I understand
> how Python solves this code.

It might help you to start with a simpler example:

def print_test():
print "Hello World!"  # use print("...") in Python 3


This function takes no arguments, and always prints the same thing. It 
returns nothing. (To be precise, it returns the special object None, but 
don't worry about that.)

py> print_test()  # Round brackets calls the function
Hello World!
py> result = print_test()
Hello World!
py> result
py> 


So this demonstrates that printing values just prints them. You cannot 
access the printed result programatically. It just gets printed to the 
screen and that's it.


def return_test():
return "And now for something completely different!"


This function uses return instead of print. Here it is in use:

py> return_test()
'And now for something completely different!'
py> result = return_test()
py> result
'And now for something completely different!'
py> result.upper()
'AND NOW FOR SOMETHING COMPLETELY DIFFERENT!'


So as you can see, using return is *much* more flexible. You can capture 
the result of the function, hold of printing it until you want, or 
process it further, pass it on to other functions, or so forth.


Finally, let's combine the two:


def test_both():
print "This is immediately printed."
return "And this is returned."



By now you hopefully should be able to predict what calling this 
function will do, but just in case you can't:


py> result = test_both()
This is immediately printed.
py> result
'And this is returned.'
py> result.upper()
'AND THIS IS RETURNED.'



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


Re: [Tutor] Question about Functions

2013-09-10 Thread Dino Bektešević
> Date: Tue, 10 Sep 2013 13:34:50 -0400
> From: novo shot 
> To: tutor@python.org
> Subject: [Tutor] Question about Functions
> Message-ID:
> 
> Content-Type: text/plain; charset="iso-8859-1"
>
> Dear tutors:
>
> The following is an example I found in the Raspberry Pi for Dummies book:
>
> #function test
>
> def theFunction(message):
> print "I don't get ", message
> return "ARRRGH!"
>
> theFunction("this")
>
> result=theFunction("this either")
> print "reply is: ", result
>
> -
> The result of this code looks like this:
>
> I don't get  this
> I don't get  this either
> reply is:  ARRRGH!
>
> --
> Here's what I don't understand:
>
> When I declare a variable to be equal as the fucntion
> (result=theFunction("this either")) is Python also executing the function?
>
> The way I see it, I only called for the function once before printing
> ARRRGH!! Then after that I declared a variable and then I print.
>
> This is how I expected the result to look like:
>
> I don't get this
> reply is: I don't get this either
> ARRRGH!
>
> -
>
> Can you help me understand? I can't move forward until I understand how
> Python solves this code.
>
> Thanks in advance

Function in Python work very much the same way like they do in most
programming languages. When working with them you can't really "feel"
the difference.
There is a big difference, however, "underneath" (just always keep in
mind everything in Python is an object, the book should mention that
repeatedly).
Since you didn't mention I have to assume you didn't do any
programming before python.

In the case of big C's (C, C++, C#) I was always thought that I should
look at a function as a variable. In particular the exact same
variable you return.
I.e. if I have a function:
  >>> def add1(int_number):
  return number+1
you can look at function add1 as if it's an integer because it returns
an integer.
The same applies to your example, which you can see if you do some
introspection:
  >>> type(result)
  
So you see your result is nothing more then a string! Basically
whatever you return in your function will be assigned to the variable
you return it to. Because you return "AARGH" in your function and
assign the return value to result:
 >>> result=theFunction("thisEither")
the variable result will become "AARGH". So this line basically amounts to:
 >>> result= "AARGH"

This is a special case because this function always returns the same
thing. That's not usually the case with functions.
I.e. let's return to my add1 function. Output (that part behind the
return statement) of add1 function will change depending on the input
number:
  >>> add1(3)
  4
  >>> added = add1(5)
  >>> print added
  6
What you can also see from the above example is that when I explicitly
assigned a variable to a function [added = add1(5)] the result of the
function did not print out, but the function must have executed
because variable added has a value of '6'.
So function executes every time you call on it, but prints out value
of "return" only when you don't specify a "container" that will hold
it's output.

I'm pretty sure you're confused here because you have a print
statement in your function. Print statement calls on your standard
output that works "over" anything and pretty much "whenever", it's
kind of special that way. If I changed my example function add1 to:
  >>> def add1(int_number):
  print "Working, hold your horses"
  return number+1
then my output from before would be:
  >>> add1(3)
  Working, hold your horses
  4
  >>> added = add1(5)
 Working, hold your horses
  >>> print added
  6
This is the main difference between return and print, think of return
like it defaults to print if there is no value to which it can assign
what it returned. That is also why you always see line "I don't get
(this/this either)" printed every time you call on your function.
  >>> theFunction("this")
  I don't get this
  ARRGHHH
  >>> result=theFunction("this either")
  I don't get this either
  >>> print "reply is: ", result
  reply is AARGGG
I think it should be pre

Re: [Tutor] Question about Functions

2013-09-10 Thread Alan Gauld

On 10/09/13 18:49, novo shot wrote:

Dear tutors:

The following is an example I found in the Raspberry Pi for Dummies book:

#function test

def theFunction(message):
 print "I don't get ", message
 return "ARRRGH!"


All the code above does is define the function and assign it the name 
theFunction (which is a terrible name but we'll ignore that for now!)

It does not execute the function.


theFunction("this")


Any time the function name is followed by parentheses (but not
preceded by def) the function gets executed. So this calls the
function passing in the argument 'this' which results in the
string "I don't get this" being printed. The value 'AARGH!'
is returned but not stored anywhere so is lost.


result=theFunction("this either")


This time the function is executed with the argument 'this either' 
passed in and the string "I don't get this either" is printed. Again the 
value 'AARGH!' is returned but this time it is assigned to the variable 
result.



print "reply is: ", result


This prints the string "reply is:  AARGH!"


The result of this code looks like this:

I don't get  this
I don't get  this either
reply is:  ARRRGH!


Which is what I described above.


When I declare a variable to be equal as the fucntion
(result=theFunction("this either")) is Python also executing the
function?


Yes, every time the function name is followed by parentheses
it gets executed (and the return value assigned to any variable
ready to receive it).


The way I see it, I only called for the function once before printing
ARRRGH!! Then after that I declared a variable and then I print.


Wrong. You defined the function once. You called it twice.
Then you printed the return value of the second invocation.


This is how I expected the result to look like:

I don't get this
reply is: I don't get this either
ARRRGH!


The 'I don't get...' line is printed inside the function.
The program outside the function knows nothing about that.
It has no way to access that string. That separation of
what's inside the function from the code outside is a
very important feature of programming and is known as
abstraction, data hiding and encapsulation. (All subtly
different variations on the same theme but very important
in programming). It is this feature that enables us to
write reusable functions that can be inserted into any
program without relying on, or breaking, the surrounding
code.

One final thing to note is that when you are at the
Python interpreter prompt the return value of a function
is always printed. But when executing a script file the
return value is not printed unless the program does it
explicitly using print.

>>> def f():
...   print 'this is always printed'
...   return "this isn't"
...
>>> f()
this is always printed
"this isn't"

Now if you put the definition of f() in a file called
test.py like this:


def f():
   print 'this is always printed'
   return "this isn't"

f()
##

and run it, you will only see the first line printed.
The return value has been lost because it was never
explicitly printed out. This difference in behaviour
between the  prompt and executing a script often
confuses beginners but is a useful feature when
testing/experimenting at the >>> prompt. You just
need to remember that it will not always give
identical behaviour to a script.

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

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


Re: [Tutor] Question about Functions

2013-09-10 Thread Prasad, Ramit
novo shot wrote:
> Dear tutors:
> 
> The following is an example I found in the Raspberry Pi for Dummies book:
> 
> #function test
> 
> def theFunction(message):
> print "I don't get ", message
> return "ARRRGH!"
> 
> theFunction("this")
> 
> result=theFunction("this either")
> print "reply is: ", result
> 
> -
> The result of this code looks like this:
> 
> I don't get  this
> I don't get  this either
> reply is:  ARRRGH!
> 
> --
> Here's what I don't understand:
> 
> When I declare a variable to be equal as the fucntion
> (result=theFunction("this either")) is Python also executing the
> function?

Yes, when you do function() it calls the function.
In this case it is calling theFunction with the
string arguments 'this' and 'this either', respectively.

> The way I see it, I only called for the function once before printing
> ARRRGH!! Then after that I declared a variable and then I print.
> 
> This is how I expected the result to look like:
> 
> I don't get this
> reply is: I don't get this either
> ARRRGH!


You do not get this output because you do not return the 
string with the `message`, you print it immediately and 
return "ARRRGH!". "ARRRGH!" then gets bound to the name 
`result` which you then print.

If you want the result you specify you should return 

"reply is: " + result # where result must be a string

Not sure how to expect to get "ARRRGH!" unless you return that 
too. You can return multiple objects but you typically need to 
attach it to an object. Lists and tuples are frequently used to 
return multiple objects. Some examples are below.

# tuple
return a,b,c
# list (in-line)
return [ a, b, c]
# list (created and all objects added earlier)
list_object = []
for x in xrange(4):
list_object.append( x ) #just an example
return list_object

# as attribute (use when you need to pass state / data handling)
obj = Class()
obj.attribute = [a,b,c]
return obj


> 
> -
> 
> Can you help me understand? I can't move forward until I understand
> how Python solves this code.

I recommend going through some beginner Python tutorials first
to get a grasp of how Python works before you start on a book
for Raspberry Pi.

> 
> Thanks in advance
> Optional


~Ramit



This email is confidential and subject to important disclaimers and conditions 
including on offers for the purchase or sale of securities, accuracy and 
completeness of information, viruses, confidentiality, legal privilege, and 
legal entity disclaimers, available at 
http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question about Functions

2013-09-10 Thread Chris Down
On 2013-09-10 13:34, novo shot wrote:
> When I declare a variable to be equal as the fucntion
> (result=theFunction("this either")) is Python also executing the function?

You're not declaring it as equal, that would be `==' (or `is' for identity).
`=' assigns, it doesn't check for equality.

> The way I see it, I only called for the function once before printing
> ARRRGH!! Then after that I declared a variable and then I print.
>
> This is how I expected the result to look like:
>
> I don't get this
> reply is: I don't get this either
> ARRRGH!

Why do you expect "reply is" to happen on the second line? It clearly only
happens when printing the returned value, not when printing from inside the
function itself:

> def theFunction(message):
> print "I don't get ", message
> return "ARRRGH!"
>
> theFunction("this")
>
> result=theFunction("this either")
> print "reply is: ", result

The extra spaces are because "," implies one. If you don't want a double space
before the message, remove the trailing space in the string.


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


[Tutor] Question about Functions

2013-09-10 Thread novo shot
Dear tutors:

The following is an example I found in the Raspberry Pi for Dummies book:

#function test

def theFunction(message):
print "I don't get ", message
return "ARRRGH!"

theFunction("this")

result=theFunction("this either")
print "reply is: ", result

-
The result of this code looks like this:

I don't get  this
I don't get  this either
reply is:  ARRRGH!

--
Here's what I don't understand:

When I declare a variable to be equal as the fucntion
(result=theFunction("this either")) is Python also executing the
function?

The way I see it, I only called for the function once before printing
ARRRGH!! Then after that I declared a variable and then I print.

This is how I expected the result to look like:

I don't get this
reply is: I don't get this either
ARRRGH!

-

Can you help me understand? I can't move forward until I understand
how Python solves this code.

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


Re: [Tutor] Question about Functions

2013-09-10 Thread Joel Goldstick
On Tue, Sep 10, 2013 at 1:49 PM, novo shot  wrote:

> Dear tutors:
>
> The following is an example I found in the Raspberry Pi for Dummies book:
>
> #function test
>
> def theFunction(message):
> print "I don't get ", message
> return "ARRRGH!"
>
> theFunction("this")
>

the above line invokes theFunction, and prints "I don't get this".  It
returns "ARRRGH" but you con't assign that to a name, so it is lost.

>
> result=theFunction("this either")
>

Now you call theFunction again and it prints "I don't get this either".
You save the ARRRGH bit in result

> print "reply is: ", result
>

You print the value of result with is ARRRGH

>
> -
> The result of this code looks like this:
>
> I don't get  this
> I don't get  this either
> reply is:  ARRRGH!
>
> --
> Here's what I don't understand:
>
> When I declare a variable to be equal as the fucntion
> (result=theFunction("this either")) is Python also executing the
> function?
>

Yes it is

>
> The way I see it, I only called for the function once before printing
> ARRRGH!! Then after that I declared a variable and then I print.
>
> You see it wrong.  Each time you have theFunction(...) in your code that
function is run

> This is how I expected the result to look like:
>
> I don't get this
> reply is: I don't get this either
> ARRRGH!
>
> -
>
> Can you help me understand? I can't move forward until I understand
> how Python solves this code.
>
> Thanks in advance
> Optional
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



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


[Tutor] Question about Functions

2013-09-10 Thread novo shot
Dear tutors:

The following is an example I found in the Raspberry Pi for Dummies book:

#function test

def theFunction(message):
print "I don't get ", message
return "ARRRGH!"

theFunction("this")

result=theFunction("this either")
print "reply is: ", result

-
The result of this code looks like this:

I don't get  this
I don't get  this either
reply is:  ARRRGH!

--
Here's what I don't understand:

When I declare a variable to be equal as the fucntion
(result=theFunction("this either")) is Python also executing the function?

The way I see it, I only called for the function once before printing
ARRRGH!! Then after that I declared a variable and then I print.

This is how I expected the result to look like:

I don't get this
reply is: I don't get this either
ARRRGH!

-

Can you help me understand? I can't move forward until I understand how
Python solves this code.

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


Re: [Tutor] Question in regards to loops and matplotlib

2013-08-08 Thread Zachary Rizer
This looks quite clean! Since posting this question I have cleaned up this
script by using multiple functions, but it still isn't this clean! My data
is a normal CSV table with column headers. It isn't in a dictionary format
like your sample data here. I'm sure I could switch it to that format
though. I'll post a sample of my data, first 10 rows with column headers
here, and my current rendition of the code. Also, not to familiar with the
lambda function you did here. Little bit confused on how you split the
groups up. Anyway, new version of code and sample data:

I attached the ten row sample because it has 60 columns of info on each row
and would look huge pasted.

"""
Zach Rizer
UVJ plot of n>2 pop compare qui and sf disk and bulge pop
data = n>2_qui_flag.csv
"""

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patch
from matplotlib.path import Path

z1 = (0.6, 0.9, 0.59, 0.81, 2, "0.6= z_range[0]  and row['pz_z'] < z_range[1]:
z_data.append(row)
z_data = np.array(z_data)
return z_data

def quiescence(table,z_range):
"""
takes given csv table and specific redshfit range and spits out
a two-tuple where first index of the tuple is the quiescent pop
and the second index is the star forming pop
"""
qui_data = []
sf_data = []
for row in table:
if row['rf_UminV'] > 1.3 and row['rf_VminJ'] < 1.6 and
row['rf_UminV'] > 0.88*(row['rf_VminJ'])+z_range[2]:
qui_data.append(row)
else:
sf_data.append(row)
qui_data = np.array(qui_data)
sf_data = np.array(sf_data)
return qui_data, sf_data

def disk_vs_bulge(table):
"""
turns given csv table into a two-tuple array where the first
index is the disk-dom pop and the second index is the bulge-dom
pop: these cuts are determined by visclass data
"""
disk_data = []
bulge_data = []
for row in table:
if row['vc_Dv'] > 0.65 and row['vc_DSw'] > 0.65:
disk_data.append(row)
elif row['vc_Dv'] < 0.35 and row['vc_DSw'] > 0.65:
bulge_data.append(row)
disk_data = np.array(disk_data)
bulge_data = np.array(bulge_data)
return disk_data, bulge_data

def make_mass_cuts(table):
"""
make mass cuts using logMass row and creates four-tuple
each index is divided into its own dual tuple, x and y UVJ colors
array returned = [(m1_x, m1_y), (m2_x, m2_y), (m3_x, m3_y), (m4_x,
m4_y)]
"""
m1_x = []
m1_y = []
m2_x = []
m2_y = []
m3_x = []
m3_y = []
m4_x = []
m4_y = []
for row in table:
if row['ms_lmass'] >= 9.7 and row['ms_lmass'] < 10:
m1_x.append(row['rf_VminJ'])
m1_y.append(row['rf_UminV'])
elif row['ms_lmass'] >= 10 and row['ms_lmass'] < 10.5:
m2_x.append(row['rf_VminJ'])
m2_y.append(row['rf_UminV'])
elif row['ms_lmass'] >= 10.5 and row['ms_lmass'] < 10.8:
m3_x.append(row['rf_VminJ'])
m3_y.append(row['rf_UminV'])
elif row['ms_lmass'] >= 10.8:
m4_x.append(row['rf_VminJ'])
m4_y.append(row['rf_UminV'])
return [(m1_x, m1_y), (m2_x, m2_y), (m3_x, m3_y), (m4_x, m4_y)]

def plots(m_q_disk, m_q_bulge, m_sf_disk, m_sf_bulge):
"""
plot the first column as x, and second column as y
takes all four mass arrays and plots all 16 subplots
returns a 3-tuple of plot of qui_bulge, sf_bulge, sf_disk for legend
"""
plt.plot(m_q_disk[3][0], m_q_disk[3][1], 'wo', ms=12)
qui_bulge_label, = plt.plot(m_q_bulge[3][0], m_q_bulge[3][1], 'ro',
ms=12)
plt.plot(m_q_disk[2][0], m_q_disk[2][1], 'wo', ms=9)
plt.plot(m_q_bulge[2][0], m_q_bulge[2][1], 'ro', ms=9)
plt.plot(m_q_disk[1][0], m_q_disk[1][1], 'wo', ms=6)
plt.plot(m_q_bulge[1][0], m_q_bulge[1][1], 'ro', ms=6)
plt.plot(m_q_disk[0][0], m_q_disk[0][1], 'wo', ms=3)
plt.plot(m_q_bulge[0][0], m_q_bulge[0][1], 'ro', ms=3)

sf_disk_label, = plt.plot(m_sf_disk[3][0], m_sf_disk[3][1], 'wo', ms=12)
sf_bulge_label, = plt.plot(m_sf_bulge[3][0], m_sf_bulge[3][1], 'bo',
ms=12)
plt.plot(m_sf_disk[2][0], m_sf_disk[2][1], 'wo', ms=9)
plt.plot(m_sf_bulge[2][0], m_sf_bulge[2][1], 'bo', ms=9)
plt.plot(m_sf_disk[1][0], m_sf_disk[1][1], 'wo', ms=6)
plt.plot(m_sf_bulge[1][0], m_sf_bulge[1][1], 'bo', ms=6)
plt.plot(m_sf_disk[0][0], m_sf_disk[0][1], 'wo', ms=3)
plt.plot(m_sf_bulge[0][0], m_sf_bulge[0][1], 'bo', ms=3)

return qui_bulge_label, sf_bulge_label, sf_disk_label

def make_hash_region(z_range):
"""make quiescent region"""
verts = [(-1.,1.3),
 (z_range[3],1.3),
 (1.6,z_range[4]),
 (1.6,2.5),
 (-1.,2.5),
 (-1.,1.3)]
codes = [Path.MOVETO,
 Path.LINETO,
 Path.LINETO,
 Path.LINETO,
 Path.LINETO,
 Path.CLOSEPOLY]
return Path(verts,codes)

def titles_labels(labels, z_range):
"""

[Tutor] Question in regards to loops and matplotlib

2013-08-07 Thread Zachary Rizer
So I just started coding, and I'm so glad I chose Python to start me off! I
really enjoy the clean layout, easy syntax, and power of the language. I'm
doing astronomy research and I just started teaching myself matplotlib
along with my general python work. I feel like I'm catching on quick, but I
also feel that this particular plot script is a little rough. The plot
looks correct, but the code seems really long for what I'm trying to do. So
any tricks to make this more efficient would be greatly appreciated!

A little bit about what's going on before I post the script. I'm using
np.genfromtext to upload a CSV file of a bunch of astronomy data. I need to
break this data down into multiple subsets. 4 mass separated subsets
(row['logM']) and each of those is divided into bulge and disk dominated.
And for each of those I need to separate quiescent and star forming. So I
have a total of 8 star forming subsets and 8 quiescent subsets. And all
sixteen different styles of object need a distinct marker on the plot. I
hope that with the comments you can see where I divided those up in the
code. I did it all with a ton of for loops and if statements filling in a
bunch of empty arrays. Hopefully this is enough info to make sense of what
I'm going for. My main question is can I shorten this code, especially the
for loops, to make it more efficient and clean? Here is the script:


# -*- coding: utf-8 -*-
#- Zach Rizer
#- UVJ plot
#- data = n>2_qui_flag.csv

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patch
from matplotlib.path import Path

fig = plt.figure('UVJ')
ax = fig.add_subplot(111) #subplot for shaded region

##
# - Data uploaded from preliminary TopCat CSV Files
data =
np.genfromtxt('/Users/ProtonLenny/Documents/Research/Catalog_Data/Catalog_3/n>2_qui_flag.csv',\
dtype=None,names=True,delimiter =",")

# - Define Quiesent Subset
qui_m1d_xval = []
qui_m1d_yval = []
qui_m2d_xval = []
qui_m2d_yval = []
qui_m3d_xval = []
qui_m3d_yval = []
qui_m4d_xval = []
qui_m4d_yval = []
qui_m1b_xval = []
qui_m1b_yval = []
qui_m2b_xval = []
qui_m2b_yval = []
qui_m3b_xval = []
qui_m3b_yval = []
qui_m4b_xval = []
qui_m4b_yval = []
for row in data:
if row['Dv'] > 0.65 and row['DSw'] > 0.65:
 * # filling disk-dom arrays*
if row['UminV'] > 1.3 and row['VminJ'] < 1.6 and row['UminV'] >
0.88*(row['VminJ']+0.59):#quiescent criteria at particular z
if row['Z'] >= 0.6 and row['Z'] < 0.9:#redshift bin criteria
if row['logM'] >= 9.7 and row['logM'] < 10:#mass subsets
for shape in plots
qui_m1d_xval.append(row['VminJ'])
  * # (x) fill the empty list with the data from the appropriate column.*
qui_m1d_yval.append(row['UminV'])
elif row['logM'] >= 10 and row['logM'] < 10.5:
qui_m2d_xval.append(row['VminJ'])
qui_m2d_yval.append(row['UminV'])
elif row['logM'] >= 10.5 and row['logM'] < 10.8:
qui_m3d_xval.append(row['VminJ'])
qui_m3d_yval.append(row['UminV'])
elif row['logM'] >= 10.8:
qui_m4d_xval.append(row['VminJ'])
qui_m4d_yval.append(row['UminV'])
if row['Dv'] < 0.35 and row['DSw'] > 0.65:
   *  # filling bulge-dom arrays*
if row['UminV'] > 1.3 and row['VminJ'] < 1.6 and row['UminV'] >
0.88*(row['VminJ']+0.59):#quiescent criteria at particular z
if row['Z'] >= 0.6 and row['Z'] < 0.9:#redshift bin criteria
if row['logM'] >= 9.7 and row['logM'] < 10:#mass subsets
for shape in plots
qui_m1b_xval.append(row['VminJ'])
qui_m1b_yval.append(row['UminV'])
elif row['logM'] >= 10 and row['logM'] < 10.5:
qui_m2b_xval.append(row['VminJ'])
qui_m2b_yval.append(row['UminV'])
elif row['logM'] >= 10.5 and row['logM'] < 10.8:
qui_m3b_xval.append(row['VminJ'])
qui_m3b_yval.append(row['UminV'])
elif row['logM'] >= 10.8:
qui_m4b_xval.append(row['VminJ'])
qui_m4b_yval.append(row['UminV'])

# - Define Star-Forming Subset
sf_m1d_xval = []
sf_m1d_yval = []
sf_m2d_xval = []
sf_m2d_yval = []
sf_m3d_xval = []
sf_m3d_yval = []
sf_m4d_xval = []
sf_m4d_yval = []
sf_m1b_xval = []
sf_m1b_yval = []
sf_m2b_xval = []
sf_m2b_yval = []
sf_m3b_xval = []
sf_m3b_yval = []
sf_m4b_xval = []
sf_m4b_yval = []
for row in data:
if row['Dv'] > 0.65 and row['DSw'] > 0.65:
# filling disk-dom arrays
if row['UminV'] < 1.3 or row['VminJ'] > 1.6 or row['UminV'] <
0.88*(row['VminJ']+0.59):#star forming creteria at particular z
if row['Z'] >= 0.6 and row['Z'] < 0.9:#reshift bin criteria
if row['logM'] >= 9.7 an

Re: [Tutor] Question

2013-08-07 Thread zubair alam
what exactly you want to do by

[1,2,3] = "Anything"


the above code is called unpacking of sequence, so there must be some
variable on left side of assignment operator.
but you have list of integers, why?


On Tue, Jul 23, 2013 at 11:15 PM, Don Jennings  wrote:

>
> On Jul 21, 2013, at 10:26 PM, Amandeep Behl wrote:
>
> >
> >
> > def Move(label):
> >   label = "Anything"
> >
> > a_list = [1,2,3]
> > Move(a_list)
> >
> > I don't see any error when executing above but  when i manually assign
> [1,2,3] = "Anything" i get error
> >  Why?
>
> Repeat after me:  label is a name, label is a name, label is a name ;>)
>
> So, you misunderstand what is happening in your code. Your function
> accepts the argument named "label", but you do nothing with the object (a
> list of numbers in this case). Instead, you use the same name and assign it
> to the string object "Anything".
>
> Assignment works by assigning a name (on the left side of the operator),
> to an object on the right side.
>
> Take care,
> Don
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Question

2013-07-23 Thread Amandeep Behl
def Move(label):
  label = "Anything"

a_list = [1,2,3]
Move(a_list)

I don't see any error when executing above but  when i manually assign
[1,2,3] = "Anything" i get error
 Why?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question about python for web

2013-06-26 Thread Seshadri Raja
Dear Dat,

Sorry for the late reply.

The path of the python should be #!/usr/bin/python (or) #!/usr/bin/env
python. Forward Slash(/) is missing in your CGI script.

​Enable the ExecCGI for your DocumentRoot

Ref:
http://httpd.apache.org/docs/current/howto/cgi.html​

​

Options +ExecCGI

​

Kindly try and let us know the details.

Kind Regards
:: S. Seshadri Raja ::




On Sun, Jun 23, 2013 at 6:12 PM, Dat Huynh  wrote:

> Dear all,
>
> I have a very simple question about running a simple web application with
> apache on MacOS.
>
> Step 1: Copy the file mod_wsgi.so from the link
>
> http://code.google.com/p/modwsgi/downloads/detail?name=mod_wsgi-macosx106-ap22py26-3.3.so
> into the folder "/usr/libexec/apache2"
>
>
> Step 2: Add the following line:
>
>   LoadModule wsgi_module libexec/apache2/mod_wsgi.so
> into the file "/etc/apache2/httpd.conf"
>
>
> Step 3: Edit a file "test.py" as below and copy the file to the folder
> "/Library/WebServer/Documents".
>
> #!usr/bin/python
> print "Content-type: text/html"
> print
> print ""
> print ""
> print ""
> print "Test Page"
> print ""
>
> When I type the following url "http://localhost/test.py"; on my browser, I
> see exactly the content of the file, NOT the text "Test Page" only.
>
> I think I miss something in the procedure.
> What should I do to make my browser process the received HTML data?
>
> Thank you very much.
>
> Sincerely,
> Dat.
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Question about python for web

2013-06-23 Thread Dat Huynh
Dear all,

I have a very simple question about running a simple web application with
apache on MacOS.

Step 1: Copy the file mod_wsgi.so from the link
http://code.google.com/p/modwsgi/downloads/detail?name=mod_wsgi-macosx106-ap22py26-3.3.so
into the folder "/usr/libexec/apache2"


Step 2: Add the following line:

  LoadModule wsgi_module libexec/apache2/mod_wsgi.so
into the file "/etc/apache2/httpd.conf"


Step 3: Edit a file "test.py" as below and copy the file to the folder
"/Library/WebServer/Documents".

#!usr/bin/python
print "Content-type: text/html"
print
print ""
print ""
print ""
print "Test Page"
print ""

When I type the following url "http://localhost/test.py"; on my browser, I
see exactly the content of the file, NOT the text "Test Page" only.

I think I miss something in the procedure.
What should I do to make my browser process the received HTML data?

Thank you very much.

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


[Tutor] Question regarding the 'chr' function

2013-06-09 Thread Colin Clayton
Hi everyone, I am fairly new to the Python language and have come from a
background of Google's App Inventor Block Language. I'm having trouble
understanding what the 'chr' function does? I have yet to find a tutorial
or information online relating to the 'chr' function  that really clicks
with me. If I want to make an AsciiChart function that returns a string
that is an AsciiChart using the 'chr' function how would I do this? I don't
expect or need code as an answer, I'm really just looking for an
explanation of the possible logic.
Please let me know if you have any ideas.
Thanks!

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


Re: [Tutor] question already discussed with oscar benjamin

2013-05-16 Thread Oscar Benjamin
On 7 May 2013 21:10, Linsey Raaijmakers  wrote:
> Hi,
>
> Im trying to work with the help Oscar provided me, but I still get stuck :(

For the benefit of everyone else here, this is referring to a question
that was asked on python-list. The discussion there went off-list and
I recommended that it take place on-list but on this list instead of
python-list.

> So what I'm trying to do now is write the program with the following input
> and output:

The input/output specification below was my own suggestion of a
subproblem to solve. The idea is that actions with integer identifiers
have integer start/apex/end times and the program should read a file
containing those and identify when actions are occurring
simultaneously. The events in the file appear in order of start time.

> Input:
> action,start,apex,stop
> 3, 12, 13, 15
> 4, 15, 15, 15
> 3, 20, 21, 25
> 5, 21, 23, 30
> ...
>
> And when you run your program it prints out:
> actions, start, stop
> [3], 12, 13
> [], 14,15
> [4], 15, 15
> [], 16, 19
> [3], 20, 21
> [3, 5], 21, 21
> [5], 22, 23
> ...
>
> I don't want to use the stop. Only the start till apex is important.
>
> This is the code I have now:

Not it's not. This code doesn't work. Can you post a complete program
that actually runs rather than just a segment of it? See here:
http://sscce.org/

>
> now = onset_list[0]
> end = apex_list[0]
> active = action_list[0]
>
> for i in range(1,len(onset_list)):
>   next_start = onset_list[i]
>   next_end = apex_list[i]
>   next_active = action_list[i]
>   prev_end = apex_list[i-1]
>
>   while next_start > end:
> print active+"\t"+now+'\t'+end
> end = next_end
> now = next_start
> active = next_active
>   print active+','+next_active+'\t'+now+'\t'+next_end

This will just print each event and the following event. That is not
what you want. You need to keep a list of currently active events and
as you loop forward through the times you should remove events that
have finished and add events that have started.

> But my output will print now:
>
> 31213
> 4,4  1515
> 4 1515
> 3,3   2021
> 3,5   2025
>
> How do I fix that it doesn't print out the double ones?

The problem is not that it prints the double ones. The problem is that
it does not keep track of a list of currently active events. I'll make
the problem a bit simpler: make a program that gives the following
input/output.

Input:
action,start,apex,stop
3, 12, 13, 15
4, 15, 15, 15
3, 20, 21, 25
5, 21, 23, 30
...

And when you run your program it prints out:
actions, time
[3], 12
[3], 13
[], 14
[4], 15
[], 16
[], 17
[], 18
[], 19
[3], 20
[3, 5], 21
[5], 22
[5], 23
...

The first column in this output is the list of active events at the
times given in the second column. Your code will need to actually have
a list that it adds and removes from as events start and stop


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


[Tutor] question already discussed with oscar benjamin

2013-05-15 Thread Linsey Raaijmakers
Hi,

Im trying to work with the help Oscar provided me, but I still get stuck :(
So what I'm trying to do now is write the program with the following input
and output:

Input:
action,start,apex,stop
3, 12, 13, 15
4, 15, 15, 15
3, 20, 21, 25
5, 21, 23, 30
...

And when you run your program it prints out:
actions, start, stop
[3], 12, 13
[], 14,15
[4], 15, 15
[], 16, 19
[3], 20, 21
[3, 5], 21, 21
[5], 22, 23
...

I don't want to use the stop. Only the start till apex is important.

This is the code I have now:

now = onset_list[0]
end = apex_list[0]
active = action_list[0]

for i in range(1,len(onset_list)):
  next_start = onset_list[i]
  next_end = apex_list[i]
  next_active = action_list[i]
  prev_end = apex_list[i-1]

  while next_start > end:
print active+"\t"+now+'\t'+end
end = next_end
now = next_start
active = next_active
  print active+','+next_active+'\t'+now+'\t'+next_end

But my output will print now:

31213
4,4  1515
4 1515
3,3   2021
3,5   2025

How do I fix that it doesn't print out the double ones?
I'm sorry that I can't figure it out without your help. Im really trying..
:(
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question on regular expressions

2013-02-12 Thread Mark Lawrence

On 12/02/2013 17:43, Marcin Mleczko wrote:

Hello,

given this kind of string:

"start SomeArbitraryAmountOfText start AnotherArbitraryAmountOfText end"

a search string like: r"start.*?end" would give me the entire string
from the first "start" to "end" : "start SomeArbitraryAmountOfText start
AnotherArbitraryAmountOfText end"

but I am interested only in the second part between the 2nd "start" and
the "end": "start AnotherArbitraryAmountOfText end"

What would be best, most clever way to search for that?

Or even more general: how do I exlude always the text between the last
"start" and the "end" tag assuming the entire text contains several
"start" tags spaced by an arbitrary amount of text befor the "end" tag?

Any ideas?

Thank you in advance. ;-)

Marcin



IMHO the best way is to use the rindex method to grab what you're after. 
 I don't do clever, it makes code too difficult to maintain.  So how about.


>>> a="start SomeArbitraryAmountOfText start 
AnotherArbitraryAmountOfText end"

>>> b="start "
>>> x=a.rindex(b)
>>> y=a.rindex(' end')
>>> a[x+len(b):y]
'AnotherArbitraryAmountOfText'
>>> c="garbage in, garbage out"
>>> x=c.rindex(b)
Traceback (most recent call last):
  File "", line 1, in 
ValueError: substring not found
>>>

--
Cheers.

Mark Lawrence

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


Re: [Tutor] Question on regular expressions

2013-02-12 Thread Peter Otten
Marcin Mleczko wrote:

> given this kind of string:
> 
> "start SomeArbitraryAmountOfText start AnotherArbitraryAmountOfText end"
> 
> a search string like: r"start.*?end" would give me the entire string
> from the first "start" to "end" : "start SomeArbitraryAmountOfText start
> AnotherArbitraryAmountOfText end"
> 
> but I am interested only in the second part between the 2nd "start" and
> the "end": "start AnotherArbitraryAmountOfText end"
> 
> What would be best, most clever way to search for that?
> 
> Or even more general: how do I exlude always the text between the last
> "start" and the "end" tag assuming the entire text contains several
> "start" tags spaced by an arbitrary amount of text befor the "end" tag?

>>> s = "start SomeArbitraryAmountOfText start AnotherArbitraryAmountOfText 
end"

>>> [t[::-1] for t in re.compile("dne(.*?)trats").findall(s[::-1])]
[' AnotherArbitraryAmountOfText ']

Ok, I'm not serious about this one -- but how about

>>> parts = (t.partition("end") for t in s.split("start"))
>>> [left for left, mid, right in parts if mid]
[' AnotherArbitraryAmountOfText ']


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


Re: [Tutor] Question on regular expressions

2013-02-12 Thread Alan Gauld

On 12/02/13 17:43, Marcin Mleczko wrote:


but I am interested only in the second part between the 2nd "start" and
the "end": "start AnotherArbitraryAmountOfText end"

What would be best, most clever way to search for that?


best and clever are not always the same.

The simplest way if its a fixed string is just use the string split() 
method...  being more 'clever' you could use the re.split() method to 
handle non-constant strings. Being even more clever you can define regex 
of increasing complexity to match the Nth appearance of a pattern. These 
kinds of regex are very easy to get wrong so you have to be very clever 
to get them right.


HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

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


[Tutor] Question on regular expressions

2013-02-12 Thread Marcin Mleczko
Hello,

given this kind of string:

"start SomeArbitraryAmountOfText start AnotherArbitraryAmountOfText end"

a search string like: r"start.*?end" would give me the entire string
from the first "start" to "end" : "start SomeArbitraryAmountOfText start
AnotherArbitraryAmountOfText end"

but I am interested only in the second part between the 2nd "start" and
the "end": "start AnotherArbitraryAmountOfText end"

What would be best, most clever way to search for that?

Or even more general: how do I exlude always the text between the last
"start" and the "end" tag assuming the entire text contains several
"start" tags spaced by an arbitrary amount of text befor the "end" tag?

Any ideas?

Thank you in advance. ;-)

Marcin

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


Re: [Tutor] Question on re.findall usage

2013-01-28 Thread Mitya Sirenef

On 01/28/2013 03:19 PM, Dave Wilder wrote:


> On 28 January 2013 2:44, : Oscar Benjamin 
[mailto:oscar.j.benja...@gmail.com wrote:

>
> Please post in plain text (not html) as otherwise the code gets 
screwed up.

> ...
>
> Some people like to use regexes for everything. I prefer to try 
string methods first as I find them easier to understand.

> Here's my attempt:
 junk_list = 'tmsh list net interface 1.3 media-ca 
\rpabilities\r\nnet interface 1.3 {\r\n media-capabilities {\r\n 
none\r\n auto\r\n 4SR4-FD\r\n 10T-HD\r\n 100TX-FD\r\n 100TX-HD\r\n 
1000T-FD\r\n 4LR4-FD\r\n 1000T-HD\r\n }\r\n}\r\n'

 junk_list = [s.strip() for s in junk_list.splitlines()] junk_list =
 [s for s in junk_list if s == 'auto' or s[:2] in ('10', '40')]
 junk_list
> ['auto', '4SR4-FD', '10T-HD', '100TX-FD', '100TX-HD', '1000T-FD', 
'4LR4-FD', '1000T-HD']

>
> Does that do what you want?
>
>
> Oscar
>
>
> *
>
> Got it Oscar. Thank you for your respectful corrections and your 
solution.
> I used "Rich Text" which is what I thought was recommended by the 
list gurus at one point. Plain Text it is then.

>
> Your response definitely does the trick and I can use that as a base 
for the future.

>
> As per Joel's comment that it is a variation of questions I asked in 
the past, right you are. I had to put this away for a while and am 
picking it up again now.

> I will get string manipulation / RegEx educated.
>
> Thank You,
>
> Dave

I would like to emphasize that regex is an entirely wrong approach for
this task. The reason is that it's very brittle, hard to read, hard to
debug and update if the text file changes. The first step should be to
simplfy the task -- in this case, to split the string into lines and
strip each line.

List comps as shown by Oscar is the best approach, but if you don't feel
comfortable with list comps, you can then use a loop:

lst = []
for line in junk_list:
if line == "auto"  : lst.append(line)
elif line.startswith("10") : lst.append(line)
elif line.startswith("40") : lst.append(line)

You could even use a regex as part of the loop:

for line in junk_list:
if re.match("^(auto|10|40)", line):
lst.append(line)

It's still much better than using a humongous regex.

 - m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

When a friend succeeds, I die a little.  Gore Vidal

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


Re: [Tutor] Question on re.findall usage

2013-01-28 Thread Dave Wilder

On 28 January 2013 2:44, : Oscar Benjamin [mailto:oscar.j.benja...@gmail.com 
wrote:

Please post in plain text (not html) as otherwise the code gets screwed up. 
...

Some people like to use regexes for everything. I prefer to try string methods 
first as I find them easier to understand. 
Here's my attempt:
>>> junk_list = 'tmsh list net interface 1.3 media-ca \rpabilities\r\nnet 
>>> interface 1.3 {\r\nmedia-capabilities {\r\nnone\r\n
>>> auto\r\n 4SR4-FD\r\n  10T-HD\r\n100TX-FD\r\n
>>> 100TX-HD\r\n1000T-FD\r\n4LR4-FD\r\n 1000T-HD\r\n
>>> }\r\n}\r\n'
>>> junk_list = [s.strip() for s in junk_list.splitlines()] junk_list = 
>>> [s for s in junk_list if s == 'auto' or s[:2] in ('10', '40')] 
>>> junk_list
['auto', '4SR4-FD', '10T-HD', '100TX-FD', '100TX-HD', '1000T-FD', 
'4LR4-FD', '1000T-HD']

Does that do what you want?


Oscar


*

Got it Oscar.  Thank you for your respectful corrections and your solution.
 I used "Rich Text" which is what  I thought was recommended by the list gurus 
at one point.   Plain Text it is then.

Your response definitely does the trick and I can use that as a base for the 
future.

As per Joel's comment that it is a variation of questions I asked in the past, 
right you are.   I had to put this away for a while and am picking it up again 
now.
I will get string manipulation / RegEx educated.

Thank You,

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


Re: [Tutor] Question on re.findall usage

2013-01-28 Thread Joel Goldstick
On Mon, Jan 28, 2013 at 2:15 PM, Dave Wilder  wrote:

>  Hello,
>
> I am trying using re.findall to parse the string below and then create a
> list from the results.
> junk_list = 'tmsh list net interface 1.3 media-ca \rpabilities\r\nnet
> interface 1.3 {\r\nmedia-capabilities {\r\nnone\r\n
> auto\r\n 4SR4-FD\r\n  10T-HD\r\n100TX-FD\r\n
> 100TX-HD\r\n1000T-FD\r\n4LR4-FD\r\n 1000T-HD\r\n
> }\r\n}\r\n'
>

This looks like a variation on the questions you asked over the last couple
of months.  Printing junk_list I get this:

>>> print junk_list
pabilitiesnet interface 1.3 media-ca
net interface 1.3 {
media-capabilities {
none
auto
 4SR4-FD
  10T-HD
100TX-FD
100TX-HD
1000T-FD
4LR4-FD
 1000T-HD
}
}
How do you get junk_list?  Read from a file?  Is there more in the file
besides what is in junk_list?  Do you have this exact file format every
time?

You might do better to use readline() instead of read(), and strip() each
line so that you don't have the new line issue.  I'm guessing but it looks
like you can toss every line until you get past media-capabilities, and
toss every line that contains }.  But maybe I am reading more into the data
format than is appropriate.

If my guesses are correct, you don't need regex stuff at all, because each
line (that you don't toss) contains something you want, and you can build
you list




> What I am doing now is obviously quite ugly, but I have not yet able to
> manipulate it to work how I want but in a much more efficient and modular
> way.
> I did some research on re.findall but am still confused as to how to do
> character repetition searches, which  I guess is what I need to do here.
> >> junk_list =
> re.findall(r'(auto|[1|4]0+[A-Z]-[HF]D|[1|4]0+[A-Z][A-Z]-[HF]D|[1|4]0+[A-Z][A-Z][0-9])',
> junk_list)
> >> junk_list
> ['auto', '4SR4', '10T-HD', '100TX-FD', '100TX-HD', '4LR4',
> '1000T-FD', '1000T-HD']
> >>>
>
> Basically, all I need to search on is:
>
>- auto
>- anything that starts w/ ‘1’ or ‘4’ and then any number of subsequent
>zeroes   e.g. 10T-HD, 4LR4-FD, 100TX-FD
>
>
> My environment:
> [root@f5ite ~/tests]$ uname -a
> Linux VM-QA-ITE-03 2.6.32-220.17.1.el6.i686 #1 SMP Tue May 15 22:09:39 BST
> 2012 i686 i686 i386 GNU/Linux
> [root@f5ite ~/tests]$
> [root@f5ite ~/tests]$ /usr/bin/python
> Python 2.7 (r27:82500, Jul  6 2010, 02:54:50)
> [GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>
> Any ideas?
>
> Thanks,
>
> Dave
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


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


Re: [Tutor] Question on re.findall usage

2013-01-28 Thread Oscar Benjamin
Please post in plain text (not html) as otherwise the code gets
screwed up. When I paste your code into a terminal this is what
happens:

>>> junk_list = 'tmsh list net interface 1.3 media-ca \rpabilities\r\nnet 
>>> interface 1.3 {\r\nmedia-capabilities {\r\nnone\r\n
>>> auto\r\n 4SR4-FD\r\n  10T-HD\r\n100TX-FD\r\n
>>> 100TX-HD\r\n1000T-FD\r\n4LR4-FD\r\n 1000T-HD\r\n
>>> }\r\n}\r\n'
>>> junk_list
'tmsh list net interface 1.3 media-ca \rpabilities\r\nnet interface
1.3 {\r\n\xc2\xa0\xc2\xa0\xc2\xa0 media-capabilities
{\r\n\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0
none\r\n\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0
auto\r\n\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0 4SR4-FD\r\n\xc2\xa0
10T-HD\r\n\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0
100TX-FD\r\n\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0
100TX-HD\r\n\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0
1000T-FD\r\n\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0
4LR4-FD\r\n \xc2\xa0\xc2\xa0\xc2\xa0
1000T-HD\r\n\xc2\xa0\xc2\xa0\xc2\xa0 }\r\n}\r\n'

Those \xc2\xa0 characters are non-breaking space characters. The
trouble is that I don't know if they were added by your email client
or are actually part of your junk string. I've assumed the former and
replaced them with spaces in the code I show below.

On 28 January 2013 19:15, Dave Wilder  wrote:
> Hello,
>
> I am trying using re.findall to parse the string below and then create a
> list from the results.
> junk_list = 'tmsh list net interface 1.3 media-ca \rpabilities\r\nnet
> interface 1.3 {\r\nmedia-capabilities {\r\nnone\r\n
> auto\r\n 4SR4-FD\r\n  10T-HD\r\n100TX-FD\r\n
> 100TX-HD\r\n1000T-FD\r\n4LR4-FD\r\n 1000T-HD\r\n
> }\r\n}\r\n'
>
> What I am doing now is obviously quite ugly, but I have not yet able to
> manipulate it to work how I want but in a much more efficient and modular
> way.
> I did some research on re.findall but am still confused as to how to do
> character repetition searches, which  I guess is what I need to do here.
>>> junk_list =
>>> re.findall(r'(auto|[1|4]0+[A-Z]-[HF]D|[1|4]0+[A-Z][A-Z]-[HF]D|[1|4]0+[A-Z][A-Z][0-9])',
>>> junk_list)
>>> junk_list
> ['auto', '4SR4', '10T-HD', '100TX-FD', '100TX-HD', '4LR4',
> '1000T-FD', '1000T-HD']

This output doesn't match what I would expect from the string above.
Why is '1000T-FD' after '4LR4-FD'? Is that the problem with the
code you posted?


>
> Basically, all I need to search on is:
>
> auto
> anything that starts w/ ‘1’ or ‘4’ and then any number of subsequent zeroes
> e.g. 10T-HD, 4LR4-FD, 100TX-FD

Does "any number" mean "one or more" or "zero or more"?

Some people like to use regexes for everything. I prefer to try string
methods first as I find them easier to understand. Here's my attempt:

>>> junk_list = 'tmsh list net interface 1.3 media-ca \rpabilities\r\nnet 
>>> interface 1.3 {\r\nmedia-capabilities {\r\nnone\r\n
>>> auto\r\n 4SR4-FD\r\n  10T-HD\r\n100TX-FD\r\n
>>> 100TX-HD\r\n1000T-FD\r\n4LR4-FD\r\n 1000T-HD\r\n
>>> }\r\n}\r\n'
>>> junk_list = [s.strip() for s in junk_list.splitlines()]
>>> junk_list = [s for s in junk_list if s == 'auto' or s[:2] in ('10', '40')]
>>> junk_list
['auto', '4SR4-FD', '10T-HD', '100TX-FD', '100TX-HD', '1000T-FD',
'4LR4-FD', '1000T-HD']

Does that do what you want?


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


[Tutor] Question on re.findall usage

2013-01-28 Thread Dave Wilder
Hello,

I am trying using re.findall to parse the string below and then create a list 
from the results.
junk_list = 'tmsh list net interface 1.3 media-ca \rpabilities\r\nnet interface 
1.3 {\r\nmedia-capabilities {\r\nnone\r\nauto\r\n 
4SR4-FD\r\n  10T-HD\r\n100TX-FD\r\n100TX-HD\r\n
1000T-FD\r\n4LR4-FD\r\n 1000T-HD\r\n}\r\n}\r\n'

What I am doing now is obviously quite ugly, but I have not yet able to 
manipulate it to work how I want but in a much more efficient and modular way.
I did some research on re.findall but am still confused as to how to do 
character repetition searches, which  I guess is what I need to do here.
>> junk_list = 
>> re.findall(r'(auto|[1|4]0+[A-Z]-[HF]D|[1|4]0+[A-Z][A-Z]-[HF]D|[1|4]0+[A-Z][A-Z][0-9])',
>>  junk_list)
>> junk_list
['auto', '4SR4', '10T-HD', '100TX-FD', '100TX-HD', '4LR4', '1000T-FD', 
'1000T-HD']
>>>

Basically, all I need to search on is:
-   auto
-   anything that starts w/ '1' or '4' and then any number of subsequent 
zeroes   e.g. 10T-HD, 4LR4-FD, 100TX-FD

My environment:
[root@f5ite ~/tests]$ uname -a
Linux VM-QA-ITE-03 2.6.32-220.17.1.el6.i686 #1 SMP Tue May 15 22:09:39 BST 2012 
i686 i686 i386 GNU/Linux
[root@f5ite ~/tests]$
[root@f5ite ~/tests]$ /usr/bin/python
Python 2.7 (r27:82500, Jul  6 2010, 02:54:50)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

Any ideas?

Thanks,

Dave

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


Re: [Tutor] Question regular expressions - the non-greedy pattern

2013-01-22 Thread Marcin Mleczko
Now I think I got it. Thanks a lot again.

Marcin

Am 22.01.2013 12:00, schrieb tutor-requ...@python.org:

> 
> Message: 1
> Date: Tue, 22 Jan 2013 11:31:01 +1100
> From: Steven D'Aprano 
> To: tutor@python.org
> Subject: Re: [Tutor] Question regular expressions - the non-greedy
>   pattern
> Message-ID: <50fdddc5.6030...@pearwood.info>
> Content-Type: text/plain; charset=UTF-8; format=flowed
> 
> On 22/01/13 10:11, Marcin Mleczko wrote:
>> -BEGIN PGP SIGNED MESSAGE-
>> Hash: SHA1
>>
>> Hello Hugo, hello Walter,
>>
>> first thank you very much for the quick reply.
>>
>> The functions used here i.e. re.match() are taken directly form the
>> example in the mentioned HowTo. I'd rather use re.findall() but I
>> think the general interpretetion of the given regexp sould be nearly
>> the same in both functions.
> 
> Regular expressions are not just "nearly" the same, they are EXACTLY
> the same, in whatever re function you call, with one exception:
> 
> re.match only matches at the start of the string.
> 
> 
>> So I'd like to neglect the choise of a particular function for a
>> moment a concentrate on the pure theory.
>> What I got so far:
>> in theory form s = '<Title'
>> '<.*?>' would match''''''''
> 
> Incorrect. It will match
> 
> '<'
> ''
> ''
> ''
> 
> 
> Why don't you try it and see?
> 
> py> s = '<Title'
> py> import re
> py> re.findall('<.*?>', s)
> ['<', '', '', '']
> 
> 
> The re module is very stable. The above is what happens in every Python
> version between *at least* 1.5 and 3.3.
> 
> 
>> to achieve this the engine should:
>> 1. walk forward along the text until it finds<
> 
> Correct. That matches the first "<".
> 
> 
>> 2. walk forward from that point until in finds>
> 
> Correct. That matches the first ">".
> 
> Since the regex has now found a match, it moves on to the next part
> of the regex. Since this regex is now complete, it is done, and
> returns what it has found.
> 
> 
>> 3. walk backward form that point (the one of>) until it finds<
> 
> Regexes only backtrack on *misses*, not once they successfully find
> a match. Once a regex has found a match, it is done.
> 
> 
>> 4. return the string between<  from 3. and>  from 2. as this gives the
>> least possible string between<  and>
> 
> Incorrect.
> 
> 
>> Did I get this right so far? Is this (=least possible string between<
>> and>), what non-greedy really translates to?
> 
> No. The ".*" regex searches forward as far as possible; the ".*?" searches
> forward as little as possible. They do not backtrack.
> 
> The only time a non-greedy regex will backtrack is if the greedy version
> will backtrack. Since ".*" has no reason to backtrack, neither does ".*?".
> 
> 
>> For some reason, I did not get so far the regexp engine in Python
>> omits step 3. and returns the string between<  from 1. and>  from 2.
>> resulting in '<'
>>
>> Am I right? If so, is there an easily graspable reason for the engine
>> designers to implement it this way?
> 
> Because that's the way regexes work. You would need to learn about
> regular expression theory, which is not easy material. But you can start
> here:
> 
> http://en.wikipedia.org/wiki/Regular_expression
> 
> and for more theoretical approach:
> 
> http://en.wikipedia.org/wiki/Chomsky_hierarchy
> http://en.wikipedia.org/wiki/Regular_language
> http://en.wikipedia.org/wiki/Regular_grammar
> 
> If you don't understand all the theory, don't worry, neither do I.
> 
> 
> 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question regular expressions - the non-greedy pattern

2013-01-21 Thread Alan Gauld

Your understanding is flawed.

Try these actions and ponder their significance...

>>> s = '>> re.search('<.*?>',s).group()
'<'
>>> re.search('<.*>',s).group()
'>> s = '>> re.search('<.*>',s).group()
'<'
>>> re.search('<.*t',s).group()
'>> re.search('<.*?t',s).group()
'<>>


The non greediness applies to what follows the '?' not what precedes it.
That is, it swallows everything up until the last possible matching 
pattern by default. Non greedy only swallows up to the first matching 
pattern after the ?


HTH

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

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


Re: [Tutor] Question regular expressions - the non-greedy pattern

2013-01-21 Thread Lie Ryan

On 22/01/13 10:11, Marcin Mleczko wrote:

-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hello Hugo, hello Walter,

first thank you very much for the quick reply.

The functions used here i.e. re.match() are taken directly form the
example in the mentioned HowTo. I'd rather use re.findall() but I
think the general interpretetion of the given regexp sould be nearly
the same in both functions.

So I'd like to neglect the choise of a particular function for a
moment a concentrate on the pure theory.
What I got so far:
in theory form s = '' would match '' '' '' ''
to achieve this the engine should:
1. walk forward along the text until it finds <
2. walk forward from that point until in finds >
3. walk backward form that point (the one of >) until it finds <
4. return the string between < from 3. and > from 2. as this gives the
least possible string between < and >

Did I get this right so far? Is this (=least possible string between <
and >), what non-greedy really translates to?


Nope, that's not how regex works. In particular, it does not do step 3, 
non-greedy regex do not walk backward to find the shortest string that 
matches.


What it does for the non-greedy pattern <.*?> is:

1. walk forward along the text until it finds <
2. if the next character matches . (any chars) then step one character 
forward, otherwise backtrack from where we left off in the previous step
3. if the next char is >, then we find a match, otherwise backtrack from 
where we left off in the previous step

4. return the string between < from 1 and > from 3

or alternatively

1. walk forward along the text until it finds <
2. walk forward from that point until in finds >
3. return the string between < from 1 and > from 2

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


Re: [Tutor] Question regular expressions - the non-greedy pattern

2013-01-21 Thread Walter Prins
Hi Marcin,


On 21 January 2013 23:11, Marcin Mleczko  wrote:

> first thank you very much for the quick reply.
>
No problem...


> The functions used here i.e. re.match() are taken directly form the
> example in the mentioned HowTo. I'd rather use re.findall() but I
> think the general interpretetion of the given regexp sould be nearly
> the same in both functions.
>

... except that the results are fundamentally different due to the
different goals for the 2 functions: the one (match) only matches a regex
from the first character of a string.  (No conceptual "walking forward"
unless you've managed to match the string to a regex.)  The other (find),
matches the first possible match (conceptually walking the starting point
forward only as far as necessary to find a possible match.)


> So I'd like to neglect the choise of a particular function for a
> moment a concentrate on the pure theory.
> What I got so far:
> in theory form s = ' '<.*?>' would match '' '' '' ''
> to achieve this the engine should:
> 1. walk forward along the text until it finds <
> 2. walk forward from that point until in finds >
>

Here, conceptually the regex engines work for your original regex is
complete and it returns a match.


> 3. walk backward form that point (the one of >) until it finds <
>

No.  No further walking backward when you've already matched the regex.

4. return the string between < from 3. and > from 2. as this gives the
> least possible string between < and >
>

"Non greedy" doesn't imply the conceptually altering the starting point in
a backwards manner after you've already found a match.


> Did I get this right so far? Is this (=least possible string between <
> and >), what non-greedy really translates to?
>

No, as explained above.

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


Re: [Tutor] Question regular expressions - the non-greedy pattern

2013-01-21 Thread Steven D'Aprano

On 22/01/13 10:11, Marcin Mleczko wrote:

-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hello Hugo, hello Walter,

first thank you very much for the quick reply.

The functions used here i.e. re.match() are taken directly form the
example in the mentioned HowTo. I'd rather use re.findall() but I
think the general interpretetion of the given regexp sould be nearly
the same in both functions.


Regular expressions are not just "nearly" the same, they are EXACTLY
the same, in whatever re function you call, with one exception:

re.match only matches at the start of the string.



So I'd like to neglect the choise of a particular function for a
moment a concentrate on the pure theory.
What I got so far:
in theory form s = '' would match


Incorrect. It will match

'<'
''
''
''


Why don't you try it and see?

py> s = ' import re
py> re.findall('<.*?>', s)
['<', '', '', '']


The re module is very stable. The above is what happens in every Python
version between *at least* 1.5 and 3.3.



to achieve this the engine should:
1. walk forward along the text until it finds<


Correct. That matches the first "<".



2. walk forward from that point until in finds>


Correct. That matches the first ">".

Since the regex has now found a match, it moves on to the next part
of the regex. Since this regex is now complete, it is done, and
returns what it has found.



3. walk backward form that point (the one of>) until it finds<


Regexes only backtrack on *misses*, not once they successfully find
a match. Once a regex has found a match, it is done.



4. return the string between<  from 3. and>  from 2. as this gives the
least possible string between<  and>


Incorrect.



Did I get this right so far? Is this (=least possible string between<
and>), what non-greedy really translates to?


No. The ".*" regex searches forward as far as possible; the ".*?" searches
forward as little as possible. They do not backtrack.

The only time a non-greedy regex will backtrack is if the greedy version
will backtrack. Since ".*" has no reason to backtrack, neither does ".*?".



For some reason, I did not get so far the regexp engine in Python
omits step 3. and returns the string between<  from 1. and>  from 2.
resulting in '<'

Am I right? If so, is there an easily graspable reason for the engine
designers to implement it this way?


Because that's the way regexes work. You would need to learn about
regular expression theory, which is not easy material. But you can start
here:

http://en.wikipedia.org/wiki/Regular_expression

and for more theoretical approach:

http://en.wikipedia.org/wiki/Chomsky_hierarchy
http://en.wikipedia.org/wiki/Regular_language
http://en.wikipedia.org/wiki/Regular_grammar

If you don't understand all the theory, don't worry, neither do I.



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


Re: [Tutor] Question regular expressions - the non-greedy pattern

2013-01-21 Thread Marcin Mleczko
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hello Hugo, hello Walter,

first thank you very much for the quick reply.

The functions used here i.e. re.match() are taken directly form the
example in the mentioned HowTo. I'd rather use re.findall() but I
think the general interpretetion of the given regexp sould be nearly
the same in both functions.

So I'd like to neglect the choise of a particular function for a
moment a concentrate on the pure theory.
What I got so far:
in theory form s = '' would match '' '' '' ''
to achieve this the engine should:
1. walk forward along the text until it finds <
2. walk forward from that point until in finds >
3. walk backward form that point (the one of >) until it finds <
4. return the string between < from 3. and > from 2. as this gives the
least possible string between < and >

Did I get this right so far? Is this (=least possible string between <
and >), what non-greedy really translates to?

For some reason, I did not get so far the regexp engine in Python
omits step 3. and returns the string between < from 1. and > from 2.
resulting in '<'

Am I right? If so, is there an easily graspable reason for the engine
designers to implement it this way?

If I'm wrong, where is my fault?

Marcin

Am 21.01.2013 17:23, schrieb Walter Prins:
> Hi,
> 
> 
> 
> On 21 January 2013 14:45, Marcin Mleczko  > wrote:
> 
> Did I get the concept of non-greedy wrong or is this really a bug?
> 
> 
> Hugo's already explained the essence of your problem, but just to 
> add/reiterate:
> 
> a) match() will match at the beginning of the string (first
> character) or not at all.  As specified your regex does in fact
> match from the first character as shown so the result is correct.
> (Aside, "" in "<" does not in fact match *from the
> beginning of the string* so is besides the point for the match()
> call.)
> 
> b) Changing your regexp so that the body of the tag *cannot*
> contain "<", and then using search() instead, will fix your
> specific case for you:
> 
> import re
> 
> s = ' 
> matchobj = re.match(tag_regex, s) print "re.match() result:",
> matchobj # prints None since no match at start of s
> 
> matchobj = re.search(tag_regex, s) # prints something since regex
> matches at index 1 of string print "re.search() result:\n", print
> "span:", matchobj.span() print "group:", matchobj.group()
> 
> 
> Walter
> 
> 
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.17 (MingW32)
Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/

iQEcBAEBAgAGBQJQ/cs4AAoJEDAt44dGkgj1CSUH/iT7b7jKafu8ugXGlNiLtISy
Abt6GcAZuwxeuokH7dna4FGA54x5BZzjrglu+VWrRJx8hsherL04Qt216V725Tpx
SN4IgLtK+AYAuhI73iBvyWK51vOTkWDzLrs6DYjNEWohw+n9QEtZVEkgMej/p760
6YDs8lbrHxVqUGiFTQr+vpCb6W85sOr+RlfkBsFibC3S17wRNVtaYWITc85I5Dfr
lLBh2kPzi9ITKPIFag4GRNzj1rWtp0NUGGAjyhmgijdl2GbiCLAGteJGoUvajOa1
889UuPItCi4zVJ5PJv0PDej8eD0ppd+k0rRHQK3SgaSgtTDgviGOvs3Ch4A9/Sk=
=Qo8U
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question regular expressions - the non-greedy pattern

2013-01-21 Thread Steven D'Aprano

On 22/01/13 01:45, Marcin Mleczko wrote:


Now I'm changing the input string to (adding an extra '<'):

s = '', s).group()
I would expect to get the same result



as I'm using the non-greedy pattern. What I get is

<

Did I get the concept of non-greedy wrong or is this really a bug?



Definitely not a bug.


Your regex says:

"Match from the beginning of the string: less-than sign, then everything
up to the FIRST (non-greedy) greater-than sign."

So it matches the "<" at the beginning of the string, followed by the
"".


To get the result you are after, you could do this:

# Match two < signs, but only report from the second on
re.match('<(<.*?>)', s).group(1)


# Skip the first character
re.match('<.*?>', s[1:]).group()


# Don't match on < inside the <> tags
re.search('<[^<]*?>', s).group()


Notice that the last example must use re.search, not re.match,
because it does not match the beginning of the string.



By the way, you cannot parse general purpose HTML with a regular
expressions. You really should learn how to use Python's html
parsers, rather than trying to gerry-rig something that will do a
dodgy job.




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


Re: [Tutor] Question regular expressions - the non-greedy pattern

2013-01-21 Thread Walter Prins
Hi,



On 21 January 2013 14:45, Marcin Mleczko  wrote:

> Did I get the concept of non-greedy wrong or is this really a bug?


Hugo's already explained the essence of your problem, but just to
add/reiterate:

a) match() will match at the beginning of the string (first character) or
not at all.  As specified your regex does in fact match from the first
character as shown so the result is correct.  (Aside, "" in "<"
does not in fact match *from the beginning of the string* so is besides the
point for the match() call.)

b) Changing your regexp so that the body of the tag *cannot* contain "<",
and then using search() instead, will fix your specific case for you:

import re

s = '

Re: [Tutor] Question regular expressions - the non-greedy pattern

2013-01-21 Thread Hugo Arts
On Mon, Jan 21, 2013 at 3:45 PM, Marcin Mleczko wrote:

> Now I'm changing the input string to (adding an extra '<'):
>
> s = '
> and evoking the last command again:
>
> print re.match('<.*?>', s).group()
> I would expect to get the same result
>
> 
>
> as I'm using the non-greedy pattern. What I get is
>
> <
>
> Did I get the concept of non-greedy wrong or is this really a bug?
>

No, this is not a bug. Note first that you are using re.match, which only
tries to match from the beginning of the string. If you want to match
anywhere inside the string, you should use re.search, which returns the
first match found. However even re.search will still return '<' since
that *is* a valid match of the regular expression  '<.*?>', and re.search
returns the first match it finds.

in essence, re.search first tries calling match(regex, s), then
match(regex, s[1:]), then match(regex, s[2:]) and so on and so on, moving
on one character at the time until the regular expression produces a match.
Since the regex produces a match on the first character, matching on the
second isn't even tried.

It is true that non-greedy matching will try to match the fewest number of
characters possible. However, it will not cause the regular expression
engine to backtrack, i.e. go back on parts of the pattern already matched
and match them elsewhere to try and see if that produces a shorter match.
If a greedy variant of a regex matches, then the non-greedy variant *will*
also match at the same place. The only difference is the length of the
result.

more generally, regexes can not parse HTML fully since they simply lack the
power. HTML is just not a regular language. If you want to parse arbitrary
HTML documents, or even sufficiently complex HTML documents you should get
a real HTML parser library (python includes one, check the docs). If you
just want to grab some data from HTML tags it's probably ok to use regexes
though, if you're careful.

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


[Tutor] Question regular expressions - the non-greedy pattern

2013-01-21 Thread Marcin Mleczko
Hello,

in the howto (http://docs.python.org/2/howto/regex.html#regex-howto)
there are code examples near the end of the page  (the non-greedy
pattern) I am referring to:

s = 'Title'
>>> len(s)
32
>>> print re.match('<.*>', s).span()
(0, 32)
>>> print re.match('<.*>', s).group()
Title

print re.match('<.*?>', s).group() #<- I'm referring to this


So far everything is fine.

Now I'm changing the input string to (adding an extra '<'):

s = '', s).group()
I would expect to get the same result



as I'm using the non-greedy pattern. What I get is

<

Did I get the concept of non-greedy wrong or is this really a bug?
I've treid this with
python -V
Python 2.7.3
on Win 7 64 Bit as well as Ubuntu 64 bit.

I'd be glad to here from you soon.

Thank's a lot for your effort.

best regards

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


Re: [Tutor] Question regarding lists and manipulating items in lists.

2013-01-19 Thread Scurvy Scott
[SNIP]

Thank you guys so much, sorry for the delayed response. It's awesome
being able to learn a thing or two from people who know so much about
their craft. I've got the code working the way I envisioned it now and
probably couldn't without y'alls help.

I'm so glad this mailing list exists, thanks again.

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


Re: [Tutor] Question regarding lists and manipulating items in lists.

2013-01-16 Thread Steven D'Aprano

On 16/01/13 11:23, Scurvy Scott wrote:


After playing with your example I keep being told that list has no
attribute int_to_note. I know what the problem is, I just don't know
how to fix it.


Oops, sorry about that, that is my fault. I did warn that my code was
untested!

If you know what the problem is, the solution should be obvious. Before
reading ahead, try explaining to yourself what you think the problem
actually is. If you do that, the answer should pop right out at you.

Still need a hint? Okay, try this:


"I need to convert the Fibonacci integers to musical notes, using the
notes.int_to_note function imported from mingus.core. But inside Steven's
make_notes function, he sets a local variable `notes = []`, which means
that inside the function I cannot access the global notes.int_to_note."

Or, a shorter version:

"I have notes.int_to_note, which I need, but accessing it is blocked by
the local variable notes which is a list."

So the obvious solution is...


...rename the local variable `notes` to something else.


def make_notes(num_notes):
it = fib()
music = []  # start with an empty list
for i in range(num_notes):
n = next(it) % 12  # get the next Fibonacci number, modulo 12
music.append(notes.int_to_note(n))
return music



Still untested.



Also, I believe I've fixed my email so it will no longer be in HTML or
anything fancy, just plain text.


Many thanks!

More comments below.



So right now my code is:

import mingus.core.notes as notes

#fibonacci
def fib():
 a, b = 0, 1
 while True:
 yield b
a, b = b, a+b


I have now tested that, and it works fine:

py> it = fib()
py> [next(it) for i in range(15)]
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]


Some people prefer to start the Fibonacci sequence with 0. That's an
easy change to make: change the line "yield b" to "yield a". But
Wolfram Mathworld and Mathematica start the Fibonacci sequence with
1, 1, 2, ... rather than 0, 1, 1, ... so that's good enough for me.

http://mathworld.wolfram.com/FibonacciNumber.html




def make_notes(num_notes):
it = fib()
notes = []
for i in range(num_notes):
n = next(it) % 12
notes.append(notes.int_to_note(n))
return notes

Which is pretty different from what my original code was.



Maybe so, but I'm teaching you a practice that will see you in good stead
whenever you program: each function should do *one* thing.

Think of programming as creating tools. You wouldn't try to create a single
tool for cutting wood, driving screws into it, and painting it. Instead we
have three tools: saw, screwdriver, paint brush. It's *much* easier to make
three separate tools than a single tool that tries to do all three jobs.

Likewise for your program. It is better to write separate functions to:

* create the Fibonacci numbers;

* turn them into musical notes;


than to do both jobs in one function. Now in *this* case, the labour saved
is relatively small. But it is a good habit to get into, and when you get
to large, complex programs it becomes essential.




 The
generator function doesn't actually do anything when called, it just
tells me it's a generator function and where it's located.


If you look at how my code uses the generator function, you will see the
correct way to use it. Here's another example:


py> it = fib()
py> n = next(it)
py> while n < 100:
... print n
... n = next(it)
...
1
1
2
3
5
8
13
21
34
55
89




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


Re: [Tutor] Question regarding lists and manipulating items in lists.

2013-01-15 Thread Andreas Perstinger

On 16.01.2013 01:23, Scurvy Scott wrote:
> After playing with your example I keep being told that list has no
> attribute int_to_note. I know what the problem is, I just don't know
> how to fix it.
[SNIP]
> So right now my code is:
>
> import mingus.core.notes as notes
  ^
On this line you import your module and give it the name "notes".

> def make_notes(num_notes):
>it = fib()
>notes = []
^

Inside your function "notes" is a list.

>for i in range(num_notes):
>n = next(it) % 12
>notes.append(notes.int_to_note(n))
 ^

Since "notes" is a list inside the function, Python tries to find the 
method "int_to_note" for a list and fails. But I think you want to use 
the function which is defined in your module.


You have to either rename your module reference or your list.

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


Re: [Tutor] Question regarding lists and manipulating items in lists.

2013-01-15 Thread Scurvy Scott

>> So here I extract out of your code (untested!) a generator which produces
>> an infinite series of Fibonacci numbers, one at a time:
>>
>> def fib():
>>
>> a, b = 0, 1
>> while True:
>> yield b
>>
>> a, b = b, a+b
>>
>>
>> This is untested, I may have got it wrong.
>>
>> Next, a function to generate notes from those Fibonacci numbers:
>>
>>
>> def make_notes(num_notes):
>> it = fib()
>> notes = []  # start with an empty list
>> for i in range(num_notes):
>> n = next(it) % 12  # get the next Fibonacci number, modulo 12
>> notes.append(notes.int_to_note(n))
>> return notes
>>
>>
>> That returns a list of notes.
>>
>>
>> Does that help? Start with that, and see how you go.
>>
>>
>>
>> --
>> Steven
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>
> Steve
> After playing with your example I keep being told that list has no
> attribute int_to_note. I know what the problem is, I just don't know
> how to fix it.
> Also, I believe I've fixed my email so it will no longer be in HTML or
> anything fancy, just plain text.
>
> So right now my code is:
>
> import mingus.core.notes as notes
>
>
> #fibonacci
> def fib():
> a, b = 0, 1
> while True:
> yield b
> a, b = b, a+b
>
>
> def make_notes(num_notes):
> it = fib()
> notes = []
> for i in range(num_notes):
> n = next(it) % 12
> notes.append(notes.int_to_note(n))
> return notes
>
> Which is pretty different from what my original code was. The
> generator function doesn't actually do anything when called, it just
> tells me it's a generator function and where it's located. And like I
> said the listing function doesn't want to comply with the module being
> called under append method. My code was working almost as I intended
> it to, it just wasn't creating a list properly of everything, which I
> didn't notice until after one of you guys mentioned it to me. Now I
> see it and I can sorta visualize what I'm supposed to do, but can't
> see what to do to fix it, if that makes any sense.


On a hunch I've gone back to my original code, and feel I've almost
got the list properly working.

import mingus.core.notes as notes


#fibonacci
def fib(num1,num2):
a, b = 0, 1
for i in xrange(num1,num2):
c = b % 12
a_list= []
a, b = b, a+b
while True:
a_list.append(notes.int_to_note(c))
print a_list

The problem here, which most of you will probably see immediately, is
that all this does is infinitely append the same note to the list over
and over again, which is not my intention. This is the closest I've
gotten the code to actually working somewhat correctly as far as this
list is concerned. Any hints would be helpful.

I also think Oscars solution with searching the list for items in the
'search' list and then just removing them is the most elegant so far
but I'm still open to anything you guys can show me, that's why you're
the tutors and I came here to ask, right?

I appreciate any information y'all can share.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question regarding lists and manipulating items in lists.

2013-01-15 Thread Scurvy Scott
On Tue, Jan 15, 2013 at 4:01 PM, Steven D'Aprano  wrote:
> On 16/01/13 10:40, Scurvy Scott wrote:
> [...]
>
>> Anyways, the problem I'm having is I'm not really sure how to search a
>> list
>> for multiple elements and remove just those elements. Below is my code so
>> far, and information y'all could provide would be appreciated. Thanks.
>
>
> Actually, your problem so far is that you aren't even producing a list of
> elements at all, you keep creating a *single* element, then throwing it
> away when you generate the next Fibonacci number.
>
> Also, you, or more likely Gmail, lost the indentation in your code, so I'm
> going to have to guess what you intended rather than what you have. That's
> because you are sending HTML email, which eats spaces.
>
>
>
>> import mingus.core.notes as notes
>> #fibonacci
>> def fib(num1,num2):
>> a, b = 0, 1
>> for i in xrange(num1,num2):
>> c = b % 12 #modulo 12 on each generated fibonacci number
>> a_list= [notes.int_to_note(c)] #using Mingus to translate the Fib mod12
>> numbers into notes and then (I think) storing each one as an element in a
>> list?
>> a, b = b, a+b #this is just the algorithm for the fibonacci numbers
>
>
>
> Firstly, I recommend that you follow the principle "separation of concerns".
> Keep a separate function for each part of the problem:
>
> * generate Fibonacci numbers;
> * turn them into notes;
>
>
> So here I extract out of your code (untested!) a generator which produces
> an infinite series of Fibonacci numbers, one at a time:
>
> def fib():
>
> a, b = 0, 1
> while True:
> yield b
>
> a, b = b, a+b
>
>
> This is untested, I may have got it wrong.
>
> Next, a function to generate notes from those Fibonacci numbers:
>
>
> def make_notes(num_notes):
> it = fib()
> notes = []  # start with an empty list
> for i in range(num_notes):
> n = next(it) % 12  # get the next Fibonacci number, modulo 12
> notes.append(notes.int_to_note(n))
> return notes
>
>
> That returns a list of notes.
>
>
> Does that help? Start with that, and see how you go.
>
>
>
> --
> Steven
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

Steve
After playing with your example I keep being told that list has no
attribute int_to_note. I know what the problem is, I just don't know
how to fix it.
Also, I believe I've fixed my email so it will no longer be in HTML or
anything fancy, just plain text.

So right now my code is:

import mingus.core.notes as notes


#fibonacci
def fib():
a, b = 0, 1
while True:
yield b
a, b = b, a+b


def make_notes(num_notes):
it = fib()
notes = []
for i in range(num_notes):
n = next(it) % 12
notes.append(notes.int_to_note(n))
return notes

Which is pretty different from what my original code was. The
generator function doesn't actually do anything when called, it just
tells me it's a generator function and where it's located. And like I
said the listing function doesn't want to comply with the module being
called under append method. My code was working almost as I intended
it to, it just wasn't creating a list properly of everything, which I
didn't notice until after one of you guys mentioned it to me. Now I
see it and I can sorta visualize what I'm supposed to do, but can't
see what to do to fix it, if that makes any sense.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question regarding lists and manipulating items in lists.

2013-01-15 Thread Oscar Benjamin
On 15 January 2013 23:53, Scurvy Scott  wrote:
>> > Anyways, the problem I'm having is I'm not really sure how to search a list
>> > for multiple elements and remove just those elements. Below is my code so
>> > far, and information y'all could provide would be appreciated. Thanks.
>>
[SNIP]
>
> What I meant to say is, I want to be able to search the generated list
> for a specific set of strings so like
>
> list = ['a','b','c','d','e','f','g']
> search = ['b','d','g']
> list.del[search]

How about:

new_list = [element for element in list if element not in search]

(It would be more efficient to use a set but it's not strictly necessary)


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


Re: [Tutor] Question regarding lists and manipulating items in lists.

2013-01-15 Thread Steven D'Aprano

On 16/01/13 10:40, Scurvy Scott wrote:
[...]

Anyways, the problem I'm having is I'm not really sure how to search a list
for multiple elements and remove just those elements. Below is my code so
far, and information y'all could provide would be appreciated. Thanks.


Actually, your problem so far is that you aren't even producing a list of
elements at all, you keep creating a *single* element, then throwing it
away when you generate the next Fibonacci number.

Also, you, or more likely Gmail, lost the indentation in your code, so I'm
going to have to guess what you intended rather than what you have. That's
because you are sending HTML email, which eats spaces.



import mingus.core.notes as notes
#fibonacci
def fib(num1,num2):
a, b = 0, 1
for i in xrange(num1,num2):
c = b % 12 #modulo 12 on each generated fibonacci number
a_list= [notes.int_to_note(c)] #using Mingus to translate the Fib mod12
numbers into notes and then (I think) storing each one as an element in a
list?
a, b = b, a+b #this is just the algorithm for the fibonacci numbers



Firstly, I recommend that you follow the principle "separation of concerns".
Keep a separate function for each part of the problem:

* generate Fibonacci numbers;
* turn them into notes;


So here I extract out of your code (untested!) a generator which produces
an infinite series of Fibonacci numbers, one at a time:

def fib():
a, b = 0, 1
while True:
yield b
a, b = b, a+b


This is untested, I may have got it wrong.

Next, a function to generate notes from those Fibonacci numbers:


def make_notes(num_notes):
it = fib()
notes = []  # start with an empty list
for i in range(num_notes):
n = next(it) % 12  # get the next Fibonacci number, modulo 12
notes.append(notes.int_to_note(n))
return notes


That returns a list of notes.


Does that help? Start with that, and see how you go.



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


Re: [Tutor] Question regarding lists and manipulating items in lists.

2013-01-15 Thread Oscar Benjamin
On 15 January 2013 23:40, Scurvy Scott  wrote:
[SNIP]
>
> Anyways, the problem I'm having is I'm not really sure how to search a list
> for multiple elements and remove just those elements. Below is my code so
> far, and information y'all could provide would be appreciated. Thanks.

Perhaps you'd like to use a list comprehension to filter out the
values you are interested in:

>>> my_list = [1,4,12,3,5,2,1,45,6,32]
>>> my_filtered_list = [x for x in my_list if x%2] # only the odd numbers
>>> print my_filtered_list
[1, 3, 5, 1, 45]

>
> import mingus.core.notes as notes
> #fibonacci
> def fib(num1,num2):
> a, b = 0, 1
> for i in xrange(num1,num2):
> c = b % 12 #modulo 12 on each generated fibonacci number
> a_list= [notes.int_to_note(c)] #using Mingus to translate the Fib mod12
> numbers into notes and then (I think) storing each one as an element in a
> list?
> a, b = b, a+b #this is just the algorithm for the fibonacci numbers

Please post in plain-text rather than html as it screws up the code
formatting (see above).


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


[Tutor] Question regarding lists and manipulating items in lists.

2013-01-15 Thread Scurvy Scott
Hello guys, I'm using Ubuntu 12.10 and Python 2.7 right now. I'm working on
code using the Mingus module but this question isn't specific to this
module, per se.

What I'm trying to do is to generate the fibonacci numbers up to a given N
and then do modulo 12 on each number in order to create a list of numbers
for the Mingus module to convert to notes. What I would like to do is store
each note created in a different element in a list so that I can later
manipulate it, say by removing certain note letters from the list at will.
That way the scales created by the program can become more useful, for
example I could remove all notes that aren't present in say a Harmonic
Minor scale, and only keep the list items that do exist in that scale in a
given key. That way it becomes, in a way, like the computer is writing your
guitar solos! Pretty neat I think.

Anyways, the problem I'm having is I'm not really sure how to search a list
for multiple elements and remove just those elements. Below is my code so
far, and information y'all could provide would be appreciated. Thanks.

import mingus.core.notes as notes
#fibonacci
def fib(num1,num2):
a, b = 0, 1
for i in xrange(num1,num2):
c = b % 12 #modulo 12 on each generated fibonacci number
a_list= [notes.int_to_note(c)] #using Mingus to translate the Fib mod12
numbers into notes and then (I think) storing each one as an element in a
list?
a, b = b, a+b #this is just the algorithm for the fibonacci numbers
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question about the raw string

2012-11-27 Thread Steven D'Aprano
On Wed, Nov 28, 2012 at 01:01:12AM +, JiangShan wrote:
> Hi everyone, 
> 
>I am studying the python 3 and I am confused about the raw 
>string. Why does the python interpreter do not escape the 
>single backslash before the quotes even I add a "r" before the 
>string.  The following is an example:
>
>>>> print(r"\")
>   
> SyntaxError: EOL while scanning string literal
>>>> print(r"\\")
> \\
> >>> 

A very good question! Note that this is not just in Python 3, the same 
thing applies to all versions of Python, and even other implementations 
like IronPython:

steve@runes:~$ ipy
IronPython 2.6 Beta 2 DEBUG (2.6.0.20) on .NET 2.0.50727.1433
Type "help", "copyright", "credits" or "license" for more information.
>>> s = r"\"
  File "", line 1
s = r"\"

^
SyntaxError: EOL while scanning single-quoted string



Unfortunately, there is no good answer except "that's the way it is, 
because that's the way the string parser is designed to work". It is a 
documented limitation of raw strings:

http://docs.python.org/2/reference/lexical_analysis.html#string-literals

and it has been reported as a bug but closed as "Invalid":

http://bugs.python.org/issue1271



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


[Tutor] Question about the raw string

2012-11-27 Thread JiangShan
Hi everyone, 


   I am studying the python 3 and I am confused about the raw string. Why 
does the python interpreter do not escape the single backslash  before the 
quotes even I add a "r" before the string.  The following is an example:
   >>> print(r"\")
  
SyntaxError: EOL while scanning string literal
   >>> print(r"\\")
\\
>>> 




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


Re: [Tutor] Question

2012-10-28 Thread Alan Gauld

On 28/10/12 17:41, Emile van Sebille wrote:


How can I use wxpython on python 3.3.0?


Actually, it looks to me that the v3.x compatible wxpython is being
rebranded as Project Phoenix

-- see http://wiki.wxpython.org/ProjectPhoenix


That's good news although two names for the same toolkit will confuse 
things! But good to dsee progress. And a pity the wxPython home page 
makes no mention of Phoenix.



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

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


Re: [Tutor] Question

2012-10-28 Thread Mark Lawrence

On 28/10/2012 17:41, Emile van Sebille wrote:

On 10/27/2012 2:19 PM, Alan Gauld wrote:

On 27/10/12 20:50, Amin Memar wrote:

Hi there!
How can I use wxpython on python 3.3.0?


You can't its not supported yet.
So you will need to either port the code yourself or use Python 2.7.

This is not uncommon with third party modules a lot of them are still on
v2. It is a lot of work to convert a large code base from Python 2 to 3
and then test it thoroughly and the people doing the work are nearly all
volunteers.

So either find another GUI framework (like Tkinter) ) that works with
Python 3 or downshift to v2.7.



Actually, it looks to me that the v3.x compatible wxpython is being
rebranded as Project Phoenix

-- see http://wiki.wxpython.org/ProjectPhoenix

Emile



Thanks for the link that's extremely useful.

For the benefit of all here's the link to the wxPython mailing lists, 
there are many references to Phoenix on the development list 
http://wxpython.org/maillist.php


--
Cheers.

Mark Lawrence.

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


Re: [Tutor] Question

2012-10-28 Thread Emile van Sebille

On 10/27/2012 2:19 PM, Alan Gauld wrote:

On 27/10/12 20:50, Amin Memar wrote:

Hi there!
How can I use wxpython on python 3.3.0?


You can't its not supported yet.
So you will need to either port the code yourself or use Python 2.7.

This is not uncommon with third party modules a lot of them are still on
v2. It is a lot of work to convert a large code base from Python 2 to 3
and then test it thoroughly and the people doing the work are nearly all
volunteers.

So either find another GUI framework (like Tkinter) ) that works with
Python 3 or downshift to v2.7.



Actually, it looks to me that the v3.x compatible wxpython is being 
rebranded as Project Phoenix


-- see http://wiki.wxpython.org/ProjectPhoenix

Emile


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


Re: [Tutor] Question

2012-10-27 Thread Alan Gauld

On 27/10/12 20:50, Amin Memar wrote:

Hi there!
How can I use wxpython on python 3.3.0?


You can't its not supported yet.
So you will need to either port the code yourself or use Python 2.7.

This is not uncommon with third party modules a lot of them are still on 
v2. It is a lot of work to convert a large code base from Python 2 to 3 
and then test it thoroughly and the people doing the work are nearly all 
volunteers.


So either find another GUI framework (like Tkinter) ) that works with 
Python 3 or downshift to v2.7.


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

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


[Tutor] Question

2012-10-27 Thread Amin Memar
Hi there!
How can I use wxpython on python 3.3.0?
thanks

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


Re: [Tutor] Question about language code

2012-10-11 Thread eryksun
On Fri, Oct 12, 2012 at 12:37 AM, eryksun  wrote:
>
> For example (untested):
>
> >>> locale.setlocale(locale.LC_ALL, 'German_Germany.1252')

I got around to testing the above, and it works. Also, the Python docs
say "if [locale is] an iterable, it’s converted to a locale name using
the locale aliasing engine." This doesn't work on Windows. It aliases
a tuple of ('German_Germany', '1252') to 'de_DE.cp1252', which Windows
doesn't recognize.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question about language code

2012-10-11 Thread eryksun
On Thu, Oct 11, 2012 at 11:12 PM, Dae James  wrote:
>
 import locale
 loc = locale.getlocale() # get current locale
> # use German locale; name might vary with platform
 locale.setlocale(locale.LC_ALL, 'de_DE')

This depends on the C runtime. For Windows, see MSDN:

setlocale
http://msdn.microsoft.com/en-us/library/x99tb11d
Language strings
http://msdn.microsoft.com/en-us/library/39cwe7zf
Country/Region strings
http://msdn.microsoft.com/en-us/library/cdax410z
Code pages
http://msdn.microsoft.com/en-us/library/cc195051

For example (untested):

>>> locale.setlocale(locale.LC_ALL, 'German_Germany.1252')


>From the MSDN setlocale() docs:

The "locale" argument can be formatted as follows:

setlocale( LC_ALL, "" );
Sets the locale to the default, which is the user-default ANSI code
page obtained from the operating system.

setlocale( LC_ALL, ".OCP" );
Explicitly sets the locale to the current OEM code page obtained from
the operating system.

setlocale( LC_ALL, ".ACP" );
Sets the locale to the ANSI code page obtained from the operating system.

setlocale( LC_ALL, "[lang_ctry]" );
Sets the locale to the language and country/region indicated, using
the default code page obtained from the host operating system.

setlocale( LC_ALL, "[lang_ctry.cp]" );
Sets the locale to the language, country/region, and code page
indicated in the [lang_ctry.cp] string. You can use various
combinations of language, country/region, and code page.

For example:

setlocale( LC_ALL, "French_Canada.1252" );

// Set code page to French Canada ANSI default
setlocale( LC_ALL, "French_Canada.ACP" );

// Set code page to French Canada OEM default
setlocale( LC_ALL, "French_Canada.OCP" );
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Question about language code

2012-10-11 Thread Dae James
Here is a example in "Python v2.7.2 document":

>>> import locale
>>> loc = locale.getlocale() # get current locale
# use German locale; name might vary with platform
>>> locale.setlocale(locale.LC_ALL, 'de_DE')

However, the result of executing on my computer is:
>>> locale.setlocale(locale.LC_ALL, 'de_DE')
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python27\lib\locale.py", line 531, in setlocale
return _setlocale(category, locale)
locale.Error: unsupported locale setting

Why is it unsuccessful? 
My os is Windows 7. My python version is 2.7.2. 




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


Re: [Tutor] Question about lists

2012-09-21 Thread Hugo Arts
On Fri, Sep 21, 2012 at 3:31 PM, Leo Degon  wrote:

> I'm trying to create a class where the main focus is creating a list whose
> elements are lists and the elements of those lists are collection of zeros
> and ones. I am trying to create functions to rotate the list ninety
> degrees, to reflect it. Having a few problems with the rotation.
> get TypeError: 'list' object is not callable
>
> def pset(n):
> for i in n:
> print(i)
> class board():
> def make(self,size):
> b=[]
> for i in range(size[0]):
> b.append([])
> for j in range(size[1]):
> b[i].append(0)
> return b
>
> def rotate(self,board,size):
> size[0],size[1]=size[1],size[0]
> new=board(size)
> lists=[]
> for j in range(size[1]):
> lists.append([])
> for i in range(size[0]).__reversed__():
> lists[j].append(board[i][j])
> for i in range(size[1]):
> for j in range(size[0]):
> new.board[i,j]=lists[i,j]
> return(new.board)
> def __init__(self,size):
> self.size=size
> self.board=self.make(size)
> y=[7,7]
> x=board(y)
> pset(x.board)
> x.board[0][0]=1
> print()
> pset(x.board)
> print()
> x.board=x.rotate(x.board,x.size)
> pset(x.board)
> print()
>
>
Please always include a full traceback, it makes the error much more
obvious. For example, running your code I get:

>>>
[0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0]
()
[1, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0]
()

Traceback (most recent call last):
  File "C:/Users/hugo/Downloads/test.py", line 35, in 
x.board=x.rotate(x.board,x.size)
  File "C:/Users/hugo/Downloads/test.py", line 15, in rotate
new=board(size)
TypeError: 'list' object is not callable
>>>

This makes it fairly obvious what is going on. in the rotate function, you
have an argument called board, and your class is also called board. You
can't have the same name refer to two different things. What happens is
that the argument "masks" the class, making it inaccessible.

I should also say it is very confusing to have a class called board with an
attribute that is also called board. You should think about naming your
variables more clearly to minimize confusion.

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


Re: [Tutor] Question about lists

2012-09-21 Thread Peter Otten
Leo Degon wrote:

> I'm trying to create a class where the main focus is creating a list whose
> elements are lists and the elements of those lists are collection of zeros
> and ones. I am trying to create functions to rotate the list ninety
> degrees, to reflect it. Having a few problems with the rotation.
> get TypeError: 'list' object is not callable
> 
> def pset(n):
> for i in n:
> print(i)
> class board():
> def make(self,size):
> b=[]
> for i in range(size[0]):
> b.append([])
> for j in range(size[1]):
> b[i].append(0)
> return b
> 
> def rotate(self,board,size):

The local parameter "board" shades the class with the same name, 

> size[0],size[1]=size[1],size[0]
> new=board(size)

so here you are not making a new board instance but instead trying to call 
the board parameter which is a list. To fix this problem you have to rename 
the parameter or the class. I recommend that you rename the class to Board 
(by convention class names start with an uppercase letter).

As to the parameter board, you actually don't need it at all -- you can 
instead make the board attribute of the new Board instance a rotated version 
of self.board.

(There are more bugs in your code, but I suggest you tackle them one at a 
time. Come back here if you need help fixing them)

> lists=[]
> for j in range(size[1]):
> lists.append([])
> for i in range(size[0]).__reversed__():
> lists[j].append(board[i][j])
> for i in range(size[1]):
> for j in range(size[0]):
> new.board[i,j]=lists[i,j]
> return(new.board)
> def __init__(self,size):
> self.size=size
> self.board=self.make(size)
> y=[7,7]
> x=board(y)
> pset(x.board)
> x.board[0][0]=1
> print()
> pset(x.board)
> print()
> x.board=x.rotate(x.board,x.size)
> pset(x.board)
> print()


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


Re: [Tutor] Question about lists

2012-09-21 Thread Dave Angel
On 09/21/2012 09:31 AM, Leo Degon wrote:
> I'm trying to create a class where the main focus is creating a list whose
> elements are lists and the elements of those lists are collection of zeros
> and ones. I am trying to create functions to rotate the list ninety
> degrees, to reflect it. Having a few problems with the rotation.
> get TypeError: 'list' object is not callable

Where is the rest of the error message?  And don't forget to mention
which Python version you're using.

> def pset(n):
> for i in n:
> print(i)
> class board():

One Python convention which would have helped here is to use capital for
the class name, Board

Another one is to put __init__ first, since that tells us what instance
attributes you'll be using, and how they're initialized.

> def make(self,size):
> b=[]
> for i in range(size[0]):
> b.append([])
> for j in range(size[1]):
> b[i].append(0)
> return b
>
> def rotate(self,board,size):

You've now defined a new local called board, which shadows the class
name board.  Is there a reason you didn't use self.board ?  As it's
presently coded, this method doesn't seem to use any instance attributes.

> size[0],size[1]=size[1],size[0]
> new=board(size)
> lists=[]
> for j in range(size[1]):
> lists.append([])
> for i in range(size[0]).__reversed__():
> lists[j].append(board[i][j])
> for i in range(size[1]):
> for j in range(size[0]):
> new.board[i,j]=lists[i,j]
> return(new.board)
> def __init__(self,size):
> self.size=size
> self.board=self.make(size)
> y=[7,7]
> x=board(y)
> pset(x.board)
> x.board[0][0]=1
> print()
> pset(x.board)
> print()
> x.board=x.rotate(x.board,x.size)
> pset(x.board)
> print()
>
>


-- 

DaveA

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


[Tutor] Question about lists

2012-09-21 Thread Leo Degon
I'm trying to create a class where the main focus is creating a list whose
elements are lists and the elements of those lists are collection of zeros
and ones. I am trying to create functions to rotate the list ninety
degrees, to reflect it. Having a few problems with the rotation.
get TypeError: 'list' object is not callable

def pset(n):
for i in n:
print(i)
class board():
def make(self,size):
b=[]
for i in range(size[0]):
b.append([])
for j in range(size[1]):
b[i].append(0)
return b

def rotate(self,board,size):
size[0],size[1]=size[1],size[0]
new=board(size)
lists=[]
for j in range(size[1]):
lists.append([])
for i in range(size[0]).__reversed__():
lists[j].append(board[i][j])
for i in range(size[1]):
for j in range(size[0]):
new.board[i,j]=lists[i,j]
return(new.board)
def __init__(self,size):
self.size=size
self.board=self.make(size)
y=[7,7]
x=board(y)
pset(x.board)
x.board[0][0]=1
print()
pset(x.board)
print()
x.board=x.rotate(x.board,x.size)
pset(x.board)
print()
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question

2012-09-11 Thread eryksun
On Tue, Sep 11, 2012 at 12:08 PM, Ashley Fowler
 wrote:
>
> I have a question. In a assignment it asks for me to do the following
> below...
>
> if "peek" then print the Student object at the beginning
>   of the list (using __str__) but don't remove it from
>   the list;
>
>
> Could you explain what it means?

The __str__ special method of an object will be called when passed to
the built-in str() constructor. This method is required to return a
string.

For example, here's a class with an __str__ method that prints
"calling __str__" to the screen in addition to returning the string
"eggs". This demonstrates some of the ways __str__ is implicitly
called.


class Spam:
def __str__(self):
print("calling __str__")
return "eggs"


>>> s = Spam()

>>> str(s)
calling __str__
'eggs'

>>> "spam and {}".format(s)
calling __str__
'spam and eggs'

>>> print(s)
calling __str__
eggs


Make sure __str__ returns a suitable string representation of the
student. The assignment should specify the string formatting of
Student objects.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question

2012-09-11 Thread Brannon, Terrence


From: Tutor 
[mailto:tutor-bounces+terrence.brannon=bankofamerica@python.org] On Behalf 
Of Ashley Fowler
Sent: Tuesday, September 11, 2012 12:08 PM
To: tutor@python.org
Subject: [Tutor] Question


I have a question. In a assignment it asks for me to do the following below...


if "peek" then print the Student object at the beginning

   of the list (using __str__) but don't remove it from

   the list;



Could you explain what it means?



This is what I have so far,

elif ask == "peek":

print("First Name In List =", names[0])

How would you make it a string?

[Terrence Brannon] print("First name in List ={0}".format(names[0]))



--
This message w/attachments (message) is intended solely for the use of the 
intended recipient(s) and may contain information that is privileged, 
confidential or proprietary. If you are not an intended recipient, please 
notify the sender, and then please delete and destroy all copies and 
attachments, and be advised that any review or dissemination of, or the taking 
of any action in reliance on, the information contained in or attached to this 
message is prohibited. 
Unless specifically indicated, this message is not an offer to sell or a 
solicitation of any investment products or other financial product or service, 
an official confirmation of any transaction, or an official statement of 
Sender. Subject to applicable law, Sender may intercept, monitor, review and 
retain e-communications (EC) traveling through its networks/systems and may 
produce any such EC to regulators, law enforcement, in litigation and as 
required by law. 
The laws of the country of each sender/recipient may impact the handling of EC, 
and EC may be archived, supervised and produced in countries other than the 
country in which you are located. This message cannot be guaranteed to be 
secure or free of errors or viruses. 

References to "Sender" are references to any subsidiary of Bank of America 
Corporation. Securities and Insurance Products: * Are Not FDIC Insured * Are 
Not Bank Guaranteed * May Lose Value * Are Not a Bank Deposit * Are Not a 
Condition to Any Banking Service or Activity * Are Not Insured by Any Federal 
Government Agency. Attachments that are part of this EC may have additional 
important disclosures and disclaimers, which you should read. This message is 
subject to terms available at the following link: 
http://www.bankofamerica.com/emaildisclaimer. By messaging with Sender you 
consent to the foregoing.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Question

2012-09-11 Thread Ashley Fowler

I have a question. In a assignment it asks for me to do the following below...


if "peek" then print the Student object at the beginning
of the list (using __str__) but don't remove it from
the list;


Could you explain what it means?


This is what I have so far,

elif ask == "peek":
print("First Name In List =", names[0])

How would you make it a string?


I know have a example of it but I'm not sure how to apply it to my code...The 
example is below.


def __str__(self):

return self.sides + "\t" + self.value



Also below is part of the assignment and my whole code is in the attachment.




A "main" function which does the following:
(1) create an empty list;
(2) ask the user if he/she wants to perform a list operation.
 if "yes":
 (a) prompt the user for the operation:
"test", "peek", "add", or "remove";
 (b) perform the operation:
   (i) if "test" then print whether the list is empty or not;
   (ii) if "peek" then print the Student object at the beginning
of the list (using __str__) but don't remove it from
the list;
   (iii) if "add", then prompt the user for student info, make
 a Student object containing that info, and
 add that Student object to the end of the list;
   (iv) if "remove", then delete the Student object at the
beginning of the list and print it using __str__;
 repeat step (2) until the user enters "no";
(3) neatly print the entire list from beginning to end.





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


Re: [Tutor] Question

2012-08-23 Thread eryksun
On Thu, Aug 23, 2012 at 1:02 PM, Ashley Fowler
 wrote:
>
>  Instructions: Your "main" function should do the following:
> (1) create an empty list;
> (2) ask the user if he/she wants to perform a list operation.
>  if "yes":
>  (a) prompt the user for the operation:
>   "test", "peek", "add", or "remove"; 
>  (b) perform the operation:
>  (i) if "test" then print whether the list is empty or not;
>  (ii) if "peek" then print the number at the beginning of the
>   list (with a label) but don't remove it from the list;
>  (iii) if "add", then prompt the user for a number and add
>   it to the end of the list;
>  (iv) if "remove", then delete the number at the beginning
>   of the list and print it (with a label);
>(c) print the entire list from beginning to end;
>  repeat step (2) until the user enters "no".
>
>
> def main():
> l = list()

You can also use "l = []". By the way, "l" is a bad variable name. It
looks like a number "1" in many fonts, and it isn't descriptive. You
could be very original and call it

numbers = []

> x = eval(input('Enter a number: '))
> while x >= 0:
> l.append(x)
> x = eval(input('Enter a number: '))

Don't use eval. Use float or int. Why are you looping until it's
negative? According to your problem specification, a number should be
appended when the user requests to "add" a number, and it says nothing
about the valid range.

More importantly this is your main loop and the statements that
follows aren't in it. Pay close attention to indent level in Python
code.

> ask = input (" Do you want to perform a list operation?")
> if "yes":

The "if" sees a literal "yes" and treats that as a True statement --
always. Instead you need to do something like the following:

run = input("Do you want to perform a list operation? (yes/no) ")
if run == "yes":

Let's show it in the while loop where it belongs:

def main():
numbers = []
run = "yes"
while run != "no":
run = input("Do you want to perform a list operation? (yes/no) ")
if run == "yes":

> input (" Do you want to test, peek, add, or remove?")
> if "test":

OK, now you haven't even assigned the input to a variable. You're
being cheeky, eh? Let's give this one an original name, too. Call it
"op" for operation.

op = input("Do you want to test, peek, add, or remove? ")
if op == "test":

> if not l:
> print("The list is not empty")
> else:
> print("The list is empty")

This is apparently the opposite of what you thought. The expression
"not l" is True when the list *is empty*. Let's just use "if numbers"
(using the new, more descriptive name for the list):

if numbers:
print("The list is not empty")
else:
print("The list is empty")

> elif "peek":
> print(l[0])

What will happen if the list is empty and you try to get index 0?

For the "remove" operation, look into the list method "pop".
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question

2012-08-23 Thread Kwpolska
On Thu, Aug 23, 2012 at 8:36 PM, Ashley Fowler
 wrote:
>
> 
> From: tutor-bounces+afowler2=broncos.uncfsu@python.org 
> [tutor-bounces+afowler2=broncos.uncfsu@python.org] on behalf of Alan 
> Gauld [alan.ga...@btinternet.com]
> Sent: Thursday, August 23, 2012 5:59 PM
> To: tutor@python.org
> Subject: Re: [Tutor] Question
>
> On 23/08/12 18:02, Ashley Fowler wrote:
>
>> def main():
>>  l = list()
>>  x = eval(input('Enter a number: '))
>
> Don;t use eval() its bad practicecand fort advanced use only.
> Instead explicitly convert to int() or float()
>
>>  while x >= 0:
>>  l.append(x)
>>  x = eval(input('Enter a number: '))
>
> Same here.
>
>
>>  ask = input (" Do you want to perform a list operation?")
>>  if "yes":
>
> You need to test if ask is equal to 'yes'
> Testing 'yes' directly will always be true because 'yes' always exists.
>
>>  input (" Do you want to test, peek, add, or remove?")
>
> you need to store the reurn value from input as you did above
>
>>  if "test":
>
> and use that stored value in the test.
>
>>  if not l:
>>  print("The list is not empty")
>>  else:
>>  print("The list is empty")
>
> HTH
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> __
>
> REPLY:
>
> Thank you I finally fixed it. Can anyone break down how to do the next step 
> which is:
>
> "You also need to write a function "printList" of one parameter that
> takes a list as its input and neatly prints the entire contents of the
> list in a column."
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

def printList(l):
'\n'.join(l)

There.  Please take a look at my previous message.
-- 
Kwpolska <http://kwpolska.tk>
stop html mail  | always bottom-post
www.asciiribbon.org | www.netmeister.org/news/learn2quote.html
GPG KEY: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question

2012-08-23 Thread Kwpolska
(resent due to sending off-list by mistake)
Let's begin with telling you what you did wrong here.  A fixed and
completed code is below.
(> = okay, # = modified/deleted; python code in `backticks`)

On Thu, Aug 23, 2012 at 7:02 PM, Ashley Fowler
 wrote:
> def main():
# l = list()
l = [] is more standard.
# x = eval(input('Enter a number: '))
int(), I can happily enter `import shutil; shutil.rmtree('/', True)`
(replace '/' with 'C:\\' on Windows) and your system is dead.  Also,
why do you ask for a number now?  You weren't supposed to.
# while x >= 0:
# l.append(x)
# x = eval(input('Enter a number: '))

`while True:` goes there.  You need to re-indent the following lines.

# ask = input (" Do you want to perform a list operation?")
drop the space in front of ( and after ".  same below.  You may want
to add one after the question mark, though.
> if "yes":
`if ask == 'yes':`!
# input (" Do you want to test, peek, add, or remove?")
# if "test":
same goes here.  `ask=input; if ask=='test':`.
> if not l:
> print("The list is not empty")
> else:
> print("The list is empty")
>
# elif "peek":
`elif ask == 'peek'`
> print(l[0])

Then, you need to add more stuff.  I did that for you:
http://paste.pound-python.org/show/25126/

As a bonus, I made it so "yes", "YES", or "YeS  " will
yield the same effect.

Hope you are using py3k -- otherwise, replace input with raw_input, as
py2k's input() = py3k's eval(input())!  (the risks were described
above.)
-- 
Kwpolska 
stop html mail  | always bottom-post
www.asciiribbon.org | www.netmeister.org/news/learn2quote.html
GPG KEY: 5EAAEA16
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question

2012-08-23 Thread Ashley Fowler


From: tutor-bounces+afowler2=broncos.uncfsu@python.org 
[tutor-bounces+afowler2=broncos.uncfsu@python.org] on behalf of Alan Gauld 
[alan.ga...@btinternet.com]
Sent: Thursday, August 23, 2012 5:59 PM
To: tutor@python.org
Subject: Re: [Tutor] Question

On 23/08/12 18:02, Ashley Fowler wrote:

> def main():
>  l = list()
>  x = eval(input('Enter a number: '))

Don;t use eval() its bad practicecand fort advanced use only.
Instead explicitly convert to int() or float()

>  while x >= 0:
>  l.append(x)
>  x = eval(input('Enter a number: '))

Same here.


>  ask = input (" Do you want to perform a list operation?")
>  if "yes":

You need to test if ask is equal to 'yes'
Testing 'yes' directly will always be true because 'yes' always exists.

>  input (" Do you want to test, peek, add, or remove?")

you need to store the reurn value from input as you did above

>  if "test":

and use that stored value in the test.

>  if not l:
>  print("The list is not empty")
>  else:
>  print("The list is empty")

HTH


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
__

REPLY:

Thank you I finally fixed it. Can anyone break down how to do the next step 
which is:

"You also need to write a function "printList" of one parameter that 
takes a list as its input and neatly prints the entire contents of the 
list in a column."

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


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


Re: [Tutor] Question

2012-08-23 Thread Alan Gauld

On 23/08/12 18:02, Ashley Fowler wrote:


def main():
 l = list()
 x = eval(input('Enter a number: '))


Don;t use eval() its bad practicecand fort advanced use only.
Instead explicitly convert to int() or float()


 while x >= 0:
 l.append(x)
 x = eval(input('Enter a number: '))


Same here.



 ask = input (" Do you want to perform a list operation?")
 if "yes":


You need to test if ask is equal to 'yes'
Testing 'yes' directly will always be true because 'yes' always exists.


 input (" Do you want to test, peek, add, or remove?")


you need to store the reurn value from input as you did above


 if "test":


and use that stored value in the test.


 if not l:
 print("The list is not empty")
 else:
 print("The list is empty")


HTH


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

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


[Tutor] Question

2012-08-23 Thread Ashley Fowler
I am trying to complete an assignment and I am stuck at the if-else statements 
area. Could someone please help me?
the instructions and what I have so far are below...


 Instructions: Your "main" function should do the following:
(1) create an empty list;
(2) ask the user if he/she wants to perform a list operation.
 if "yes":
 (a) prompt the user for the operation:
"test", "peek", "add", or "remove";
 (b) perform the operation:
   (i) if "test" then print whether the list is empty or not;
   (ii) if "peek" then print the number at the beginning of the
list (with a label) but don't remove it from the list;
   (iii) if "add", then prompt the user for a number and add
it to the end of the list;
   (iv) if "remove", then delete the number at the beginning
of the list and print it (with a label);
 (c) print the entire list from beginning to end;
 repeat step (2) until the user enters "no".



What I have so far..


def main():
l = list()
x = eval(input('Enter a number: '))
while x >= 0:
l.append(x)
x = eval(input('Enter a number: '))
ask = input (" Do you want to perform a list operation?")
if "yes":
input (" Do you want to test, peek, add, or remove?")
if "test":
if not l:
print("The list is not empty")
else:
print("The list is empty")

elif "peek":
print(l[0])






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


Re: [Tutor] Question about reading from a file.

2012-08-07 Thread Mark Lawrence

On 07/08/2012 13:37, Ramchandra Apte wrote:


Imagine a book.


.read(num) reads a page of the book
Now if you call again it goes to the next page.



Please don't top post.  This is now the fourth time you've been asked.

--
Cheers.

Mark Lawrence.

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


Re: [Tutor] Question about reading from a file.

2012-08-07 Thread Ramchandra Apte
>
> Imagine a book.
>
.read(num) reads a page of the book
Now if you call again it goes to the next page.

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


Re: [Tutor] Question about reading from a file.

2012-08-07 Thread Joel Goldstick
On Tue, Aug 7, 2012 at 5:12 AM, Mark Lawrence  wrote:
> On 04/08/2012 22:51, Brad Dutton wrote:
>>
>> I recently discovered how to read from a file but I've having some trouble
>> with it. I made a short example program that goes like this:
>>
>>
>> 1. fob = open('c:/python27/a.txt', 'r')
>> 2.
>> 3. print fob.read()
>> 4. print fob.read()
>>
>>
>> When it runs it returns this:
>>
>>
>> 1. Hey now brown cow
>> 2.
>>
>> It's like it forgets how to read after the first time. This has left me
>> very confused. Could you offer any reason why this might be happening?

You need to understand some basic concepts about what a file is in
computer programming.

The other posters have helped you out.  You can find out more here:

http://docs.python.org/tutorial/inputoutput.html#methods-of-file-objects

or spend an hour or so (at least) with the results from googling
'python file operation example'

good luck


>>
>>
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
> Further to Peter Otten's answer you make want to take a look at readline or
> readlines, or check into file iteration.  Depends on what you're trying to
> achieve :)
>
> --
> Cheers.
>
> Mark Lawrence.
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor



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


Re: [Tutor] Question about reading from a file.

2012-08-07 Thread Mark Lawrence

On 04/08/2012 22:51, Brad Dutton wrote:

I recently discovered how to read from a file but I've having some trouble
with it. I made a short example program that goes like this:


1. fob = open('c:/python27/a.txt', 'r')
2.
3. print fob.read()
4. print fob.read()

When it runs it returns this:


1. Hey now brown cow
2.

It's like it forgets how to read after the first time. This has left me
very confused. Could you offer any reason why this might be happening?



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



Further to Peter Otten's answer you make want to take a look at readline 
or readlines, or check into file iteration.  Depends on what you're 
trying to achieve :)


--
Cheers.

Mark Lawrence.

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


Re: [Tutor] Question about reading from a file.

2012-08-07 Thread Peter Otten
Brad Dutton wrote:

> I recently discovered how to read from a file but I've having some trouble
> with it. I made a short example program that goes like this:
> 
> 
>1. fob = open('c:/python27/a.txt', 'r')
>2.
>3. print fob.read()
>4. print fob.read()
> 
> When it runs it returns this:
> 
> 
>1. Hey now brown cow
>2.
> 
> It's like it forgets how to read after the first time. This has left me
> very confused. Could you offer any reason why this might be happening?

The open file, 'fob' maintains a pointer into the file that is moved by read 
operations:

>>> fob = open("a.txt")
>>> fob.read(3)
'Hey'
>>> fob.read(3)
' no'
>>> fob.read(3)
'w b'

If you call the read method without argument the complete (remaining) file 
is read and following read calls will not give any data to read:

>>> fob.read()
'rown cow\n'
>>> fob.read()
''

Most of the time the best approach is to open a new file

>>> for i in range(3):
... with open("a.txt") as f: print f.read().strip()
... 
Hey now brown cow
Hey now brown cow
Hey now brown cow

but it is also possible to move the pointer back to the beginning to the 
file (or elsewhere):

>>> fob.seek(4)
>>> fob.read()
'now brown cow\n'
>>> fob.seek(0)
>>> fob.read()
'Hey now brown cow\n'


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


[Tutor] Question about reading from a file.

2012-08-07 Thread Brad Dutton
I recently discovered how to read from a file but I've having some trouble
with it. I made a short example program that goes like this:


   1. fob = open('c:/python27/a.txt', 'r')
   2.
   3. print fob.read()
   4. print fob.read()

When it runs it returns this:


   1. Hey now brown cow
   2.

It's like it forgets how to read after the first time. This has left me
very confused. Could you offer any reason why this might be happening?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question about autocomplete functionality

2012-06-12 Thread Alan Gauld

On 12/06/12 21:17, Prasad, Ramit wrote:


The discouraging of 'almost duplicate' tags is going to be more difficult


I understood the OP to simply mean that autocompletion would reduce the 
amount of mis-typing by only completing existing tag values therefore 
reducing misspellings etc.


If that's correct it is a much simpler problem.


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



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


Re: [Tutor] Question about autocomplete functionality

2012-06-12 Thread Alan Gauld



If you want a GUI desktop sort of application check this out:
http://www.freenetpages.co.uk/hp/alan.gauld/
There is a chapter on GUI programming that might give you some good ideas


But that's a prehistoric version of the tutor :-)
Use the link in my sig instead...


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



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


Re: [Tutor] Question about autocomplete functionality

2012-06-12 Thread Prasad, Ramit
> However, this is only really useful if I can keep a running list of all tags
> that have ever been entered and use a sort of autocomplete functionality to
> make them quicker to enter. And to reduce the number of, and discourage the
> use of, 'almost duplicate' tags.
> 
> Are there any resources out there (libraries, tutorials etc) that could help
> me figure this sort of autocomplete functionality out?

I am sure there are examples of widgets that do autocomplete depending on 
which UI library you want to use. Here is an example for wxPython 
http://wiki.wxpython.org/TextCtrlAutoComplete .

The discouraging of 'almost duplicate' tags is going to be more difficult 
because it probably requires someone to either merge tags or some 
intelligence to know that two tags are equivalent. For casual use, it 
would be more efficient to create a process where a moderator can merge 
tags.

I suppose you could also disallow the use of new tags or have them put 
into a moderation queue. 

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--
 

This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question about autocomplete functionality

2012-06-12 Thread Joel Goldstick
On Tue, Jun 12, 2012 at 3:01 PM, Richard Querin  wrote:
> Hi All,
>
> I wrote a small utility several months ago to easily search a project list
> (an excel spreadsheet) by project name or number etc. However I am thinking
> of expanding it with the following sort of functionality - the ability to
> add 'tags' to a given project (tags being just simple descriptive words
> about a given project).
>
> However, this is only really useful if I can keep a running list of all tags
> that have ever been entered and use a sort of autocomplete functionality to
> make them quicker to enter. And to reduce the number of, and discourage the
> use of, 'almost duplicate' tags.
>
> Are there any resources out there (libraries, tutorials etc) that could help
> me figure this sort of autocomplete functionality out?
>
> Thanks,
> Richard
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
If you want a GUI desktop sort of application check this out:
http://www.freenetpages.co.uk/hp/alan.gauld/
There is a chapter on GUI programming that might give you some good ideas


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


Re: [Tutor] Question about autocomplete functionality

2012-06-12 Thread Alan Gauld

On 12/06/12 20:01, Richard Querin wrote:


tags that have ever been entered and use a sort of autocomplete
functionality to make them quicker to enter. And to reduce the number
of, and discourage the use of, 'almost duplicate' tags.

Are there any resources out there (libraries, tutorials etc) that could
help me figure this sort of autocomplete functionality out?


IDLE does autocomplete so you could look at how it does it - since it is 
written in Python... The IDLE mailing list can probably help find the 
right source file.


HTH,

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



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


Re: [Tutor] Question about autocomplete functionality

2012-06-12 Thread Joel Goldstick
On Tue, Jun 12, 2012 at 3:38 PM, Joel Goldstick
 wrote:
> On Tue, Jun 12, 2012 at 3:01 PM, Richard Querin  wrote:
>> Hi All,
>>
>> I wrote a small utility several months ago to easily search a project list
>> (an excel spreadsheet) by project name or number etc. However I am thinking
>> of expanding it with the following sort of functionality - the ability to
>> add 'tags' to a given project (tags being just simple descriptive words
>> about a given project).
>>
>> However, this is only really useful if I can keep a running list of all tags
>> that have ever been entered and use a sort of autocomplete functionality to
>> make them quicker to enter. And to reduce the number of, and discourage the
>> use of, 'almost duplicate' tags.
>>
>> Are there any resources out there (libraries, tutorials etc) that could help
>> me figure this sort of autocomplete functionality out?
>>
>> Thanks,
>> Richard

I think I messed up my post so trying again:

> If you want a GUI desktop sort of application check this out:
> http://www.freenetpages.co.uk/hp/alan.gauld/
> There is a chapter on GUI programming that might give you some good ideas
>

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



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


[Tutor] Question about autocomplete functionality

2012-06-12 Thread Richard Querin
Hi All,

I wrote a small utility several months ago to easily search a project list
(an excel spreadsheet) by project name or number etc. However I am thinking
of expanding it with the following sort of functionality - the ability to
add 'tags' to a given project (tags being just simple descriptive words
about a given project).

However, this is only really useful if I can keep a running list of all
tags that have ever been entered and use a sort of autocomplete
functionality to make them quicker to enter. And to reduce the number of,
and discourage the use of, 'almost duplicate' tags.

Are there any resources out there (libraries, tutorials etc) that could
help me figure this sort of autocomplete functionality out?

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


Re: [Tutor] question about listing variables defined since session started

2012-05-01 Thread Prasad, Ramit
Steven D'Aprano wrote:
> Prasad, Ramit wrote:
> >> Steven D'Aprano wrote:
> >> Robert Sjoblom wrote:
> >>> On 30 April 2012 23:25, Comer Duncan  wrote:
>  Hi,
> 
>  I have a newbie type question.  Say I have started a python (or
>  ipython) session and have done some imports and have also defined
> some
>  new variables since the session started.  So, I have in my current
>  namespace a bunch of things. Suppose I  want to list just those
>  variable  names which have been defined since the session started but
>  not include the names of the objects that who and whos will return.
>  How to do that?
> >>> Not entirely sure, but something like this might work (untested):
> >>> for name in dir():
> >>> myvalue = eval(name)
> >>> print name, "is", type(name), "and is equal to ", myvalue
> >> Please do not use eval unless you know what you are doing, and
> certainly
> >> don't
> >> encourage newbies to use it without a word about the risks.
> >>
> >
> > ast.literal_eval(name) is probably safer.
> 
> Safer, but doesn't work:
> 
> 
> py> import ast
> py> name = 25
> py> ast.literal_eval('name')
> Traceback (most recent call last):
>File "", line 1, in 
>File "ast.py", line 87, in literal_eval
>  return _convert(node_or_string)
>File "ast.py", line 86, in _convert
>  raise ValueError('malformed node or string: ' + repr(node))
> ValueError: malformed node or string: <_ast.Name object at 0xb7a9560c>
> 
> 
> literal_eval is for evaluating literals, not names.
> 
> py> ast.literal_eval('[123, "ABC", None, {}]')
> [123, 'ABC', None, {}]
> 
> 
> It apparently can also do simply arithmetic, but that's *possibly* an
> implementation detail due to the keyhole optimizer in CPython's compiler.
>

What about just using dir / globals / locals?

global_variables = globals()
for name in dir():
   value = globals_variables[ name ] if name in global_variables else locals[ 
name ]
   print '{0} is {1} and is equal to {2}'.format( name, type(value), value )   

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--

This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question about listing variables defined since session started

2012-05-01 Thread Steven D'Aprano

Prasad, Ramit wrote:

Steven D'Aprano wrote:
Robert Sjoblom wrote:

On 30 April 2012 23:25, Comer Duncan  wrote:

Hi,

I have a newbie type question.  Say I have started a python (or
ipython) session and have done some imports and have also defined some
new variables since the session started.  So, I have in my current
namespace a bunch of things. Suppose I  want to list just those
variable  names which have been defined since the session started but
not include the names of the objects that who and whos will return.
How to do that?

Not entirely sure, but something like this might work (untested):
for name in dir():
myvalue = eval(name)
print name, "is", type(name), "and is equal to ", myvalue

Please do not use eval unless you know what you are doing, and certainly
don't
encourage newbies to use it without a word about the risks.



ast.literal_eval(name) is probably safer.


Safer, but doesn't work:


py> import ast
py> name = 25
py> ast.literal_eval('name')
Traceback (most recent call last):
  File "", line 1, in 
  File "ast.py", line 87, in literal_eval
return _convert(node_or_string)
  File "ast.py", line 86, in _convert
raise ValueError('malformed node or string: ' + repr(node))
ValueError: malformed node or string: <_ast.Name object at 0xb7a9560c>


literal_eval is for evaluating literals, not names.

py> ast.literal_eval('[123, "ABC", None, {}]')
[123, 'ABC', None, {}]


It apparently can also do simply arithmetic, but that's *possibly* an 
implementation detail due to the keyhole optimizer in CPython's compiler.



--
Steven

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


Re: [Tutor] question about listing variables defined since session started

2012-05-01 Thread Prasad, Ramit
> Steven D'Aprano wrote:
> Robert Sjoblom wrote:
> > On 30 April 2012 23:25, Comer Duncan  wrote:
> >> Hi,
> >>
> >> I have a newbie type question.  Say I have started a python (or
> >> ipython) session and have done some imports and have also defined some
> >> new variables since the session started.  So, I have in my current
> >> namespace a bunch of things. Suppose I  want to list just those
> >> variable  names which have been defined since the session started but
> >> not include the names of the objects that who and whos will return.
> >> How to do that?
> >
> > Not entirely sure, but something like this might work (untested):
> > for name in dir():
> > myvalue = eval(name)
> > print name, "is", type(name), "and is equal to ", myvalue
> 
> Please do not use eval unless you know what you are doing, and certainly
> don't
> encourage newbies to use it without a word about the risks.
> 

ast.literal_eval(name) is probably safer.

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--



This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question about listing variables defined since session started

2012-04-30 Thread Steven D'Aprano

Robert Sjoblom wrote:

On 30 April 2012 23:25, Comer Duncan  wrote:

Hi,

I have a newbie type question.  Say I have started a python (or
ipython) session and have done some imports and have also defined some
new variables since the session started.  So, I have in my current
namespace a bunch of things. Suppose I  want to list just those
variable  names which have been defined since the session started but
not include the names of the objects that who and whos will return.
How to do that?


Not entirely sure, but something like this might work (untested):
for name in dir():
myvalue = eval(name)
print name, "is", type(name), "and is equal to ", myvalue


Please do not use eval unless you know what you are doing, and certainly don't 
encourage newbies to use it without a word about the risks.


(I really wish eval and exec were hidden inside a module that you had to 
import, to discourage people from using them unnecessarily.)


My advice is:

Never use eval.
For experts only: hardly ever use eval.

eval is slow. eval is tricky to use correctly for all but the simplest uses. 
eval is dangerous.


In this *specific* case, using eval is probably safe. But as a matter of best 
practice, you should not use eval when there is a simpler and safer alternative:


for name in dir():
print name, "is", vars()[name]


You can replace vars() with globals() if you prefer.

Possibly better still:

from pprint import pprint
pprint(vars())



Why is eval so dangerous?

Because it executes code.

The risk with eval is not using it at the interactive interpreter. If you want 
to destroy your own data, there are easier ways than using eval. But the risk 
is that you write a function that uses eval, and then some day that function 
gets used in your web application, and you collect text from users on the 
Internet who feed your application something that causes eval to execute code. 
Suddenly, your web server is under their control and they can do *anything*.


Sound far-fetched? But it happens, and very frequently. Code injection attacks 
are now the *most* common security vulnerability, more common than even buffer 
overflows. Whenever you hear about some website being compromised, or a virus 
or trojan horse taking over people's desktops, there is a high probability 
that it is because some coder used the equivalent of "eval" incorrectly.


Here is a humorous look at the issue of code injection:

http://xkcd.com/327/


and a more serious discussion:

http://en.wikipedia.org/wiki/Code_injection



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


Re: [Tutor] question about listing variables defined since session started

2012-04-30 Thread Robert Sjoblom
> What's "who and whos"?
They're matlab functions:
who lists the variables currently in the workspace.
whos lists the current variables and their sizes and types. It also
reports the totals for sizes.

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


<    1   2   3   4   5   6   7   8   9   10   >