Re: [Tutor] List of ints

2015-03-02 Thread Mark Lawrence

On 03/03/2015 06:50, Phil wrote:

Thank you for reading this.
Python 3 under Linux.

I'd like to set up a two dimensional list of counters as follows;

count = [
 [0],
 [0],
 [0]
 ]

And then increment the first counter as follows;

count [0] += 1

This fails with the following error;

TypeError: 'int' object is not iterable

The array module looks like the answer because it seems to function in
the same way as an array under C. However, it seems to me that I should
be able to do the same thing with a list.

Is there a way to add a value to a list of ints?



You are trying to increment the first element of count which is itself a 
list containing one element.  You actually need:-


count[0][0] +=1

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


[Tutor] List of ints

2015-03-02 Thread Phil

Thank you for reading this.
Python 3 under Linux.

I'd like to set up a two dimensional list of counters as follows;

count = [
[0],
[0],
[0]
]

And then increment the first counter as follows;

count [0] += 1

This fails with the following error;

TypeError: 'int' object is not iterable

The array module looks like the answer because it seems to function in 
the same way as an array under C. However, it seems to me that I should 
be able to do the same thing with a list.


Is there a way to add a value to a list of ints?

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


Re: [Tutor] text file help

2015-03-02 Thread Alan Gauld

Forwarding to list too.

On 02/03/15 19:04, Tihomir Zjajic wrote:

kl_number = []
myfile = open("formular_doznake.txt")
for line in "formular_doznake":


Note that you want to iterate over the file not the name of the file.
The code above sets line to each character in the file name.

You want to set it to each line in the file so it should look like:

myfile = open("formular_doznake.txt")
for line in myfile:


or just

for line in open("formular_doznake.txt") :


   if line.startswith('1'):
   num = makeNumber(next[vrs_drv], next[prs_prec], next[teh_kl])
   kl_number.append(num)

def makeNumber(l1,l2,l3):
   nums = []
   for line in(vrs_drv,prs_prec,teh_kl):
   nums.append(line.rstrip().split()[-1])
   return ".join(nums)"
print(next(myfile)+next(myfile)+next(myfile))
print(kl_number)

> sorry, but this doesn't work !

Always try to be specific. Say what doesn't work about it and
include any error messages.

The hint above may help however.


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
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] Use python to parse the subject line of emails, listen for and react to commands

2015-03-02 Thread Danny Yoo
Hi Willie,

Ok, spent a few minutes looking over the code.

I'll spend a brief moment reviewing the following block:

> msg = email.message_from_string(data[0][1])
> decode = email.header.decode_header(msg['Subject'])[0]
> subject = unicode(decode[0])
> print '%s' % (subject)
> COMMAND_FILE.write('%s' % (subject)+'.py')
> COMMAND_FILE.close()
> EX = '%s' %(subject)+'.py' #save the subject as an name.py
> execfile (EX) # exe name as a py


1.  Do you have a complete list of all the command files you're planning to use?


2.  The use of string formatting here might be redundant.  Instead of:

print '%s' % (subject)

since we know subject is a unicode string, can we just say:

print subject


3.  Similar comment on the line:

COMMAND_FILE.write('%s' % (subject)+'.py')

but somewhat different.  If you're doing string formatting, be
consistent: do it so we can see the shape of the final string by
looking at the string literal alone.   Here, the concatenation of
'.py' is apart from the string literal.  It should be together.

COMMAND_FILE.write('%s.py' % (subject))

My comment here, though, might be overridden by the recommendation to
avoid use of unrestricted execfile in favor of a closed approach.


4.  If you have a closed set of command names, then you can do
something significantly safer here.  Concretely, let's say that you
have the following three commands:

"open", "reply", "ping"

I'm just making these up so that we have something concrete to talk about.


Let us assume that we have, corresponding to these command names, the
three modules: "open_command.py", "reply_command.py" and
"ping_command.py".


But unlike what you probably have now, let's say that each of these
modules defines a run() function.

#
## open.py
def run():
print "This is open."


## reply.py
def run():
print "This is reply."


## ping.py
def run():
print "This is ping."
#


If we have this organization, then in your main command driver, you
can safely construct a mapping from command name to the appropriate
run() function:


import open_command
import reply_command
import ping_command


COMMANDS = {
u'open' : open_command.run,
u'reply' : reply_command.run,
u'ping' : ping_command.run,
}


# ... later in your program ...
def process_mailbox(M):
# ...

msg = email.message_from_string(data[0][1])
decode = email.header.decode_header(msg['Subject'])[0]
subject = unicode(decode[0])

## here's where things are slightly different:
command = COMMANDS[subject]
command()
#


There are a few things to note there:

1.  This approach is much safer because we know that the only commands
that can be run are listed in COMMANDS.  It's a lot more constrained
in what it can do.

2.  It's also robust in the face of changes to the current directory.
If your current directory is somewhere where you can't write, that has
no effect whatsover with this revision.  The original approach can
suffer from mysterious failure possibilities because it implicitly
depends on the "global" current working directory.

3.  Other folks will better understand what's going on: this
command-dispatching pattern is used quite often.  For example, see:


https://docs.python.org/2/faq/design.html#why-isn-t-there-a-switch-or-case-statement-in-python


There are also some guaranteed low-level efficiency bonuses if we take
this approach.  But those are ancillary when we compare vs the safety
guarantees we'll get if we avoid exec or execfile approaches.


If you have questions about this, please ask, and hopefully someone
here can help explain further and point to resources.  Good luck!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Use python to parse the subject line of emails, listen for and react to commands

2015-03-02 Thread Danny Yoo
> The code is not pretty and I have no doubt that there are thousands of ways 
> for it to be hacked or messed up since there is little to no error checking 
> in it. I don’t know enough to do so yet sorry I am doing the best I can and 
> have only started learning python a week ago.


Yikes!  My apologies for my alarmed tone.

Panic is not a good way to get people to think clearly.  I may have to
rethink the way that I personally warn people away from eval().  The
way that I've been doing it now has bad side effects in terms of
sounding like personal criticism.  :(  That is, the technical content
story might be getting overshadowed by the personal criticism story if
I'm not careful.   I will think about this more.



As a brief comment about your program: execfile might be ok.  I
haven't taken a close look at your program yet.  If I have more time,
I'll take a closer look, and hopefully others on the mailing list can
also contribute.

Do make sure you get eyes to look at your program; getting security
right is hard, and I think it takes a village to learn how to program
well.


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


Re: [Tutor] What exactly is "state"?

2015-03-02 Thread Dave Angel

On 03/02/2015 01:42 PM, Sydney Shall wrote:


Thank you very much, Joel, Danny, Alan and Dave.
Your explanations are all very clear and very enlightening.
I shall have to change several of my unittests now. In good time.
I am particularly pleased with the examples; they clarify matters
considerably for me.

Out of subject, I wonder from this exchange whether teaching should not
always involve at least several teachers. Your replies are very
complimentary!



Your reply was very complimentary, our replies were complementary. 
Notice the e instead of the i.


Yes, multiple teachers is frequently useful.  When I was in college, 
many classes had both a professor (lecturer) and assistant professors 
(or teaching assistants, or ...).  One lecture in a big hall, one 
relatively small class where you could more easily interact.  I found 
the two different viewpoints useful, though sometimes the leaders of the 
small class were almost afraid to challenge the full prof.


I also advocated a dual-manager role in one company.  Idea didn't 
formally go anywhere, but I did manage to escape from management -- went 
from 50 people to 1, and a promotion at the same time.



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


Re: [Tutor] What exactly is "state"?

2015-03-02 Thread Sydney Shall

On 02/03/2015 18:03, Dave Angel wrote:

On 03/02/2015 11:25 AM, Sydney Shall wrote:

I am a beginner and I am now at the strage of learning to write
unittests.
I have followed the current discussion entitled "How to test a class in
pyhton", and I am not clear precisely what is meant by state. In its
common meaning I can see some relevance. But is there a technical aspect
to the notion. I see it mentioned often and feel rather uncomfortable
that I know so little about it.
I have deliberately started a new thread.
Thanks.


When I started composing this, there were no other replies.  Sorry for
any duplication caused by that.

Starting with a dictionary definition:

http://www.merriam-webster.com/dictionary/state
"the overall physical condition of something : the ability of something
to be used, enjoyed, etc."

Others:


"The particular condition that someone or something is in at a specific
time"

"In computer science and automata theory, the state of a digital logic
circuit or computer program is a technical term for all the stored
information, at a given instant in time, to which the circuit or program
has access."

That last comes the closest to what I'd like to explain.

For a given fragment of executing code, the state includes all local
variables, all parameters, all closures, all visible globals (ie the
ones that *could* be visible to the code.  It also includes indirectly
the values of all environment variables, lots of system information like
the current directory, the time, the network IP address.  It also
includes the current phase of the moon, the astrological sign of the
current president of France, and the number of specs of sand on the
eastern shore of a certain Martian lake.

Thank you very much, Joel, Danny, Alan and Dave.
Your explanations are all very clear and very enlightening.
I shall have to change several of my unittests now. In good time.
I am particularly pleased with the examples; they clarify matters 
considerably for me.


Out of subject, I wonder from this exchange whether teaching should not 
always involve at least several teachers. Your replies are very 
complimentary!



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


Re: [Tutor] What exactly is "state"?

2015-03-02 Thread Dave Angel

On 03/02/2015 11:25 AM, Sydney Shall wrote:

I am a beginner and I am now at the strage of learning to write unittests.
I have followed the current discussion entitled "How to test a class in
pyhton", and I am not clear precisely what is meant by state. In its
common meaning I can see some relevance. But is there a technical aspect
to the notion. I see it mentioned often and feel rather uncomfortable
that I know so little about it.
I have deliberately started a new thread.
Thanks.


When I started composing this, there were no other replies.  Sorry for 
any duplication caused by that.


Starting with a dictionary definition:

http://www.merriam-webster.com/dictionary/state
"the overall physical condition of something : the ability of something 
to be used, enjoyed, etc."


Others:


"The particular condition that someone or something is in at a specific 
time"


"In computer science and automata theory, the state of a digital logic 
circuit or computer program is a technical term for all the stored 
information, at a given instant in time, to which the circuit or program 
has access."


That last comes the closest to what I'd like to explain.

For a given fragment of executing code, the state includes all local 
variables, all parameters, all closures, all visible globals (ie the 
ones that *could* be visible to the code.  It also includes indirectly 
the values of all environment variables, lots of system information like 
the current directory, the time, the network IP address.  It also 
includes the current phase of the moon, the astrological sign of the 
current president of France, and the number of specs of sand on the 
eastern shore of a certain Martian lake.

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


Re: [Tutor] What exactly is "state"?

2015-03-02 Thread Alan Gauld

On 02/03/15 16:25, Sydney Shall wrote:


I am not clear precisely what is meant by state. In its
common meaning I can see some relevance. But is there a technical aspect
to the notion.


Yes, although it is related to the normal vernacular meaning.
There is a whole area of math/engineering dedicated to the study
of state and in particular finite state machines and automata.
Finite State Machine on Wikipedia will tell you more about
that than you want to know :-)

Trying to simplify it to the level of ordinary mortals, state
simply means a specific set of data attribute values, which
affect the outcome of the operations of a system.

A very simple state might be a button which can be ON or OFF.
That's not very interesting.

But suppose we have a more complex circuit model with an upstairs
and downstairs switch controlling a stairway light. Now there are
two boolean variables and whether the light is on or off depends
on the state of both switches

Top Bottom  Light
UP  UP  OFF
UP  DOWNON
DOWNUP  ON
DOWNDOWNOFF

So the state of the light depends on the state of the two switches.
You can't tell what effect moving the Top switch to the UP
position will have on the light unless you already know
either the current state of the light or the state of
the Bottom switch.

We can very easily model that as a class:

class StairLight:
   def __init__(self, sw1=True,sw2=True):
   self.sw1 = sw1
   self.sw2 = sw2
   self._setLight()

   def _setLight(self):
   self.light = self.sw1 != self.sw2

   def __str__(self):
   if self.light:
  return 'light is ON'
   else:
  return 'light is OFF'

   def toggle1(self):
   self.sw1 = not self.sw1
   self._setLight()

   def toggle2(self):
   self.sw2 = not self.sw2
   self._setLight()


SL = StairLight()
print(SL)  # -> OFF
SL.toggle1()
print(SL)  # -> ON
SL.toggle1()
print(SL)  # -> OFF
SL.toggle2()
print(SL)  # -> ON
SL.toggle2()
print(SL)  # -> OFF

Of course the  state values don't need to be boolean, they
can be any type. And they can have many valid values.
Consider the state of a order with several order lines.

It can be initiated, costed, approved, packaged, shipped,
delivered, paid, completed, archived.

That's the happy path, but then consider the extra states
needed for the 'unhappy paths' - awaiting stock, cancelled,
rejected, partial delivery, returned, faulty, and so on.

To simplify things we usually create an explicit state
attribute which is updated after each operation on the
order to reflect the current status.

There are many ways to address these kinds of problems,
and mathematical models that can be applied to simplify
them (in many ways similar to the techniques for simplifying
boolean algebra). In practice they boil down to either a
state model where each state is modelled as a class or
a state table where a large table contains a row for
each possible state and a column for each possible
event. The cells contain an action and the action
returns the next state.

The huge advantage of using state machines like this is
that they are entirely predictable in behaviour and can
be modelled and tested exhaustively. This means they
are ideal for safety critical systems and the like.
Most air/rail/traffic control systems, telecomms network switches,
and equipment control software (cameras, iPods, phones etc)
are built using state machines. Specialist CASE tools
are available (for many !) that will generate the
code from a state model (often graphical). They also
allow the user to run simulations etc to see the effects,
perform performance tests etc all without writing a line
of actual code. It's one of the main reasons that aircraft
don't often crash due to software faults even though your
web browser probably falls over almost every day!

One formal language for developing complex designs based
on this approach is SDL (not the graphics toolset). There
is an opensource CASE tool for SDL written in Python and
Qt, called openGeode:

http://taste.tuxfamily.org/wiki/index.php?title=Technical_topic:_OpenGEODE,_an_SDL_editor_for_TASTE

I spent many years of my life building systems using SDL,
C and Motorola 68000 assembler

Oh, and finally. Another big win for state machines is that they
can oftewn be translated from software into hardware for
the ultimate in performance tweaking! :-)

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
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] What exactly is "state"?

2015-03-02 Thread Danny Yoo
On Mon, Mar 2, 2015 at 8:25 AM, Sydney Shall  wrote:
> I am a beginner and I am now at the strage of learning to write unittests.
> I have followed the current discussion entitled "How to test a class in
> pyhton", and I am not clear precisely what is meant by state. In its common
> meaning I can see some relevance. But is there a technical aspect to the
> notion. I see it mentioned often and feel rather uncomfortable that I know
> so little about it.


Hi Sydney,

Let's take a concrete example that might help things get started.
Let's say that we're writing a playlist generator for a music
broadcast system.

##
class Playlist(object):
# ...?
##

What do we want the Playlist to know?  When we create such a Playlist,
what does the playlist have in hand?


Let's say that it has a complete list of songs when it's being built.

##
class Playlist(object):
def __init__(self, songs):
self.songs = songs
##

That is, 'songs' is a piece of a playlist's state, something that it owns.


So, we can imagine creating a playlist with songs like:

##
class Playlist(object):
def __init__(self, songs):
self.songs = songs

## Here's an example playlist.
playlist = Playlist(["Happy", "Beethoven's 9th Symphony", "Power"])
##

Ok, a bit eclectic.  But let's go with it.


Let's say that we want to add a simple behavior to this class, so that
it can do something useful.  Let's be able to ask the playlist to give
us the *next* song.  What would we like next to do here?  Let's say
that if we call it once on the playlist example above, we'd like to
first see "Happy".  If we call next() again, we'd like to see
"Beethoven", and if we call next() again, we'd like to see "Power".
And for the sake of it, once we're out of songs, let's just see
"*silence*".


We can express the previous paragraph as a unit test!

##
import unittest

class PlaylistTest(unittest.TestCase):
def testSimple(self):
playlist = Playlist(["Happy", "Beethoven", "Power"])
self.assertEqual(playlist.next(), "Happy")
self.assertEqual(playlist.next(), "Beethoven")
self.assertEqual(playlist.next(), "Power")
self.assertEqual(playlist.next(), "*silence*")
##


In a unit test with a function, all we need to do is call the function
on arguments.  But in a unit test with a class, we need to set up the
background scene.  Here, we need to first create a playlist, and
*then* test it out.

Also, notice the weirdness of calling playlist.next() multple times,
and expecting *different* results.  If you have mathematical training,
this is particularly weird!  It's important to notice this because
this means that playlist's next() method can't behave as a
mathematical function that only pays attention to its immediate
parameters.  It will also need to take into account something else,
something part of the state of the playlist.



We can actually run the tests at this point.  Of course, they'll fail,
but that's ok.  Here is a complete program that we can run:

###
import unittest

class PlaylistTest(unittest.TestCase):
def testSimple(self):
playlist = Playlist(["Happy", "Beethoven", "Power"])
self.assertEqual(playlist.next(), "Happy")
self.assertEqual(playlist.next(), "Beethoven")
self.assertEqual(playlist.next(), "Power")
self.assertEqual(playlist.next(), "*silence*")

class Playlist(object):
def __init__(self, songs):
self.songs = songs

if __name__ == '__main__':
unittest.main()
###



When we run this, we'll see an error.

###
$ python playlist.py
E
==
ERROR: testSimple (__main__.PlaylistGeneratorTest)
--
Traceback (most recent call last):
  File "playlist.py", line 6, in testSimple
self.assertEqual(playlist.next(), "Happy")
AttributeError: 'Playlist' object has no attribute 'next'

--
Ran 1 test in 0.000s

FAILED (errors=1)
###


And in this case, we are overjoyed to see errors.  The tests are
telling us that we haven't implemented a next() method.


For the sake of keeping this message short, let's write a quick and
dirty implementation of one:


###
## Revised implementation of a Playlist:
class Playlist(object):
def __init__(self, songs):
self.songs = songs

def next(self):
if not self.songs:
return '*silence*'
nextSong, self.songs = self.songs[0], self

Re: [Tutor] What exactly is "state"?

2015-03-02 Thread Joel Goldstick
On Mon, Mar 2, 2015 at 11:25 AM, Sydney Shall  wrote:
> I am a beginner and I am now at the strage of learning to write unittests.
> I have followed the current discussion entitled "How to test a class in
> pyhton", and I am not clear precisely what is meant by state. In its common
> meaning I can see some relevance. But is there a technical aspect to the
> notion. I see it mentioned often and feel rather uncomfortable that I know
> so little about it.
> I have deliberately started a new thread.
> Thanks.
> --
> Sydney
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

'State' is the present value of all variables related to the code that
is running.  Often code execution is dependent on the present state to
determine the path of execution.

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


[Tutor] What exactly is "state"?

2015-03-02 Thread Sydney Shall

I am a beginner and I am now at the strage of learning to write unittests.
I have followed the current discussion entitled "How to test a class in 
pyhton", and I am not clear precisely what is meant by state. In its 
common meaning I can see some relevance. But is there a technical aspect 
to the notion. I see it mentioned often and feel rather uncomfortable 
that I know so little about it.

I have deliberately started a new thread.
Thanks.
--
Sydney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] BinaryTrees

2015-03-02 Thread Marcos Almeida Azevedo
On Sun, Mar 1, 2015 at 4:20 AM, Fatimah Taghdi  wrote:

> So i am doing this assignment and we have  make a function that changes a
> binary tree represenation list of lists to nodes and I was wondering if
>

Maybe share the starting code given to you? Or code you already have?


> somone can help on where to start and If there is a possiblity of keeping
> track of the indexdes.
>
> --
>
> *F.T.*
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Marcos | I love PHP, Linux, and Java

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


Re: [Tutor] How to test a class in python?

2015-03-02 Thread Alan Gauld

On 02/03/15 04:41, Danny Yoo wrote:


In a test case for a class, we have a few more things in hand.

1.  The class being tested.
2.  The parameters we use to create the class instance.
3.  The particular method of the class that we're testing.
4.  The parameters we're going to pass as inputs to that method.
5.  The expected output we want to see if the method is behaving properly.


And if the class has static or class methods you need
to test those too. Although they are much more like
ordinary functions.


expected result is supposed to be.  It just so happens that classes
can have a lot more state, and this can contribute to a few extra
steps to do the test set up.


I was going to pick this up once the discussion got going, but since 
you've raised it now...


Classes/objects maintain state, so the same method called with the
same inputs can return different outputs at different times.
That rarely happens with functions.
So it is important when testing classes that you exercise the
entire state machine. That may require test cases that call
specific combinations of methods in a particular sequence
with particular sets of inputs. This can lead to a very
large set of tests (sometimes known as a state explosion)
and the best way to handle such tests is to data drive them,
but that usually requires much more complex testing code
than you would normally have for functions.

So although the principles of testing functions and classes
are the same the practice can be much more complex.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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