[Tutor] class methods: using class vars as args?

2010-05-23 Thread Alex Hall
Hello all,
I know Python reasonably well, but I still run into basic questions
which those over on the other python list request I post here instead.
I figure this would be one of them:
Why would this not work:

class c(object):
 def __init__(self, arg1, arg2):
  self.arg1=arg1
  self.arg2=arg2

 def doSomething(self, arg3=self.arg1):
  ...

The above results in an error that "name 'self' is not defined". Why
can I not set the default values of a method's arguments to class vars
like that? Thanks!


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] 2d list index inverting?

2010-05-25 Thread Alex Hall
Hello all,
I have a 2d list being used for a battleship game. I have structured
the program so that it uses a grid class, which implements this array
along with a bunch of other methods and vars. For example, to get at
the top left square, you would say:
Grid.getSquareAt(0,0)
and inside getSquareAt is simply:
 def getSquareAt(self, x, y):
  return self.b[x][y] #b is the internal 2d list for the class

However, I am getting very confused with indexing. I keep getting
errors about list index out of range and I am not sure why. I have a
feeling that using 2d lists is supposed to go like a matrix
(row,column) and not like a coordinate plane (column, row). Any
suggestions? If you want the full source, just let me know and I will
update the zip file on my server and send the link. TIA!

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 2d list index inverting?

2010-05-25 Thread Alex Hall
On 5/25/10, Hugo Arts  wrote:
> On Wed, May 26, 2010 at 3:13 AM, Alex Hall  wrote:
>> Hello all,
>> I have a 2d list being used for a battleship game. I have structured
>> the program so that it uses a grid class, which implements this array
>> along with a bunch of other methods and vars. For example, to get at
>> the top left square, you would say:
>> Grid.getSquareAt(0,0)
>> and inside getSquareAt is simply:
>>  def getSquareAt(self, x, y):
>>  return self.b[x][y] #b is the internal 2d list for the class
>>
>> However, I am getting very confused with indexing. I keep getting
>> errors about list index out of range and I am not sure why. I have a
>> feeling that using 2d lists is supposed to go like a matrix
>> (row,column) and not like a coordinate plane (column, row).
>
> A 2D list doesn't really exist. What you're using is just a list whose
> elements are also lists. A nested data structure. And whether those
> sub-lists should be the rows or the columns? It doesn't matter. A list
> is just a list. Sequential data elements. It doesn't care whether it
> represents a row or a column. What are 'row' and 'column' anyway? just
> words designating some arbitrary notion. Conventions. You can swap one
> for the other, and the data remains accessible. As long as you're
> consistent, there's no problem.
I thought so, but I was hoping you would not say that as this means a
logic bug deep in my code, and those are the hardest to track down...
>
> The real problem is something else entirely. Somewhere in your code,
> you are using an index that is greater than the size of the list.
Yes, and it looks like my coordinates are bing reversed somewhere, but
I cannot find anywhere where that is happening in the code.
> Perhaps you're not consistent, somewhere. Mixing up your row/column
> order. Perhaps something else is amiss. No way to tell from the
> snippet.
So, a lot of print() statements then...
>
> Hugo
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 2d list index inverting?

2010-05-25 Thread Alex Hall
On 5/25/10, Hugo Arts  wrote:
> On Wed, May 26, 2010 at 3:47 AM, Alex Hall  wrote:
>>
>> I thought so, but I was hoping you would not say that as this means a
>> logic bug deep in my code, and those are the hardest to track down...
>
> Unfortunately, yes. Bug hunting is part art, part science.
You can say that again. My major (just one year left!) is computer
science, focusing in programming (though Python is something I am
pursuing on my own), so I have done a lot of finding seemingly
impossible bugs. It is never fun, though, until that wonderful point
when you squash the offending insect!
>
>>> The real problem is something else entirely. Somewhere in your code,
>>> you are using an index that is greater than the size of the list.
>>
>> Yes, and it looks like my coordinates are bing reversed somewhere, but
>> I cannot find anywhere where that is happening in the code.
>
> This is a good thing. You already have some idea of what is happening.
> Confirm your suspicions, then work from there.
>
>>> Perhaps you're not consistent, somewhere. Mixing up your row/column
>>> order. Perhaps something else is amiss. No way to tell from the
>>> snippet.
>> So, a lot of print() statements then...
>
> It's a good start. I suggest you begin at the place where the error
> occurs, then work your way back slowly. verify at each point that your
> data is mixed up, until you find what introduced the mixup.
Yes. I have found that, somewhere, my rows are being swapped for
columns, and vice versa. My grid on the screen is 10 columns of 14
rows, but the computer sees 14 columns of 10 rows. However, I am
currently at a loss as to just where this switch is taking place.
Still, it looks like finding one line will fix it, not every reference
to coordinates.
>
> There are other some other useful tools. The python debugger might be
> of some help. http://docs.python.org/library/pdb.html
> It's especially useful to gain more insight in what precisely a piece
> of code is doing. There is a learning curve to it, but once you know
> how to use it it will pay back many times over.
I am blind, using Jaws for Windows to access my computer
(http://www.freedomscientific.com). Is this debugger a cmd line tool,
or is it / is it part of an IDE? Basically I am hoping it is not its
own interface, as these are often not too compatible with screen
readers. I will definitely read through the page, though, and that
should help to answer the above question. I just figured I would ask
in case you had any knowledge of the debugger's accessibility.
>
> I think you'll have this bug resolved soon enough by yourself, but
> should you get the urge to bang your head against a wall repeatedly,
> come back here and we'll have a closer look at it. Good luck and happy
> hunting,
>
> Hugo
Thanks! Hopefully I will not need to have anyone on here go through
the code, but sometimes the best thing is a fresh pair of eyes. The
problem is that none of my friends know a thing about Python, so I
guess that is where this list comes in, should it prove necessary.
Thanks for the offer!
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Battleship grid not working how I expect

2010-05-27 Thread Alex Hall
Hi all,
I very much hoped not to have to do this, but I have been staring at
my code for two days and I just cannot see what is going on.
http://www.gateway2somewhere.com/bs.zip
has my code in it. You need wxPython to run it. speech.py has some
pywin stuff, but that is only to interface with screen readers and is
not important to most, probably all, of you. In board.py, you will
want to find the speak method in the grid class and comment out the
line "speech.speak(txt)", as well as commenting out "import speech" at
the top of the file.

The problem: I have a battleship grid, where each square is a
wx.Button and the row letters and column numbers are wx.StaticTexts.
Internally, I refer to coordinates as (x,y), so which column you are
in followed by which row. Battleship uses (row,col) for coordinates,
which is why anything to do with printing or reading coordinates may
seem backwards. I want a grid with 10 rows and 14 columns or, in
Battleship terms, columns 1-14 and rows a-j. Somewhere, or maybe
several somewheres, something is getting switched around and I end up
with columns 1-10 and rows a-n, but my movement function still allows
me to move in a 10cx14r grid, not the other way around. I have added a
lot of comments, but if something does not make sense, please ask me
to clarify. Also, I only indent one space, and I use #closeing tags.
This is because I use a screen reader, and it makes life a great deal
easier (especially in Python) to do it this way. Thanks in advance for
any light you can shed on this very frustrating problem!

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] class methods: using class vars as args?

2010-05-27 Thread Alex Hall
Thanks for all the explanations, everyone. This does make sense, and I
am now using the
if(arg==None): arg=self.arg
idea. It only adds a couple lines, and is, if anything, more explicit
than what I was doing before.

On 5/27/10, Mark Lawrence  wrote:
> On 23/05/2010 20:40, Alex Hall wrote:
>> Hello all,
>> I know Python reasonably well, but I still run into basic questions
>> which those over on the other python list request I post here instead.
>> I figure this would be one of them:
>> Why would this not work:
>>
>> class c(object):
>>   def __init__(self, arg1, arg2):
>>self.arg1=arg1
>>self.arg2=arg2
>>
>>   def doSomething(self, arg3=self.arg1):
>>...
>>
>> The above results in an error that "name 'self' is not defined". Why
>> can I not set the default values of a method's arguments to class vars
>> like that? Thanks!
>>
>>
> You've already had some explanations as to what happens, but what are
> you trying to achieve?  Why don't you forget about arg3 because it is
> arg1, which must exist by creating an instance of class c, or you
> wouldn't be able to call doSomething in the first place?
>
> HTH.
>
> Mark Lawrence
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] disregard Battleship post (for now)

2010-05-28 Thread Alex Hall
Hi all,
A couple days ago I posted a request for help with a strange problem
with my Battleship game. I finally double-checked the constructor for
a wx.GridSizer and, to my surprise, found that I had reversed the
column/row args in my call to said constructor. I will have to confirm
with a sighted person, but I believe that switching those two args and
updating the loop that populates the sizer has since fixed the
problem. If not I will be writing back, but for now assume I am all
set. Thanks anyway, though.

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] disregard Battleship post (for now)

2010-05-28 Thread Alex Hall
On 5/28/10, Hugo Arts  wrote:
> On Fri, May 28, 2010 at 11:06 PM, Alex Hall  wrote:
>> Hi all,
>> A couple days ago I posted a request for help with a strange problem
>> with my Battleship game. I finally double-checked the constructor for
>> a wx.GridSizer and, to my surprise, found that I had reversed the
>> column/row args in my call to said constructor. I will have to confirm
>> with a sighted person, but I believe that switching those two args and
>> updating the loop that populates the sizer has since fixed the
>> problem. If not I will be writing back, but for now assume I am all
>> set. Thanks anyway, though.
>>
>
> This mail came around right about 10 seconds after I finally got
> around to downloading that zip file ;)
Good timing, then; at least you did not spend time unnecessarily
searching for a bug I had found. Thanks anyway, though!
> Ah well, glad you solved it. It was bound to be something like this.
Mee, too. It seems that the most frustrating bugs are invariably the
smallest mistakes.
>
> Hugo
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] class methods as static methods?

2010-05-29 Thread Alex Hall
Hi all,
In Battleship, I have a weapons.py file, currently with just one
missile type (a Harpoon anti-ship missile). This Harpoon class defines
a getImpactCoords method, which returns all coordinates on the map
that it will hit. I would like to not instantiate a Harpoon object,
just call the Harpoon's getImpactCoords method and pass it the
required arguments. Is this possible? Thanks. Sorry if I got the terms
backwards in the subject; I can never remember which is static and
which is non-static.

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] class methods as static methods?

2010-05-29 Thread Alex Hall
On 5/29/10, Mark Lawrence  wrote:
> On 29/05/2010 20:49, Alex Hall wrote:
>> Hi all,
>> In Battleship, I have a weapons.py file, currently with just one
>> missile type (a Harpoon anti-ship missile). This Harpoon class defines
>> a getImpactCoords method, which returns all coordinates on the map
>> that it will hit. I would like to not instantiate a Harpoon object,
>> just call the Harpoon's getImpactCoords method and pass it the
>> required arguments. Is this possible? Thanks. Sorry if I got the terms
>> backwards in the subject; I can never remember which is static and
>> which is non-static.
>>
>
> Hi Alex,
>
> See you're still going for it :)
>
> I think that you're trying to build a Yamoto/Musashi before you've built
> a raft from oil drums or whatever :)  If I'm wrong, I'll apologise here
> and now.
I have built one app in Python and have experience in Java and
Javascript, as well as some in PHP; in fact, I am going into my fourth
year of college for a computer science degree in September. While they
have not done as much programming as I would like, I have had enough
that I can find the commonalities between languages and generally know
what I am looking for (make this public, turn that into a class
instead of an independent collection of vars...)
That said, I have no professional experience programming and do only
assigned problems and hobby-level programming. My Screenless Widgets
app is nearing beta testing and works to my satisfaction, but I am
sure there is much I could do to improve it. Still, everyone has to
start somewhere...
I say all this not to express any offense at your message - believe
me, none taken - but rather to tell everyone just where I am coming
from.
>
> For a really great introduction to Python, I suggest diveintopython,
> it's what got me going eight years ago.
I feel that I understand the basics; what I am running into are things
that crop up and I learn them as needed; if I learn a concept but then
never use it, I will forget it, or mix it up with a similar comcept in
another language, so I generally attack things by reading intro
tutorials, modifying them, and then continuing from there until I feel
that I can start my own project from scratch and figure out the pieces
as I go along.
>
> Kindest regards.
>
> Mark Lawrence.
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] class methods as static methods?

2010-05-30 Thread Alex Hall
On 5/30/10, Alan Gauld  wrote:
> "Alex Hall"  wrote
>
>> that it will hit. I would like to not instantiate a Harpoon object,
>> just call the Harpoon's getImpactCoords method and pass it the
>> required arguments. Is this possible?
>
> Others have pointed out that
> a) This is possible using staticmetjhod or classmetjod decorators and
> b) it seems a strange choice since you would expect the ability to
> use more than one harpoon and hence be better with an instance...
>
> I will add that if you really want a class method then maybe
> you can do without the class completely and just use a function?
Yes, that is what I ended up doing for testing, but it works well and
I do not think I will be making missile classes, just put each missile
type in its own file in a weapons subfolder, then import "from weapons
import *" to import all weapon files.
>
> The usual reason for class methods is to operate on the
> class as a whole - ie all instances - it is not to provide
> functionality
> without any instances (except in languages without functions,
> like Java, which really use static methods as a kluge to cover
> their limitations!)
>
> And functioons are much easiert to write and manage than
> instanceless classes!
>
> HTH,
>
> --
> Alan Gauld
> 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
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] playing game across internet: suggestions for design?

2010-05-30 Thread Alex Hall
Hi all,
While Battleship is not quite where I want it in terms of weapons, and
while I await a response on another list to improve that, I figured I
would at least start inquiries on the internet front. My plan is to
let myself and a friend play each other at the game over the internet.
I realize that one of us will have to play server and the other
client, but the roles nake no difference. When a session starts, I
will create my playing board and place my ships, and my friend will do
the same. Then, I get his board and he gets mine. In this way I can
fire at a board holding his ships, and he can fire at a board holding
my ships. Each turn, I imagine some information moving from one
computer to the other, such as the functions he called and their
arguments. I can then parse this information and output information
("Your Battleship was sunk").

Basically, how might I go about setting up a connection between the
two computers? Not at the socket level, but how do I tell his game
that mine is ready to start? How do I decide who is server and who is
client? Thanks!

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] playing game across internet: suggestions for design?

2010-05-31 Thread Alex Hall
On 5/31/10, Alan Gauld  wrote:
>
> "Alex Hall"  wrote
>
>> I realize that one of us will have to play server and the other
>> client, but the roles nake no difference.
>
> Actually since there are only two players in Battleships you
> could dispense with a server and do a peer to peer game.
>
> Or you could create a single server and both be clients.
When you say 'peer to peer', is this still with Python sockets? It
sounds like what I am looking for! Or, creating a server and both of
us being clients: I have a server (not my own machine, but I rent
space on an iPowerWeb.com server) so I could do this, but I would have
no idea where to start. Sounds like the p2p connection is the best
one.
> There are several ways to architect this.
> You could even make it a web app with cookies to
> record which player is which.
I need a lot of keyboard interaction and popup dialogs with lists and
input controls, and my server does not have Python on it. Good
thought, though; maybe I could strip this one down and port to js...
>
>> Basically, how might I go about setting up a connection between the
>> two computers? Not at the socket level, but how do I tell his game
>> that mine is ready to start? How do I decide who is server and who
>> is
>> client? Thanks!
>
> If you go for a socket level interaction then you need to
> define your own protocol, or message set. There is a basic
> example of that in my tutorial in the Network Programming
> topic under the AddressBook example.
>
> If the protocol is significant in size - lots of commands - its
> best to define the message strings as constants in a shared
> module that both client and server can read. Python's string
> formatting characters make a useful templating language.
>
> HTH,
>
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/tutor/
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] sockets, servers, clients, broadcasts...?

2010-06-03 Thread Alex Hall
Hi all,
I am a CS major, so I have had the required networking class. I get
the principles of networking, sockets, and packets, but I have never
had to actually implement any such principles in any program. Now I
have this Battleship game (not a school assignment, just a summer
project) that I am trying to make playable over the internet, since I
have not written the AI and playing Battleship against oneself is
rather boring.

Right now I am just trying to figure out how to implement something
like the following:
*you start the program and select "online game"
*you select "server" or "client" (say you choose "server")
*somehow, your instance of the program starts up a server that
broadcasts something; your enemy has selected "client", and is now
(SOMEHOW) listening for the signal your server is broadcasting
*the signal is picked up, and, SOMEHOW, you and your opponent connect
and can start sending and receiving data.

First, how does the client know where to look for the server? I am not
above popping up the server's ip and making the client type it in, but
a better solution would be great.
How do I make it so that the client can find the server correctly? The
above IP is one thing, but are ports important here? Not a big deal if
they are, but I am not sure. Does someone have an example of this
process?

Thanks. I know I have emailed this list (and other lists) before about
this, but my peer-to-peer has not even started to look promising yet,
since this is my first time ever doing anything remotely like this
from a programming perspective, in any language. For now, it is all a
frustrating and confusing tangle of Socket objects and low-level
calls, but hopefully things will start to clear up over the next few
days.

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] sockets, servers, clients, broadcasts...?

2010-06-04 Thread Alex Hall
Thanks for the suggestions, everyone. For now, more as a way to
introduce myself to all this, I am going to have my program
automatically start a server and pop up that server's ip. Then, if you
want, you can type in an ip and connect to the server at that ip
(ports are hard-coded at ). That way everyone is a server and a
client, and either you connect to someone else as a client or they
connect to you as a client. It appears, though, that I need a loop to
have a server make any sense at all, to handle incoming data and
connection requests. Obviously, starting this loop will then put the
rest of my program on hold. Am I safe to use basic threading to stick
the server's loop into a new thread? That is, will the rest of my
program be able to talk to the server / will the server be able to
talk to my program from its new home in its separate thread, and might
I run into strange problems because of process scheduling and blocking
(or not blocking)?

On 6/4/10, spir  wrote:
> On Thu, 3 Jun 2010 18:03:34 -0400
> Alex Hall  wrote:
>
>> Hi all,
>> I am a CS major, so I have had the required networking class. I get
>> the principles of networking, sockets, and packets, but I have never
>> had to actually implement any such principles in any program. Now I
>> have this Battleship game (not a school assignment, just a summer
>> project) that I am trying to make playable over the internet, since I
>> have not written the AI and playing Battleship against oneself is
>> rather boring.
>>
>> Right now I am just trying to figure out how to implement something
>> like the following:
>> *you start the program and select "online game"
>> *you select "server" or "client" (say you choose "server")
>> *somehow, your instance of the program starts up a server that
>> broadcasts something; your enemy has selected "client", and is now
>> (SOMEHOW) listening for the signal your server is broadcasting
>> *the signal is picked up, and, SOMEHOW, you and your opponent connect
>> and can start sending and receiving data.
>>
>> First, how does the client know where to look for the server? I am not
>> above popping up the server's ip and making the client type it in, but
>> a better solution would be great.
>> How do I make it so that the client can find the server correctly? The
>> above IP is one thing, but are ports important here? Not a big deal if
>> they are, but I am not sure. Does someone have an example of this
>> process?
>
> I'm far to be a specialist in this field, so this is just reasoning by
> watching your requirements.
>
> First, such a game seems to match peer-to-peer relation. This would be
> different if you implemented complicated game logic, like in the case of an
> AI playing.
> For peers to connect, a general solution is them to register on a dedicated
> public interface (the same can be used to publish a server's IP, indeed).
> Then, your app first reads data there to know which (address,port) pair(s)
> are available.
> But since you seem to be still exploring data exchange issues, you'd better
> concentrate on this basic mechanism first, choose and try one of numerous
> possible solutions, then only address higher-level problems. In the
> meanwhile, just put IPs and ports in a config file or even hardcode them as
> constants.
>
> About client-server, as said above, this model does not really seem to match
> your use case, I guess. But this is still an interesting alternative. I
> would set my own post as server and players as clients. So, when playing
> myself, I would be a local client. This indeed allows two other guys playing
> using your post as server (and you maybe watching the game ;-).
> But this does not make much sense if the server does not have any relevant
> info to deliver (eg playing hints).
>
>
> Denis
> 
>
> vit esse estrany ☣
>
> spir.wikidot.com
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] sockets, servers, clients, broadcasts...?

2010-06-04 Thread Alex Hall
On 6/4/10, Alan Gauld  wrote:
>
> "Alex Hall"  wrote
>
>> connect to you as a client. It appears, though, that I need a loop
>> to
>> have a server make any sense at all, to handle incoming data and
>> connection requests.
>
> You need to listen then process incoming messages then listen some
> more, so yes you will need a loop. Probaqbly an infinite one:
>
> while True:
>  listen()
>  if someQuitMessage:
> break
>  process()
>> rest of my program on hold. Am I safe to use basic threading to
>> stick
>> the server's loop into a new thread?
>
> For your game you don't need to do that. A single thread should
> suffice.
The idea is to have every instance of the game start up a server (if
it is configured to do so by the user). So when a client connects to
you, you and the client exchange data (ship positions, board size, and
so on), then each move by you sends results to the client and each
move by the client sends results to you. For example, the client fires
at square A1. As soon as that happens, a toople something like
("shell","a1")
is sent to you, the server. You then see if that was a hit or a miss
on one of your ships and inform the user accordingly. Currently, the
game is based on an accelerator table inside a wx Frame, but I think
what I will do is put the calls to server.send() as required in each
function called by the accelerator table. I am not sure how I would
insert this into the server's loop; as it stands, it seems much more
intuitive to have the server spinning its wheels, waiting for things
to happen. Again, I am very new to all this, so maybe there is a
better way, but I do not know how I would put all the game logic into
a huge while loop. Oh, I am using the "toomi" library, which provides
basic client and server classes and seems to do what I need, at least
for now.
> But usually a server's listen loop is the main thread and the
> processing
> goes into the sub threads.
>
>> program be able to talk to the server / will the server be able to
>> talk to my program from its new home in its separate thread,
>
> Look at the example in my tutorial. It doesn't use threads but
> services two separate clients without lockup. (Albeit it doesn't
> care about context...)
What is the link for the tutorial? Also, maybe a bit off topic, what
is a context? I dealt with them a lot in Android programming last
semester, but I still do not get them, and I thought they were just an
Android/Java thing.
>
> --
> Alan Gauld
> 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
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] while loops causing python.exe to crash on windows

2010-06-06 Thread Alex Hall
-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while loops causing python.exe to crash on windows

2010-06-06 Thread Alex Hall
On 6/6/10, bob gailer  wrote:
> On 6/6/2010 8:44 PM, Alex Hall wrote:
>> --
>> Have a great day,
>> Alex (msg sent from GMail website)
>> mehg...@gmail.com;http://www.facebook.com/mehgcap
>>
>>
> What is your question?
>
>
> --
> Bob Gailer
> 919-636-4239
> Chapel Hill NC
>
>
Why would that code cause Windows to consider the process "not
responding", and how can I fix this so I can have a sort of "listener"
in place, awaiting a change in the "grid.turnOver" variable inside
Player.takeTurn() so that the main while loop can switch to the other
player once the one player's turn is over? I thought while loops would
do it, but Windows sees them as making python.exe unresponsive.


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while loops causing python.exe to crash on windows

2010-06-06 Thread Alex Hall
On 6/6/10, Lie Ryan  wrote:
> On 06/07/10 11:08, Alex Hall wrote:
>> On 6/6/10, bob gailer  wrote:
>>> On 6/6/2010 8:44 PM, Alex Hall wrote:
>>>> --
>>>> Have a great day,
>>>> Alex (msg sent from GMail website)
>>>> mehg...@gmail.com;http://www.facebook.com/mehgcap
>>>>
>>>>
>>> What is your question?
>>>
>>>
>>> --
>>> Bob Gailer
>>> 919-636-4239
>>> Chapel Hill NC
>>>
>>>
>> Why would that code cause Windows to consider the process "not
>> responding", and how can I fix this so I can have a sort of "listener"
>> in place, awaiting a change in the "grid.turnOver" variable inside
>> Player.takeTurn() so that the main while loop can switch to the other
>> player once the one player's turn is over? I thought while loops would
>> do it, but Windows sees them as making python.exe unresponsive.
>
> Would you buy me a crystal ball to foresee what you're talking about?
I am not sure how else to explain it. I want to loop until the value
of a variable changes, but while that loop is taking place, the user
should be able to perform actions set up in a wx.AcceleratorTable.
Looping, though, causes Windows to tell me that python.exe is not
responding, so I have to close the entire thing. I guess I am looking
for a "listener", which will sit in the background and only perform an
action when it detects a certain thing. In this case, a listener to
watch for a variable to turn from False to True, then to act when it
sees that change.
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] while loops / listeners

2010-06-06 Thread Alex Hall
Hi all,
First off, I apologize to the list for my previous thread; somehow,
despite my having written the post, it ended up blank ()

I have a main loop which will continue for as long as neither player1
nor player2 has won. Inside that loop I have a call to a function
which should basically wait until the user completes a turn, then
return, exiting this loop and returning to the main loop, the one
looping until there is a winner. Once back there, the second player's
idling function is called; once that user completes a turn, the main
loop switches back to the first user, and so on. Here is the main
loop:
 player1.takeTurn() #someone has to start off the game

 #now loop until someone wins...
 while not player1.isWinner and not player2.isWinner:
  if player1.grid.turnOver: #player1 is done for this turn
   player1.grid.speak("player 2 is going.")
   #lock p1 out of the window, unlock p2, and then loop p2 until s/he
does something
   player1.lock(); player2.unlock(); player2.takeTurn()
  else: #player2 has completed a turn
   player2.grid.speak("player 1 is going.")
   #opposite of above - lock p2, unlock p1, loop until p1 is done
   player2.lock(); player1.unlock(); player1.takeTurn()
  #end if
  continue #is this doing anything?
  time.sleep(.1) #again, is this important?
 #end while

The lock and unlock functions are simply there to disable and enable
keyboard/mouse commands, respectively, so lock causes the player's
screen to stop responding to input while unlock unfreezes the screen.
This way, if you and I are playing a game, I can't keep shooting even
if my turn is over.
TakeTurn() is that smaller loop I was talking about:
 def takeTurn(self):
  while not self.grid.turnOver: #turnOver is true once a turn-ending
function is called in grid
   continue
   time.sleep(.1)
  #end while
 #end def

That is inside the Player class. Grid is just another object that is
really the most important part of all the game logic; Grid holds the
wx frame on which everything is drawn, the boolean to tell if the turn
is over, the ships, and more. That is why the function checks
self.grid.turnOver, instead of just self.turnOver; turnOver tells if
the player has performed a move that ends a turn or not. Firing ends a
turn, while just moving around does not.

The question, then, is this: when I run the code, Windows says
"python.exe has stopped responding". I know that this is because it is
getting stuck, probably in the takeTurn() loop. Ordinarily, a
situation like this would probably call for:
while ok:
 ok=#program logic

The hard part with my program, though, is that all input is set up
with a wx.AcceleratorTable object, so I cannot just dump everything
into a huge while loop and have it process that way. What I am looking
for is some kind of listener object, so that I can just monitor
self.grid.turnOver and call a function, or perform a few lines of
code, when the listener detects a change in turnOver. On the other
hand, there may be something simple that I am missing in my while loop
that would cause the problem of python.exe crashing to not happen
(well, not crashing, but rather not responding). I hope it is the
latter problem, but I am not sure what else I could add to the loop(s)
to stop this problem. Thanks, and sorry again for the blank message;
still not sure how that happened. Hopefully this one works!

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Looking for duplicates within a list

2010-06-11 Thread Alex Hall
On 6/11/10, Ken G.  wrote:
> I have been working on this problem for several days and I am not making
> any progress.  I have a group of 18 number, in ascending order, within a
> list.  They ranged from 1 to 39.  Some numbers are duplicated as much as
> three times or as few as none.
FYI, Python's "set" data type will let you have a list and never have
a repeat. I know that is not your goal now, but if you want to remove
duplicates, it seems like a good choice.
>
> I started with one list containing the numbers.  For example, they are
> listed as like below:
>
> a = [1, 2, 3, 3, 4]
>
> I started off with using a loop:
>
> for j in range (0, 5):
> x = a[0] # for example, 1
>
> How would I compare '1' with 2, 3, 3, 4?
>
> Do I need another duplicated list such as b = a and compare a[0] with
> either b[0], b[1], b[2], b[3], b[4]?
>
> Or do I compare a[0] with a[1], a[2], a[3], a[4]?
A couple points here. First, you will want to make life easier by
saying range(0, len(a)) so that the loop will work no matter the size
of a.
Second, for comparing a list to itself, here is a rather inefficient,
though simple, way:

for i in range(0, len(a)):
 x=a[i]
 for j in range(0, len(a)):
  y=a[j]
  if(x==y and i!=j): #match since a[i]==a[j] and i and j are not the
same index of a
>
> In any event, if a number is listed more than once, I would like to know
> how many times, such as 2 or 3 times.  For example, '3' is listed twice
> within a list.
Do not quote me here, but I think sets may be able to tell you that as well.
>
> TIA,
>
> Ken
>
>
>
>
>
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python a substitute/alternative for PhP?

2010-06-11 Thread Alex Hall
Personally, I would learn Python. My college does not offer Python
either, so I had to learn what I know on my own(of course, by that I
mean constantly pestering this and other of the amazing Python email
lists). PHP is fine in itself, but, after using it, Java, and intros
to a few other languages, nothing has been able to beat Python's ease
of use, massive extensibility (there is a package to let you do just
about anything you want), and support community. It is a great
language and, especially if you plan to stick with desktop
applications, I think it is much easier than a language like C++ or
Java. Your life will be even easier than mine since you are going to
be on Linux; I believe most Linux distros come with Python, while
Windows does not, so what you make can be distributed as scripts while
I have to use a program like py2exe and package the entire Python
interpreter.
Anyway, just my thoughts. Note that I am still in college for my
computer science degree and am in no way a professional programmer,
just someone who has waded in several languages and found Python to be
the only one worth diving into all the way.

On 6/11/10, Eldon Londe Mello Junior  wrote:
>
> Hi there,
>
> If you care to listen to my story and fully help me out, just keep on
> reading }else{ move to the final question :)
>
> I'm just finishing an introductory course on PhP and MySQL (HTML, CSS and
> Javascript basics included). That's a typical first step to novice
> programmers in Brazil.
>
> However, I've been reading a lot about programming languages and stuff in
> order to make the best choice as I don't want to spend much time learning
> unnecessary things I won't need in the future.
>
> Thus, I decided I want to be a contributor for the GNU/LINUX community and,
> of course, become sort of an opensource-solutions professional programmer.
> And if I got it right, python would the most adequate language for me to
> reach my goals.
>
> Only a few programmers in Brazil are familiar with python though. As I said
> before, most beginners start with PhP and stick with it or go for JAVA or MS
> proprietary languages. Actually, you can only learn python on your own
> around here as no college or private institutes offer python courses.
>
> As you may see it coming, the big question for me is: should I stick with
> PHP as most people here (those fond of free software) or Python is or would
> be a better choice for me?
>
> FINAL QUESTION> Is Python a substitute for PHP? I mean, can I start learning
> python by trying to do the things I've learned with PHP? Are they different
> anyhow or they actually compete against each other?
>
> Thanks in advance, advice on which steps to take to reach my career goals
> would be very appreciated as well!
>
> Eldon.
>
>
>
>
>
>> Date: Fri, 11 Jun 2010 15:27:44 -0700
>> From: dkuhl...@rexx.com
>> To: Tutor@python.org
>> Subject: Re: [Tutor] What's the catch with ZopeDB?
>>
>> On Fri, Jun 11, 2010 at 09:42:35PM +0200, Knacktus wrote:
>>
>> >
>> > To me, ZopeDB (a object database for Python) looks like an awesomely
>> > easy solution. I could save some brain power for the innovative part or
>> > drink more beer watching the soccer world cup. At the same moment, I
>> > wonder why anyone in the python world would go through the hassle of
>> > using relational databases unless forced.
>> >
>> > So, has anyone experience with ZopeDB? Are there some drawbacks I should
>> >
>> > be aware of before getting a book and dive in? (It sounds too good ;-))
>> >
>>
>> Jan -
>>
>> If you are evaluating alternative solutions, you might also look
>> into Django models.  There have been some very positive comments
>> about Django on this list.  And, Django models can be used outside
>> of the Django Web applications.  Also, Django models are reasonably
>> object oriented.  A Django model/DB can sit on top of several
>> different relational database engines, for example, PostgreSQL, MySQL,
>> sqlite3, etc.
>>
>> See:
>>
>> http://docs.djangoproject.com/en/1.2/#the-model-layer
>> http://www.djangobook.com/en/2.0/chapter05/
>>
>> - Dave
>>
>> --
>> Dave Kuhlman
>> http://www.rexx.com/~dkuhlman
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>   
> _
> Your E-mail and More On-the-Go. Get Windows Live Hotmail Free.
> https://signup.live.com/signup.aspx?id=60969


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] winsound.Beep(500,500) "Failed to beep"

2010-06-12 Thread Alex Hall
Not that it helps much, but using win7x64 and Python 2.6 it works as
expected. Possibly your sound card? Update drivers?

On 6/12/10, Richard D. Moores  wrote:
 import winsound
 winsound.Beep(500,500)
> Traceback (most recent call last):
>   File "", line 1, in 
> RuntimeError: Failed to beep

>
> Vista, Python 3.1
>
> Any ideas?
>
> Dick Moores
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] New to this

2010-06-20 Thread Alex Hall
On 6/20/10, Neil Thorman  wrote:
> I'm picking this up as a hobby really, not having done any programming since
> Acorn I'm pretty much starting form scratch (and even back in the BASIC day
> I never really got to grips with files).
> This is from Alan Gauld's Learning to Program: Handling Files.
> http://www.freenetpages.co.uk/hp/alan.gauld/
>
> Can I just check I'm getting
> it?
>
>
> *Menu.txt contains*
>
> *Spam & Eggs*
> *Spam & Chips*
> *Spam & Spam*
>
inp = file("menu.txt", "r")
> *What is inp? What does it now contain?*
It is now a reference to the location of the txt file. Python calls
these file "objects", where an object is just something on which you
can call functions. If you had a dog object you might call a "bark"
method; here, we have a file object, so we can see what the file is.
inp is not the file itself, just as any object is not the full
object's info but rather a pointer to where that info is. If you were
to print inp, I think you would get a memory address.
> *The following creates a list;*
> *
> *
> *
print inp.readlines()
> ['spam & eggs\n', 'spam & chips\n', 'spam & spam']
>
> but if I do it again I get:
 print inp.readlines()
> []
>
> I'm baffled, why is inp now empty?
I suspect you have hit the end of the file. I rarely work with files
myself, but I believe there is a way to reset your pointer in the file
to the top; after the readlines call, that pointer is at the end of
the file.
>
> Many thanks
>
> Neil
>
> ps. I'm working in the IDLE Python Shell.
> *
> *
> *
> *
> *
> *
> *
> *
> *
>
>
> This email is confidential and intended for addressee only .
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] New to this

2010-06-20 Thread Alex Hall
On 6/20/10, Steven D'Aprano  wrote:
> On Mon, 21 Jun 2010 09:02:55 am Alex Hall wrote:
>> On 6/20/10, Neil Thorman  wrote:
> [...]
>> >>>>inp = file("menu.txt", "r")
>> >
>> > *What is inp? What does it now contain?*
>>
>> It is now a reference to the location of the txt file.
>
> [pedantic]
> No, it's actually an abstract data structure that wraps the actual file
> itself. A reference to the *location* of the file would be:
>
> inp = "menu.txt"
>
> Locations are strings. File objects are file objects.
> [/pedantic]
>
> But in a practical sense, pay no attention to the man behind the curtain
> (the implementation details). inp is a file in every way which matters,
> just like after:
>
> n = 42
> x = 1.234
>
> n is an int and x a float in every way which matters.
>
>
>> Python calls
>> these file "objects", where an object is just something on which you
>> can call functions. If you had a dog object you might call a "bark"
>> method; here, we have a file object, so we can see what the file is.
>> inp is not the file itself, just as any object is not the full
>> object's info but rather a pointer to where that info is. If you were
>> to print inp, I think you would get a memory address.
>
> You would get a string printed to the console, like printing *anything*.
>
>>>> print inp
> 
Oh right, the object's toString method (or whatever Python calls this;
Java and Javascript call it toString, and it exists for all objects).
>
> That string happens to contain a hex number which looks like it could be
> a memory address, but that's an implementation detail because CPython
> doesn't sufficiently abstract its objects from the underlying C
> implementation.
>
> Python file objects aren't "files" only in the sense that they exist in
> memory rather than on disk in the file system, but other than that, I
> believe your explanation is at too low a level to be helpful. Neil said
> he's a beginner who hasn't done any programming since BASIC on an
> Acorn, and you're talking about low-level details like memory
> locations. Let me guess, you're also a C programmer?
Good point, and sorry for going into too much detail, much of which is
not on the mark anyway. :) No, I have hardly touched c++, but I am
starting my final year of a computer science degree in a few months so
I have had all the details of objects and how the computer actually
accesses them in several classes.
>
> As far as coding in Python is concerned, inp = file(pathname) creates a
> file object, which *is* a file in all practical sense. Everything else
> is just an implementation detail, which could change depending on the
> version of Python, the operating system, and the underlying hardware.
Very true.
>
>
> [...]
>> >>>>print inp.readlines()
>> >
>> > ['spam & eggs\n', 'spam & chips\n', 'spam & spam']
>> >
>> > but if I do it again I get:
>> >>>> print inp.readlines()
>> >
>> > []
>> >
>> > I'm baffled, why is inp now empty?
>>
>> I suspect you have hit the end of the file.
>
> Yes. readlines reads from the current file position, like all read
> operations. To read all the text again, you have to reset the file
> position with seek:
>
> inp.seek(0)
>
>
>
> --
> Steven D'Aprano
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] upgrade from 2.6.2 to 2.6.5?

2010-06-22 Thread Alex Hall
Hi all,
I am having problems with the Durus package, and I was told that
changing Python versions might help. Most of the other dependencies of
the project I have are 2.6 only, so I do not want to change versions
from 2.6.x, but I would like to try upgrading to 2.6.5 to see if that
fixes things. Will I lose all my packages (in lib/site-packages) if I
do this? Will anything else break, as far as third-party installs go?
Thanks.

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] upgrade from 2.6.2 to 2.6.5?

2010-06-22 Thread Alex Hall
Thanks, I'll go upgrade then, and hope this fixes things with this package!

On 6/22/10, Tim Golden  wrote:
> On 22/06/2010 13:40, Alex Hall wrote:
>> Hi all,
>> I am having problems with the Durus package, and I was told that
>> changing Python versions might help. Most of the other dependencies of
>> the project I have are 2.6 only, so I do not want to change versions
>> from 2.6.x, but I would like to try upgrading to 2.6.5 to see if that
>> fixes things. Will I lose all my packages (in lib/site-packages) if I
>> do this? Will anything else break, as far as third-party installs go?
>
> Nope. That should just work (assuming your 3rd-party installs aren't
> susceptible to changes occurring between 2.6.2 and 2.6.5... although,
> that said, you're *relying* on Durus being affected by such changes :) )
>
> TJG
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] GUI Creation Aide

2010-07-14 Thread Alex Hall
On 7/14/10, Corey Richardson  wrote:
> Hey tutors! I'm creating a GUI for a program. Really simple. I don't
> mind coding it out, but I was looking into things like Glade and the
> like. Do you recommend those over just coding it out by hand, or should
> I try Glade (or similiar) out? Also, I don't really have a preference
> for which toolkit I use, wx/Tk/GTK, etc.
I have only ever used wx with the XRCed program, but I really like it.
Learning xrc is pretty straightforward, and there are some good
tutorials for it. It also has the advantage of keeping the code
generating your gui separate from your program, so code management is
easier. I have heard xrc/python compared to css/html regarding code
separation. For a really simple gui it is probably not too important,
but if you do larger projects later on it will probably make life
easier.
>
> Thanks,
> ~Corey Richardson
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] attachments?

2010-07-21 Thread Alex Hall
-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] "expected an indented block" (see attached)

2010-07-22 Thread Alex Hall
Hi all,
Attached is a file. When I run the program it is part of, I get an
error that says:
line 62: IndentationError: expected an indented block.

I can see nothing wrong with the indentation, though. This is part of
my Battleship game, defining all the different ships and aircraft the
user can have, as well as the special weapons methods for each ship.
If anyone can spot the problem, it would be great. I know I only
indent one space, instead of the normal four, but I use a screen
reader and it is a lot easier and faster to do it this way. If a
version of Python based on braces instead of indents were released, my
world would be so much better!

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap


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


Re: [Tutor] "expected an indented block" (see attached)

2010-07-22 Thread Alex Hall
On 7/22/10, Evert Rol  wrote:
>> Attached is a file. When I run the program it is part of, I get an
>> error that says:
>> line 62: IndentationError: expected an indented block.
>
> This function:
>
>  def fromString(self, str):
>   #creates a Craft object from the string
> #end class Craft
>
>
> Is completely empty (the comment lines are discarded). So Python expects any
> next piece of code to be inside this method (and thus indented).
Oh, I did not realize it threw out comments. That explains it, then!
> If you want an empty function, use 'pass' instead.
>
> (also consider using four spaces for indentation, which I've also found much
> clearer. Have a read through PEP 8; has a lot of interesting tidbits.
> And an editor with a good Python mode is very handy, because that would have
> almost automatically indented the next piece of code, 'class
> Battleship(Craft)', which would have indicated something went awry before
> that line).
The only problem is that I have not found an accessible editor that
will do this.
>
>
>
>> I can see nothing wrong with the indentation, though. This is part of
>> my Battleship game, defining all the different ships and aircraft the
>> user can have, as well as the special weapons methods for each ship.
>> If anyone can spot the problem, it would be great. I know I only
>> indent one space, instead of the normal four, but I use a screen
>> reader and it is a lot easier and faster to do it this way. If a
>> version of Python based on braces instead of indents were released, my
>> world would be so much better!
>
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] "expected an indented block" (see attached)

2010-07-22 Thread Alex Hall
On 7/22/10, Hugo Arts  wrote:
> On Thu, Jul 22, 2010 at 3:35 PM, Evert Rol  wrote:
>>> Attached is a file. When I run the program it is part of, I get an
>>> error that says:
>>> line 62: IndentationError: expected an indented block.
>>
>> This function:
>>
>>  def fromString(self, str):
>>  #creates a Craft object from the string
>> #end class Craft
>>
>>
>> Is completely empty (the comment lines are discarded). So Python expects
>> any next piece of code to be inside this method (and thus indented).
>> If you want an empty function, use 'pass' instead.
>>
>> (also consider using four spaces for indentation, which I've also found
>> much clearer. Have a read through PEP 8; has a lot of interesting tidbits.
>
> Did you read the rest of his post? He's using a screen reader for a
> reason; he can't *see* the code. visual means of structuring code like
> whitespace are meaningless to him at best, and annoying at worst. No
> wonder his code is littered with '#end def' comments. Python's
> significant indentation is horrible for the blind, at least until we
> create a more specialized/better screen reader.
I think a specialized editor is all it would take. Edsharp
(http://www.empowermentzone.com/edsetup.exe) has a way of converting
braced code into Pythonic indents and colons, but you then have to
manage two sets of files, the braced code and the indented code.
Perhaps such an editor is a future project for me...
>
> Alex, Perhaps a better solution is to indent with tabs rather than
> spaces, though I'm normally opposed to using tabs. Alternatively, run
> your files through a script that expands every indent space to four
> spaces before posting here. I've attached a bare-bones script that
> takes a file and a number as argument, replaces every initial space
> with that number of spaces, and writes the result to a new file
> (filename is just the old filename with .new appended).
Tabs are worse because, for some very annoying reason, my reader reads
both hard returns and tabs as the word "blank". That means that I have
no way of knowing when I am reading a tab and when I have gone to a
previous line. Spaces are the only viable option.
Thanks for the script; if I have to attach code in the future, I will
try to remember to run the file(s) through it for easier reading. I
can also make your script remove the #end... comments, since I know a
lot of people do not like them either.
>
> Yes, the script is indented with four spaces, Sorry. I'm sure you
> could write a script that does the reverse operation so it becomes a
> little more readable for you.
>
> Hugo
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] sound libraries?

2010-07-22 Thread Alex Hall
Hi all,
I am curious. If I wanted a library that would let me play sounds at
specific positions in the stereo field, then update that position as
the user "moved" so that it would seem to be a fixed reference point,
what would I use? For example, say the left/right arrows move you left
and right. In the center of your stereo field you hear a sound, say a
bell. As you press the arrow keys, the sound moves, or rather, you
move but the sound stays the same. Pysonic looks like the perfect
answer, but it seems to require python2.3, and I am using 2.6. Are
there any other conprehensive sound libraries that would allow for
dynamic positioning of sound, doplar effects, volume control, and so
on?

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] (no subject)

2010-07-22 Thread Alex Hall
This message was blank, I am not sure if that was the idea or not.

On 7/22/10, ankur  wrote:
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how i can change two lists into one directory

2010-07-22 Thread Alex Hall
On 7/22/10, ANKUR AGGARWAL  wrote:
> hey i have just started making  a app using python and just gt a problem..
>
> i have two list
> a=["x","z"]
> b=[1,2]
>
> i want to make a directory like this
It is called a dictionary, actually.
> c={"x":1,"z":2}
>
> is it possible i mean i tried it using loops and all but i cant append a
> directory so i m unable to do this...
> plz tell me if there's any way to get the directory like this Thanks in
> advance :):)
idx=0
for i in a:
c[i]=b[idx]
idx+=1
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] sound libraries?

2010-07-22 Thread Alex Hall
On 7/22/10, Luke Paireepinart  wrote:
> You can access openal through either pyglet or pygame I believe, and
> definitely thru panda3d. That would allow you to have true 3d sound
> positioning and I believe openal can automatically Doppler too, not sure
> though. Let us know what you go with or if you have questions.
Thanks. I have pygame but was less than impressed with its audio
features, though it is quite possible that I missed or misread
something. I am downloading Panda3d right now; its audio documentation
looks quite promising. Looks like doplaring is supported, too.
>
> Sent from my iPhone
>
> On Jul 22, 2010, at 6:49 PM, Alex Hall  wrote:
>
>> Hi all,
>> I am curious. If I wanted a library that would let me play sounds at
>> specific positions in the stereo field, then update that position as
>> the user "moved" so that it would seem to be a fixed reference point,
>> what would I use? For example, say the left/right arrows move you left
>> and right. In the center of your stereo field you hear a sound, say a
>> bell. As you press the arrow keys, the sound moves, or rather, you
>> move but the sound stays the same. Pysonic looks like the perfect
>> answer, but it seems to require python2.3, and I am using 2.6. Are
>> there any other conprehensive sound libraries that would allow for
>> dynamic positioning of sound, doplar effects, volume control, and so
>> on?
>>
>> --
>> Have a great day,
>> Alex (msg sent from GMail website)
>> mehg...@gmail.com; http://www.facebook.com/mehgcap
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] web-based python?

2010-08-01 Thread Alex Hall
Hi all,
I have an IPowerWeb.com server, which claims to support Python. How
would I use this? For example, to start, how would I print html code
to the screen, or manage input from a form? Thanks.

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] web-based python?

2010-08-01 Thread Alex Hall
On 8/1/10, Hugo Arts  wrote:
> On Sun, Aug 1, 2010 at 7:07 PM, Alex Hall  wrote:
>> Hi all,
>> I have an IPowerWeb.com server, which claims to support Python. How
>> would I use this? For example, to start, how would I print html code
>> to the screen, or manage input from a form? Thanks.
>>
>
> There is a myriad of python web development frameworks. Here's a link
> with a ton of info:
>
> http://wiki.python.org/moin/WebFrameworks
I had looked into Django before. What is confusing me is that it
sounds like it is meant to be run on the server directly. I do not
have direct access to my server, I just rent space on it and can
login. Maybe I am missing something, but how would I get Django onto
my server if I do not have the physical box available to me?
>
> Hugo
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] web-based python?

2010-08-01 Thread Alex Hall
On 8/1/10, bob gailer  wrote:
> On 8/1/2010 1:07 PM, Alex Hall wrote:
>> Hi all,
>> I have an IPowerWeb.com server, which claims to support Python. How
>> would I use this? For example, to start, how would I print html code
>> to the screen, or manage input from a form? Thanks.
> Another participant just raised a similar question!
>
> Unfortunately IPowerWeb.com does not "provide support for custom code or
> custom scripts. We assume that if a customer wants to use Perl, CGI,
> PHP, Python, ASP or any other scripting language, he/she has the
> necessary programming skills to manage his/her scripts."
Sure, but django would be quite helpful. I want to do more than just
print, the point is to be able to handle form input, resize/position
images, all that. Still, it is good to not have to go through the
hastle of getting a straight answer from an iPowerWeb tech support
person. Last time I asked them about my htaccess file they deleted it!
>
> A starting place is the following script - let's call it "test.py".
> Upload it then invoke it. Try http://url-to-your-site/test.py
>
> #!/usr/bin/python
Is this line necessary? I ask because, on Windows, it is ignored, and
I do not know the path to the server's Python interpreter even if it
is required.
> print "Content-type: text/html"
> print
> print ""
> print "Hello World from Python"
> print ""
> print "Standard Hello World from a Python CGI Script"
> print "
Thanks. I assume all built-in functions will work. Would I be able to
upload and use packages?
>
> --
> Bob Gailer
> 919-636-4239
> Chapel Hill NC
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] how to get str() to use my function?

2010-08-04 Thread Alex Hall
Hi all,
I have a card class. A card object simply consists of a pair of
numbers; 0,0 might be the ace of clubs, for example. I have a toString
method in my card class. Is there a way to just say str(card) instead
of card.toString()? Maybe some sort of basic, built-in function to
override? TIA. Oh, what about doing the same with operators? For
example, could I get the program to call my own math functions when it
sees a card object in a math expression, like
if(card1==card2)

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to get str() to use my function?

2010-08-04 Thread Alex Hall
It worked, thanks. Is there a list of these functions somewhere? That
is, the functions that map implicitly to operators or implied uses?
For example, printing will call __str__, as will a cal to str(). What
about math or comparison operators? I have heard of __eq__, __gt__,
and so on, but I tried to implement one and I got an error saying that
it required three arguments. It did, but only because the first was
self. I put the function inside my card class:
 def __eq__(self, card1, card2):
  return(card1.rank==card2.rank)
 #end def __eq__
For some reason it is still looking for three arguments...


On 8/4/10, Huy Ton That  wrote:
> You could write __str__ function
>
>>>> class card(object):
> ... def __init__(self, card1, card2):
> ... self.card1, self.card2 = card1, card2
> ... def __str__(self):
> ... return str(str(self.card1)+','+str(self.card2))
> ...
>>>> a = card(0,0)
>>>> str(a)
> '0,0'
>
> On Wed, Aug 4, 2010 at 10:37 AM, Alex Hall  wrote:
>
>> Hi all,
>> I have a card class. A card object simply consists of a pair of
>> numbers; 0,0 might be the ace of clubs, for example. I have a toString
>> method in my card class. Is there a way to just say str(card) instead
>> of card.toString()? Maybe some sort of basic, built-in function to
>> override? TIA. Oh, what about doing the same with operators? For
>> example, could I get the program to call my own math functions when it
>> sees a card object in a math expression, like
>> if(card1==card2)
>>
>> --
>> Have a great day,
>> Alex (msg sent from GMail website)
>> mehg...@gmail.com; http://www.facebook.com/mehgcap
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to get str() to use my function?

2010-08-04 Thread Alex Hall
Thanks, and I also see what I did wrong with my __eq__ function.

On 8/4/10, Huy Ton That  wrote:
> These are special method names.
>
> View section 3.4 and below here
>
> http://docs.python.org/reference/datamodel.html
>
> On Wed, Aug 4, 2010 at 11:37 AM, Alex Hall  wrote:
>
>> It worked, thanks. Is there a list of these functions somewhere? That
>> is, the functions that map implicitly to operators or implied uses?
>> For example, printing will call __str__, as will a cal to str(). What
>> about math or comparison operators? I have heard of __eq__, __gt__,
>> and so on, but I tried to implement one and I got an error saying that
>> it required three arguments. It did, but only because the first was
>> self. I put the function inside my card class:
>>  def __eq__(self, card1, card2):
>>  return(card1.rank==card2.rank)
>>  #end def __eq__
>> For some reason it is still looking for three arguments...
>>
>>
>> On 8/4/10, Huy Ton That  wrote:
>> > You could write __str__ function
>> >
>> >>>> class card(object):
>> > ... def __init__(self, card1, card2):
>> > ... self.card1, self.card2 = card1, card2
>> > ... def __str__(self):
>> > ... return str(str(self.card1)+','+str(self.card2))
>> > ...
>> >>>> a = card(0,0)
>> >>>> str(a)
>> > '0,0'
>> >
>> > On Wed, Aug 4, 2010 at 10:37 AM, Alex Hall  wrote:
>> >
>> >> Hi all,
>> >> I have a card class. A card object simply consists of a pair of
>> >> numbers; 0,0 might be the ace of clubs, for example. I have a toString
>> >> method in my card class. Is there a way to just say str(card) instead
>> >> of card.toString()? Maybe some sort of basic, built-in function to
>> >> override? TIA. Oh, what about doing the same with operators? For
>> >> example, could I get the program to call my own math functions when it
>> >> sees a card object in a math expression, like
>> >> if(card1==card2)
>> >>
>> >> --
>> >> Have a great day,
>> >> Alex (msg sent from GMail website)
>> >> mehg...@gmail.com; http://www.facebook.com/mehgcap
>> >> ___
>> >> Tutor maillist  -  Tutor@python.org
>> >> To unsubscribe or change subscription options:
>> >> http://mail.python.org/mailman/listinfo/tutor
>> >>
>> >
>>
>>
>> --
>> Have a great day,
>> Alex (msg sent from GMail website)
>> mehg...@gmail.com; http://www.facebook.com/mehgcap
>>
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] access class through indexing?

2010-08-04 Thread Alex Hall
Hi all,
Further to my questions about overriding builtin methods earlier, how
would I make a class able to be accessed and changed using index
notation? For example, take the following:
deck=CardPile(52) #creates a new deck of cards
print(len(deck)) #prints 52, thanks to my __len__ function
for c in deck: print c #also works thanks to __iter__
print(deck[4]) #fails with a list index out of range error
How would I get the last one working? I tried __getattr__(self, i),
but it did not work. I want to be able to get an arbitrary item from
the "pile" of cards (which can be a deck, a hand, whatever), and/or
set an element. A "pile" is just a list of Card objects, so I would
only need to use sequence indexing, not mapping functions.

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] access class through indexing?

2010-08-04 Thread Alex Hall
On 8/4/10, Jerry Hill  wrote:
> On Wed, Aug 4, 2010 at 4:17 PM, Alex Hall  wrote:
>
>> Hi all,
>> Further to my questions about overriding builtin methods earlier, how
>> would I make a class able to be accessed and changed using index
>> notation? For example, take the following:
>> deck=CardPile(52) #creates a new deck of cards
>> print(len(deck)) #prints 52, thanks to my __len__ function
>> for c in deck: print c #also works thanks to __iter__
>> print(deck[4]) #fails with a list index out of range error
>> How would I get the last one working? I tried __getattr__(self, i),
>> but it did not work. I want to be able to get an arbitrary item from
>> the "pile" of cards (which can be a deck, a hand, whatever), and/or
>> set an element. A "pile" is just a list of Card objects, so I would
>> only need to use sequence indexing, not mapping functions.
>>
>
> Implement __getitem__(self, key) (See
> http://docs.python.org/reference/datamodel.html#emulating-container-types )
>
> If you want to support slicing (access like deck[0:10]), you'll need to
> handle getting a slice object as the key in addition to accepting an integer
> key.
>
> If a pile is really "just" a list of cards, you may want to look into
> inheriting from list instead of re-implementing all of the functionality on
> your own.
I tried this first, by typing
class Pile(list):
Doing this does not seem to work, though, since creating a pile of
size 52 results in a list of size 0, unless I include the __len__
function. I thought putting (list) in my class definition would
automatically give me the functions of a list as well as anything I
wanted to implement, but that does not seem to be the case.

>
> --
> Jerry
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] access class through indexing?

2010-08-04 Thread Alex Hall
On 8/4/10, Evert Rol  wrote:
 Further to my questions about overriding builtin methods earlier, how
 would I make a class able to be accessed and changed using index
 notation? For example, take the following:
 deck=CardPile(52) #creates a new deck of cards
 print(len(deck)) #prints 52, thanks to my __len__ function
 for c in deck: print c #also works thanks to __iter__
 print(deck[4]) #fails with a list index out of range error
 How would I get the last one working? I tried __getattr__(self, i),
 but it did not work. I want to be able to get an arbitrary item from
 the "pile" of cards (which can be a deck, a hand, whatever), and/or
 set an element. A "pile" is just a list of Card objects, so I would
 only need to use sequence indexing, not mapping functions.

>>>
>>> Implement __getitem__(self, key) (See
>>> http://docs.python.org/reference/datamodel.html#emulating-container-types
>>> )
>>>
>>> If you want to support slicing (access like deck[0:10]), you'll need to
>>> handle getting a slice object as the key in addition to accepting an
>>> integer
>>> key.
>>>
>>> If a pile is really "just" a list of cards, you may want to look into
>>> inheriting from list instead of re-implementing all of the functionality
>>> on
>>> your own.
>> I tried this first, by typing
>> class Pile(list):
>> Doing this does not seem to work, though, since creating a pile of
>> size 52 results in a list of size 0, unless I include the __len__
>> function. I thought putting (list) in my class definition would
>> automatically give me the functions of a list as well as anything I
>> wanted to implement, but that does not seem to be the case.
>
> That depends how you create the Pile of 52 cards: list(52) also doesn't
> generate 52 (random) items.
> If you override __init__ to accept an integer that generates the cards for
> you, this should work.
Here is my init, not half as pretty as yours, but it should work.
Maybe this will explain the problem.

def __init__(self, size, cards=None, fill=False):
  #creates a pile of cards. If "fill"==true, it will auto-fill the
pile starting from the Ace of Clubs up through the King of Spades,
stopping if it exceeds the size arg.
  #if the cards arg is not null, it will populate the pile with the
cards in the list.
  self=[]
  if fill: #auto-fill, useful to generate a new, unshuffled deck
   for i in range(1, 14):
for j in range(1, 5):
 self.append(Card(i, j))
#end for
   #end for
   self=self[:size] #keep only the amount specified
  elif cards is not None: #fill the pile with the cards
   for c in cards:
self.append(c)
   #end for
  #end if
 #end def __init__


> Something like:
>
> class Pile(list):
> def __init__(self, *args, **kwargs):
> if len(args) == 1 and isinstance(args[0], (int, long)):
> args = ([Card(i) for i in xrange(args[0])],)
> super(Pile, self).__init__(*args, **kwargs)
Why call super here, if it is already my own __init__?
>
> allows things like Pile(52), Pile([card1, card2, card3]), Pile(12)[0:3] etc.
Again, my init is not nearly so fancy, and I will have to look hard at
what you did to understand it, but they are the same in terms of class
structure/inheriting list attributes as far as I can see, except the
call to the super.__init__ method.
>
> Cheers,
>
>   Evert
>
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] access class through indexing?

2010-08-04 Thread Alex Hall
On 8/4/10, Dave Angel  wrote:
> Alex Hall wrote:
>> On 8/4/10, Evert Rol  wrote:
>>
>>> 
>>> That depends how you create the Pile of 52 cards: list(52) also doesn't
>>> generate 52 (random) items.
>>> If you override __init__ to accept an integer that generates the cards
>>> for
>>> you, this should work.
>>>
>> Here is my init, not half as pretty as yours, but it should work.
>> Maybe this will explain the problem.
>>
>> def __init__(self, size, cards=None, fill=False):
>>   #creates a pile of cards. If "fill"==true, it will auto-fill the
>> pile starting from the Ace of Clubs up through the King of Spades,
>> stopping if it exceeds the size arg.
>>   #if the cards arg is not null, it will populate the pile with the
>> cards in the list.
>>   self=[]
>>   if fill: #auto-fill, useful to generate a new, unshuffled deck
>>for i in range(1, 14):
>> for j in range(1, 5):
>>  self.append(Card(i, j))
>> #end for
>>#end for
>>self=self[:size] #keep only the amount specified
>>   elif cards is not None: #fill the pile with the cards
>>for c in cards:
>> self.append(c)
>>#end for
>>   #end if
>>  #end def __init__
>>
>>
>>
> You have two serious problems here, and maybe others, I didn't keep looking.
>
> Since you never call super(), the init of the base class never happens.
> It may happen to work, since you're apparently willing to take its
> default behavior, but I don't know.  But even worse, you never even talk
> to your own object.  The first parameter to __init__() is a ref to the
> actual object you're supposed to be initializing, and you immediately
> overwrite it (self) with another object.  As a result, everything else
> you do in that method is thrown out when the method returns.  Remove
> that line
>
> self = []
That makes sense, and doing so has fixed everything. I am still not
clear on the whole super() thing; I saw it in another project and
tried to find out about it, but what I found was very confusing, and
super() did not seem terribly important, so I did not pursue the
matter further. Apparently it is important...
>
> DaveA
>
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] flow problem with a exercise

2010-08-19 Thread Alex Hall
On 8/19/10, Roelof Wobben  wrote:
>
> Hello,
>
>
>
> I have this exercise:
>
>
>
> Now write the function is_odd(n) that returns True when n is odd and False
> otherwise. Include doctests for this function as you write it.
> Finally, modify it so that it uses a call to is_even to determine if its
> argument is an odd integer.
>
>
>
> So I thought of this :
>
>
>
> def is_even(argument):
> remainder= argument%2
> if remainder == 0 :
> return True
> else :
> return False
>
>
> def is_odd(argument):
>   uitkomst=is_even(argument)
> return uitkomst
The above line, the return statement, has to be indented; it did not
appear to be in your email. Also, maybe you want to return the
opposite of is_even in is_odd? Right now it looks like you are going
to get something like:
is_odd(3): is_even(3)=False, so is_odd(3) will echo that False. Maybe
return !uitkomst instead. I could have read it wrong, though.

>
>
> even=is_odd(1) ;
> if even==True :
>   print "Even getal"
> if even==False:
> print "Oneven getal"
>
>
>
> But now I get this error message :
>
>
>
> return uitkomst
>
> Syntax error : return outside function.
>
>
>
>
>
> In my opinon even calls is_odd , then uitkomst calls is_even which gives a
> true or false to uitkomst. So return uitkomst gives the outcome to even.
>
> But the intepreter thinks otherwise.
>
>
>
> I work on a Win7 machine with Python 2.7
>
>
>
> Roelof
>
>
>   


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] design of Point class

2010-08-20 Thread Alex Hall
On 8/20/10, Gregory, Matthew  wrote:
> Hi all,
>
> I often struggle with object design and inheritance.  I'd like opinions on
> how best to design a Point class to be used in multiple circumstances.
>
> I typically deal with geographic (either 2D or 3D) data, yet there are
> occasions when I need n-dimensional points as well.  My thought was to
> create a superclass which was an n-dimensional point and then subclass that
> to 2- and 3-dimensional cases.  The rub to this is that in the n-dimensional
> case, it probably makes most sense to store the actual coordinates as a list
> whereas with the 2- and 3-D cases, I would want 'named' variables, such as
> x, y, z.
>
> Here's a (very rough) first cut at the constructor and a generic distance
> function for the n-dimensional case:
>
> class PointND(object):
> def __init__(self, a_list):
> self.a_list = a_list[:]
>
> def distance(self, right):
> assert(len(self.coord) == len(right))
> squared_diffs = [(i-j)*(i-j) for (i,j) in zip(self.coord, right)]
> return math.sqrt(sum(squared_diffs))
>
> But how can I subclass this in such a way to be able to:
>
> 1) Have named variables in the 2- and 3-D cases
I assume you will have separate subclasses for both 2d and 3d, so just
set up each subclass's __init__ to accept the proper amount and order
of arguments.
> 2) Be able to initialize with separate passed values, e.g. 'p = Point2D(3.0,
> 5.0)'
>rather than passing in a list
class 2dPoint(point):
  def __init__(self, x, y):
self.x=x
self.y=y
self.points=[x,y]

>
> Or am I totally off on thinking this is a good place for inheritance?
I would use subclassing. Designed right, this gives you access to
common functions like distance but also lets you customize each
subclass with specific methods unique to that subclass. Just my 2
cents, though, and I am not too experienced here.
>
> Thanks for any help,
> matt
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] input problem

2010-08-22 Thread Alex Hall
On 8/22/10, Roelof Wobben  wrote:
>
> Hello,
>
>
>
> I made this programm :
>
>
>
> def count_letters(n,a):
> count = 0
> for char in n:
> if char == a:
> count += 1
> return count
>
> fruit=""
> letter=""
> fruit= input("Enter a sort of fruit: ")
> teller = input("Enter the character which must be counted: ")
> x=count_letters (fruit,letter)
> print "De letter", letter , "komt", x , "maal voor in het woord", fruit
>
>
>
> The problem is that I can't have the opportuntity for input anything.
Try replacing the two lines where you say "input" with "raw_input" and
see if that works.
>
> I use python 2.7 on a Win7 machine with as editor SPE.
>
>
>
> Roelof
>
>
>   


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] args to functions in a dictionary?

2010-08-25 Thread Alex Hall
Hi all,
If I wanted to have a dictionary containing functions, could I pass
args to those functions? For example:
menu={
 "option 1":f1,
 "option 2":f2
}
How would I pass args to f1 or f2 in this case? TIA.

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] args to functions in a dictionary?

2010-08-25 Thread Alex Hall
On 8/25/10, Wayne Werner  wrote:
> On Wed, Aug 25, 2010 at 4:58 PM, Alex Hall  wrote:
>
>> Hi all,
>> If I wanted to have a dictionary containing functions, could I pass
>> args to those functions? For example:
>> menu={
>>  "option 1":f1,
>>  "option 2":f2
>> }
>> How would I pass args to f1 or f2 in this case? TIA.
>
>
> You sure could, because functions are first order citizens in python,
> meaning you can pass them around like any other data type.
>
> menu['option 1']() is how you would call the functions, and you'd just put
> an args/kwargs in the parenthesis.
Of course! So simple, yet somehow I did not see it. Thanks!
>
> Conceptually you can replace menu['option 1'] with f1, so anywhere you see
> this:
>
> menu['option 1'](arg1)
>
> you can replace it with
>
> f1(arg1)
>
> I don't know if Python does that exact thing on the back end, but the end
> result is certainly the same.
>
> HTH,
> Wayne
>
> (p.s. Gmail's undo sending feature is terribly nice when I forget to
> reply-all)
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Trouble with exercise regarding classes

2010-08-25 Thread Alex Hall
On 8/25/10, Andrew Martin  wrote:
> All I want to do is add a line that displays that maximum height the
> cannonball reaches. I created a variable zenith to store the highest y
> value. I then wanted to compare the current y value of the cannonball to
> zenith while the cannonballs y value is greater than zero. If the
> cannonballs current y value is greater than zenith, I want to have the
> current value replace zenith. Finally, once the cannonball has reaches y =
> 0, I wanted the program to write out the value for zenith.
>
> I want to compare zenith, a floating point number, with the current y value?
> I thought the current y value could be retrieved by Projectile.getY. And how
It can, but you need parentheses after the function call.
> do I call the getY using the instance?
I think the problem may be where you say
ball.getY
instead of
ball.getY()
When you hear "instance", do not panic. An instance is just a variable
of type class. For example, "ball" is an instance of the Projectile
class. As an example, if I had a "pet" class, I might make a "dog"
variable of type pet:
dog=Pet()
After I have my dog set up, since it is an instance of the Pet class,
it has all the methods available in the Pet class. I might say
dog.speak()
which would just look at my Pet class for a "speak" method, and call
it. In the same way, you have a "ball" variable which is  a
Projectile, so you have all the methods and variables from the
Projectile class available in the "ball" variable. Note that, if a
variable is of type class, it is also called an object, so I could
have as easily called the "ball" a Projectile object.
>
>
>
> On Wed, Aug 25, 2010 at 7:24 PM, Alan Gauld
> wrote:
>
>>
>> "Andrew Martin"  wrote
>>
>>
>>  However, when I did so I got this error: "TypeError: unbound method
>> getY()
>>> must be called with Projectile instance as first argument (got nothing
>>> instead) "
>>>
>>
>>  def main():
angle, vel, h0, time = getInputs()
cball = Projectile(angle, vel, h0)

>>>
>> cball is a Projectile instance
>>
>>
>> zenith = 0.0
while cball.getY() >= 0:

>>>
>> So this is fine
>>
>>
>> cball.update(time)

>>>
>>
>> if Projectile.getY > zenith:
zenith = Projectile.getY()

>>>
>> But what are you doing here?
>> You are trying to compare the getY method of the class with a floating
>> point number?
>> Then you call getY using the class rather than the instance?
>> I'm confused - and so is Python...
>>
>>
>> --
>> Alan Gauld
>> 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
>>
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Giving a name to a function and calling it, rather than calling the function directly

2010-09-04 Thread Alex Hall
On 9/4/10, lists  wrote:
> Hi folks,
>
> I'm new to Python, I'm working my way through some intro books, and I
> have a question that I wonder if someone could help me with please?
>
> This is my attempt at solving an exercise where the program is
> supposed to flip a coin 100 times and then tell you the number of
> heads and tails.
>
> ATTEMPT 1 returns:
>
> The coin landed on tails 100 times
>
> The coin landed on heads 0 times
>
> ATTEMPT 2 returns:
>
> The coin landed on tails 75 times
>
> The coin landed on heads 25 times
>
> I expected to see the result in attempt 2. I don't fully understand
> why the results are different however. Is it because Python only runs
> the randint function once when I call it by the name I assigned to it
> in attempt 1, but it runs the function fully on each iteration of the
> loop in attempt 2? Why are these two things different?
Exactly. Essentially when you say
x=random.randint(1,2)
you are putting the value returned by randint into x, and this happens
only once. Had you moved that assignment into the while loop it would
keep replacing x, or toss in your case, with a random integer, but
because you just call it once it is only assigned once. Python, or any
language, would have no way of knowing that you want to reassign toss
each time. Loops are used to repeat actions, but you left the
assignment of your random int outside of the loop in attempt1 and so
there is no way for Python to know that you actually want toss updated
100 times. I hope I explained this okay.
>
> Thanks in advance,
>
> Chris
> --
> ATTEMPT 1
> --
> import random
>
> heads = 0
> tails = 0
> tossNo = 0
> toss = random.randint(1,2)
>
> while tossNo <= 99:
> if toss == 1:
> heads += 1
> tossNo += 1
> elif toss == 2:
>  tails += 1
>  tossNo += 1
>
> print "The coin landed on tails " + str(tails) + " times \n"
> print "The coin landed on heads " + str(heads) + " times \n"
>
> --
> ATTEMPT 2
> --
> import random
>
> heads = 0
> tails = 0
> tossNo = 0
>
> while tossNo <= 99:
> if random.randint(1,2) == 1:
> heads += 1
> tossNo += 1
> elif random.randint(1,2) == 2:
>  tails += 1
>  tossNo += 1
>
> print "The coin landed on tails " + str(tails) + " times \n"
> print "The coin landed on heads " + str(heads) + " times \n"
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] list dll functions?

2010-09-14 Thread Alex Hall
Hi all,
Out of curiosity: I know I can call dll functions from python using
the win32 lib, but is there any way to simply "examine" a loaded dll
to see all of the functions and attributes it exposes for use? I would
do no good with a hex editor since I have no idea what all the numbers
mean, so I am hoping for a plaintext representation of a dll's
possibilities and am most comfortable in Python. I am running the
latest 2.6 on win7. TIA.

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list dll functions?

2010-09-14 Thread Alex Hall
On 9/14/10, R. Alan Monroe  wrote:
>> the win32 lib, but is there any way to simply "examine" a loaded dll
>> to see all of the functions and attributes it exposes for use? I would
>
> http://www.dependencywalker.com/
A great program, thanks! Best of all, for me anyway, it works well (so
far) with JAWS, my screen reader. It is increasingly rare to find
fully accessible programs nowadays, and I am glad that this one works.
Now I just have to figure out how to see the expected arguments of a
function, but I am sure that is in the manual somewhere...
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why are arguments sometimes on the left side?

2010-09-20 Thread Alex Hall
On 9/20/10, Michael Scharf  wrote:
> Hi,
>
>
> Why is it
>
>
>
>list0.extend(list1)
>
>
>
> and not
>
>
>extend(list 0, list1)
>
>
>
> or
>
>
>stri0 = stri0.strip()
>
>
> and not
>
>
>stri0 = strip(stri0)

This is because you are calling methods on objects, in this case
strings and lists. You create a list, then want to extend it with
another list. Think of it as operating on list0, so, to operate on it,
you call one of its functions (extend). Some functions do not work
this way, such as print, since print is not a function under an object
or class. If I create a dog class, then create Fluffy as an object:
class dog(object):
 def __init__(self, name):
  self.name=name
 def bark(self):
  print("bark")

f=dog("Fluffy")

Okay, we now have a dog named Fluffy, which is just one instance of
our dog class. With the way you would want to do things, I would have
to say
bark(f)
But what is bark? Where is it defined? You can see it is in the dog
class, but Python cannot; you passed a dog instance to bark(), but
that will not tell Python to search in the dog class to find the bark
method. Saying
f.bark()
will work since it tells Python:
take this instance of dog, called f, and call its bark method. The
bark method is in the dog class since bark is being called on a dog
object (remember that an object is just an instance of a class).
I hope this made some sense.
>
>
>
> Why have arguments on the left side at all, when usually the dot notation
> left to right implies a hierarchical relation: file.class or class.method
> etc.
Exactly: list.function (such as list0.extend) is just the same as
class.function, since a list is a class and list0 is an instance of
the list class, so you are just calling list's extend function on a
particular list, list0 in this case.
>
>
>
> I googled this, but didn’t find it.
>
>
>
> Thank you,
>
> Mike
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] functions: use return or exceptions?

2010-09-23 Thread Alex Hall
Hi all,
A general coding question: is it better to use return(False) (or 0, or
-1, or whatever) or to raise whateverError("oops")? Are there cases
for each?

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] functions: use return or exceptions?

2010-09-23 Thread Alex Hall
Thanks for the responses. Up to now, despite using some Java and a lot
of Python, I have not even tried raising exceptions. I can see
situations where they would be useful, but was not sure if I should
use them as much as possible or just keep relying on the return codes
that I am used to. Sounds like either way works and, as was stated,
exceptions should be used in "exceptional" cases.

On 9/23/10, Luke Paireepinart  wrote:
> You should do both. Raise an exception in the exceptional case.
>
> My general pattern is to return None if no results exist, return the results
> if they do exist, and raise an exception if I couldn't perform the function.
>
> Eg. If I have a function that creates a list of users with a first name of
> bob, I'll return the users or None (or probably an empty list) but if the db
> connection is unsuccessful I'll let the exception it throws propagate back
> up from my function, or possibly trap and rethrow the exception.
>
> Or if a db connection error shouldn't matter to the calling function, I just
> won't re raise the exception.
>
> I may not actually do that in practice, depending on the implications, but
> that's my general idea usually.
>
> -
> Sent from a mobile device with a bad e-mail client.
> -
>
> On Sep 23, 2010, at 2:47 PM, Wayne Werner  wrote:
>
>> On Thu, Sep 23, 2010 at 2:32 PM, Alex Hall  wrote:
>> Hi all,
>> A general coding question: is it better to use return(False) (or 0, or
>> -1, or whatever) or to raise whateverError("oops")? Are there cases
>> for each?
>>
>> It depends on your prevailing philosophy - if you like the EAFP that
>> prevails in python, it's better to raise an error. Usually that indicates
>> that something has failed.
>>
>> OTOH, a lot of people feel that using exceptions as control flow is bad
>> practice - they're exceptional so they should only arise in exceptional
>> case.
>>
>> There may be performance issues, though I'm not familiar enough with that
>> yet.
>>
>> just my two bits,
>> -Wayne
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] dynamic arrays?

2010-09-27 Thread Alex Hall
Hi all,
One thing I have never much liked about Python is its need for
specifically sized arrays and lack of a dynamic, array-like data
structure. For example, the following fails with a "list assignment
index out of range" error:

a=[]
i=0
for l in open("file.txt", "r"):
  a[i]=l
   i+=1

Is there something in Python I am missing that would let the above
work? I am hoping that my annoyance at the apparent lack of such a
thing is unfounded. BTW, I know why the above throws that exception.
TIA.

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dynamic arrays?

2010-09-27 Thread Alex Hall
On 9/27/10, Brian Jones  wrote:
> On Mon, Sep 27, 2010 at 11:32 AM, Alex Hall  wrote:
>
>> Hi all,
>> One thing I have never much liked about Python is its need for
>> specifically sized arrays and lack of a dynamic, array-like data
>> structure. For example, the following fails with a "list assignment
>> index out of range" error:
>>
>> a=[]
>> i=0
>> for l in open("file.txt", "r"):
>>  a[i]=l
>>   i+=1
>>
>
> Is there some reason to use this construct rather than the list object's
> 'append' method?
>
> for i in open('file.txt', 'r'):
> a.append(l)

Ah, good thought. So exactly what are the functional differences
between a list and an array in Python, or are they so close that it
makes no difference which you use? It seems like you can index into
both with the bracket notation. Are lists limited in any way that
makes them not as desirable as arrays?
>
> brian
>
>>
>> Is there something in Python I am missing that would let the above
>> work? I am hoping that my annoyance at the apparent lack of such a
>> thing is unfounded. BTW, I know why the above throws that exception.
>> TIA.
>>
>> --
>> Have a great day,
>> Alex (msg sent from GMail website)
>> mehg...@gmail.com; http://www.facebook.com/mehgcap
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
>
>
> --
> Brian K. Jones
> My Blog  http://www.protocolostomy.com
> Follow me  http://twitter.com/bkjones
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dynamic arrays?

2010-09-27 Thread Alex Hall
On 9/27/10, Brian Jones  wrote:
> On Mon, Sep 27, 2010 at 11:39 AM, Alex Hall  wrote:
>
>> On 9/27/10, Brian Jones  wrote:
>> > On Mon, Sep 27, 2010 at 11:32 AM, Alex Hall  wrote:
>> >
>> >> Hi all,
>> >> One thing I have never much liked about Python is its need for
>> >> specifically sized arrays and lack of a dynamic, array-like data
>> >> structure. For example, the following fails with a "list assignment
>> >> index out of range" error:
>> >>
>> >> a=[]
>> >> i=0
>> >> for l in open("file.txt", "r"):
>> >>  a[i]=l
>> >>   i+=1
>> >>
>> >
>> > Is there some reason to use this construct rather than the list object's
>> > 'append' method?
>> >
>> > for i in open('file.txt', 'r'):
>> > a.append(l)
>>
>> Ah, good thought. So exactly what are the functional differences
>> between a list and an array in Python, or are they so close that it
>> makes no difference which you use? It seems like you can index into
>> both with the bracket notation. Are lists limited in any way that
>> makes them not as desirable as arrays?
>>
>
> A python list and a python array are one and the same to my knowledge. Do
> you mean a list and a dict? A dict is an unordered collection of key-value
> pairs, and the keys are more or less arbitrary values of your own creation
> (I believe the single limitation is the key must be a hashable type). A list
> is a 'flat' array, although you can use enumerate(l) to get index->value
> pairs from a list 'l'.
Oh. Somehow I never made the connection that arrays and lists are the
same. :) No, I was not thinking of a dictionary in this case, though I
will have to look into that enumerate function. Thanks for clearing
this up.
>
> hth.
>
>
>
>> >
>> > brian
>> >
>> >>
>> >> Is there something in Python I am missing that would let the above
>> >> work? I am hoping that my annoyance at the apparent lack of such a
>> >> thing is unfounded. BTW, I know why the above throws that exception.
>> >> TIA.
>> >>
>> >> --
>> >> Have a great day,
>> >> Alex (msg sent from GMail website)
>> >> mehg...@gmail.com; http://www.facebook.com/mehgcap
>> >> ___
>> >> Tutor maillist  -  Tutor@python.org
>> >> To unsubscribe or change subscription options:
>> >> http://mail.python.org/mailman/listinfo/tutor
>> >>
>> >
>> >
>> >
>> > --
>> > Brian K. Jones
>> > My Blog  http://www.protocolostomy.com
>> > Follow me  http://twitter.com/bkjones
>> >
>>
>>
>> --
>> Have a great day,
>> Alex (msg sent from GMail website)
>> mehg...@gmail.com; http://www.facebook.com/mehgcap
>>
>
>
>
> --
> Brian K. Jones
> My Blog  http://www.protocolostomy.com
> Follow me  http://twitter.com/bkjones
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] filling 2d array with zeros

2010-09-27 Thread Alex Hall
Hi again everyone,
I have a 2d array (I guess it is technically a list) which I want to
fill with zeros. Later I will change some values, but any I do not
change have to be zeros. I have two complex for loops, but I tried to
scale things down to a couple list comprehensions and I broke things.
What is wrong with the following line?
self.am=[[(a,b) for a in range(len(self.lines)) a=0] for b in
range(len(self.lines)) b=0]

self.lines is another array that tells self.am how big to get, but no
matter the size, all created cells of the self.am 2d array should end
up with a value of 0. I barely understand list comprehensions as it is
so am not sure what I did wrong here. I adapted this from a working
example that fills a 2d array with numbers.

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] filling 2d array with zeros

2010-09-27 Thread Alex Hall
On 9/27/10, Steven D'Aprano  wrote:
> On Tue, 28 Sep 2010 03:54:55 am Alex Hall wrote:
>> Hi again everyone,
>> I have a 2d array (I guess it is technically a list) which I want to
>> fill with zeros. Later I will change some values, but any I do not
>> change have to be zeros. I have two complex for loops, but I tried to
>> scale things down to a couple list comprehensions and I broke things.
>> What is wrong with the following line?
>> self.am=[[(a,b) for a in range(len(self.lines)) a=0] for b in
>> range(len(self.lines)) b=0]
>
>
> Start with a single row, of n columns:
>
> [0 for i in range(n)]  # the loop variable i is not used
>
> Now all you need is to set n appropriately:
>
> n = len(self.lines)
> [0 for i in range(n)]
>
>
> Is there an easier way? Yes, you don't even need a list comp:
>
> [0]*n
>
> Now make m rows of the same:
>
> [ [0]*n for i in range(m) ]
That worked, and I think I see what is going on.
>
> And you are done.
>
>
> You might be tempted to take a short-cut:
>
> [ [0]*n ]*m
>
> but this doesn't work as you expect. This is one of the rare Python
> gotchas -- it looks like it should work, but it doesn't behave like you
> might expect. Try it and see:
>
>>>> a = [[0]*3]*4
>>>> a
> [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>>> a[0][1] = 2
>>>> a
> [[0, 2, 0], [0, 2, 0], [0, 2, 0], [0, 2, 0]]
>
> What's going on here? It's a little complicated, so let's start with a
> simpler situation:
>
>>>> b = [0, 0, 0]
>>>> c = b  # c is an alias to the same list as b
>>>> d = b  # so is d
>>>> e = c  # and e
>>>> b[0] = 3
>>>> e
> [3, 0, 0]
>
> Because both b and e refer to the same list (not copies!) any change to
> b *must* also change e. It's like if Barack Obama gets a haircut, so
> does the current President of the USA, because they're the same person.
>
> Now stick them in a list:
>
>>>> a = [b, c, d, e]
>>>> a
> [[3, 0, 0], [3, 0, 0], [3, 0, 0], [3, 0, 0]]
>>>> a[0][1] = 4
>>>> a
> [[3, 4, 0], [3, 4, 0], [3, 4, 0], [3, 4, 0]]
>
> Modify one, modify them all, because in fact they are actually all the
> same list.
>
> [ [0]*3 ]*4 behaves the same way. There's no problem in the inner list,
> but the outer list doesn't make four copies of [0,0,0], it has *one*
> list repeated four times. Modify one, modify them all.
That makes sense. Basically, the * operator in this case acts as a
copying command. For simple data types this is fine, but throw in a
complex type, in this case a list (though I expect that any object
would do this) and you are just doing what Python does to copy
objects: copying the memory location, not making a deep copy and
getting a duplicate object. I never would have thought of that. Thanks
again for the great explanation!
>
>
> --
> Steven D'Aprano
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] filling 2d array with zeros

2010-09-27 Thread Alex Hall
On 9/27/10, Sander Sweers  wrote:
> On 27 September 2010 23:15, Sander Sweers  wrote:
>>> objects: copying the memory location, not making a deep copy and
>>> getting a duplicate object.
>>
>> It does not copy the object it makes multiple _references_ to the *same*
>> object.
>
> Oops, You already got the idea and I should have read better. Ow well,
> maybe the copy module was of interest to you.
Yes, very much. I never even knew such a module existed, and I had
wondered, through all of this, what would happen when a deep copy was
required. Now I know. :)
>
> Greets
> Sander
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] filling 2d array with zeros

2010-09-27 Thread Alex Hall
On 9/27/10, Steven D'Aprano  wrote:
> On Tue, 28 Sep 2010 06:00:41 am Alex Hall wrote:
>> > [ [0]*3 ]*4 behaves the same way. There's no problem in the inner
>> > list, but the outer list doesn't make four copies of [0,0,0], it
>> > has *one* list repeated four times. Modify one, modify them all.
>>
>> That makes sense. Basically, the * operator in this case acts as a
>> copying command. For simple data types this is fine, but throw in a
>> complex type, in this case a list (though I expect that any object
>> would do this) and you are just doing what Python does to copy
>> objects: copying the memory location, not making a deep copy and
>> getting a duplicate object. I never would have thought of that.
>> Thanks again for the great explanation!
>
> No, be careful about your terminology. I get that you understand what is
> going on, but you're saying it wrong. The * operator doesn't make
> copies. I know it's tempting to say it does, sometimes I catch myself
> saying so myself, but what Python is doing is making multiple
> references to the same object. The object is not copied.
Yes; the object stays put, the object's memory location (pointer) is
copied. I have just enough c++ and theory to get this, and enough to
be scared of it and very thankful that Python deals with it for me
instead of me needing all those ampersand and star operators in front
of variables... That was a nightmare, and I came running back to my
high-level languages in a hurry. :)
>
> It may be easier if you think about the underlying C implementation
> (under the hood, in the engine) rather than the Python level. At the
> Python level, objects can be in multiple places at once. Objects like
> lists can even be inside themselves:
>
>>>> L = []
>>>> L.append(L)
>
> If you've watched Doctor Who as a child, and seen his TARDIS (which of
> course is bigger on the inside than the outside) land inside itself,
> such strange loops won't hold any fear for you at all :)
>
> But at the C level, Python doesn't make copies of any object unless
> necessary. The *name* L is a pointer to the list object. When you
> execute:
>
> L = []
>
> Python creates a name L which then points ("refers to") to a list
> object. When you next do this:
>
> L.append(L)
>
> Python doesn't move the list object into itself -- that would be a good
> trick. Besides, objects are big, complex chunks of memory and moving
> them around would be slow, so Python leaves the list where it is and
> simply places a pointer to L into the appropriate list position.
Makes sense, but I never thought of this as being possible, let alone
legal. Still, though I cannot imagine a situation where it would be
necessary, I am sure someone has used it somewhere. A very interesting
thing to think about; a single-element list holding... itself. Yep,
very interesting! Now I wish I were more of a sci fi buff. :)
>
> (But don't forget that Python is not necessarily written in C. There's
> Jython, written in Java, and CLPython written in Lisp, and many others.
> How they implement objects may be different. What happens under the
> hood isn't important, so long as the behaviour at the Python level
> remains the same.)
Really? Neat! I wonder what the advantage of doing that is, since the
end result, as you say, should be the same once you start writing
Python code?
>
> So at the Python level, there is never any copying of objects unless you
> specifically ask for it, and the * operator doesn't make any copies at
> all. It repeats the one object multiple times.
>
>
> --
> Steven D'Aprano
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] filling 2d array with zeros

2010-09-28 Thread Alex Hall
On 9/28/10, Steven D'Aprano  wrote:
> On Tue, 28 Sep 2010 11:56:33 am Alex Hall wrote:
>> > (But don't forget that Python is not necessarily written in C.
>> > There's Jython, written in Java, and CLPython written in Lisp, and
>> > many others. How they implement objects may be different. What
>> > happens under the hood isn't important, so long as the behaviour at
>> > the Python level remains the same.)
>>
>> Really? Neat! I wonder what the advantage of doing that is, since the
>> end result, as you say, should be the same once you start writing
>> Python code?
>
> Different implementations can make different choices, to suit different
> needs. So long as the end result is the same, they can choose different
> mechanisms, different techniques, radically different strategies, or
> simply choose a different implementation language because they can.
>
> CPython is a conservative implementation written in ordinary C so that
> it is available on almost any platform that has a C compiler.
> Efficiency is not its primary goal, clarity of code and simplicity of
> design is considered just as important. This is almost certainly the
> version you are using.
Probably, I just got 2.6 from python.org.
>
> Unladen Swallow is a version of CPython written by Google that aims to
> speed up certain time-critical parts. If it works, it may end up being
> merged with the regular CPython. Unfortunately, after a flash of
> publicity and some promising early results, Unladen Swallow seems to
> have gone quiet.
>
> PyPy is a version of Python written in Python. It has an incredible
> mission: to eventually produce versions of Python which are faster than
> pure C, despite being written in Python itself. Although they have a
> long, long way to go, they are making good progress, and PyPy can now
> run Python code faster than CPython. PyPy is becoming a generalised
> Just-In-Time compiler for high-level languages like Python.
Okay, I now have to go investigate this and see how it is even
possible; somewhere, the Python code has to get down to machine
code...
>
> IronPython and Jython are designed to integrate with Dot-Net and Java.
> IronPython is probably written in C#, like most Dot-Net software, and
> Jython is written in Java.
>
> Stackless Python is similar to CPython except it doesn't have a function
> call stack, which is good for certain specialist applications.
I'll take your word for it, but it seems like you could then not use
OO since a function's return would have no idea where to go. I was
once forced to try LISP, MIPS machine language, and a functionless
Basic, and I hated them.
>
> Pynie is an experimental version of Python written for the Parrot
> virtual machine used by Perl 6.
>
> CapPython is a restricted version of Python which aims to be much more
> secure, allowing you to safely run untrusted code without it eating
> your computer.
>
> And there are many more... I count at least 41 current or past Python
> implementations, add-ons and related projects. My favourite (apart from
> PyPy, which makes me feel all warm and tingly in that special place) is
> LikePython:
>
> http://www.staringispolite.com/likepython/
>
>
> #!usr/bin/python
> # My first Like, Python script!
> yo just print like "hello world" bro

...interesting. This, too, will have to be looked at, if only because
it is so different. Thanks for all the info!
>
>
> I can't wait to put that on my resume :)
>
>
>
>
> --
> Steven D'Aprano
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] filling 2d array with zeros

2010-09-28 Thread Alex Hall
On 9/28/10, Dave Angel  wrote:
>
>
> On 2:59 PM, Alex Hall wrote:
>> On 9/28/10, Steven D'Aprano  wrote:
>>> 
>>>
>>> PyPy is a version of Python written in Python. It has an incredible
>>> mission: to eventually produce versions of Python which are faster than
>>> pure C, despite being written in Python itself. Although they have a
>>> long, long way to go, they are making good progress, and PyPy can now
>>> run Python code faster than CPython. PyPy is becoming a generalised
>>> Just-In-Time compiler for high-level languages like Python.
>> Okay, I now have to go investigate this and see how it is even
>> possible; somewhere, the Python code has to get down to machine
>> code...
>>
> Just-in-time compiling  (JIT) is taking some high-level construct, such
> as python byte code or a java class file, and compiling it into machine
> code, at the time of first execution.  Java uses it heavily, to achieve
> its performance level.  The standard CPython does not, but simply
> interprets those byte codes.
>
> One advantage of just-in-time is that the translation can be specific to
> a particular processor, or even to a particular operating system and
> operating environment.  Conventional compiling is done by the developer,
> and he has to release multiple versions for multiple platforms.  And
> even then, he seldom takes advantage of the newer instructions of a
> given processor, which are changing quite frequently.  I'm sure there
> are at least a dozen different instruction supersets of the original
> Pentium processor, though most of the recent ones are relatively
> specialized (eg. for hashing, searching, encryption), and likely to
> affect libraries more than your main program.
Thanks for the info. That explains why Pypy said it only works on
Intel-based systems for the moment, and why special things must be
done for 64-bit processors.
>
> DaveA
>
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] using "in" with a dictionary

2010-09-28 Thread Alex Hall
Hi all, yet again:
I have a dictionary that will look something like:
d={
 (1,2):"a",
 (3,4):"b"
}

How can I say:
if (1,2) in d: print d[(1,2)]
This is false, so I expect to have to use d.keys, but I am not quite sure how.
I will be using this in a loop, and I have to know if there is a key
in the dictionary called (i,j) and, if there is, I have to grab the
value at that slot. If not I have to print something else. When I
tried "in" in the interpreter, I got something about builtin function
not being iterable. TIA for any suggestions.

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] just what does read() return?

2010-09-30 Thread Alex Hall
Hi all,
I have a parser class which is supposed to take a text file and parse
it. I will then do more with the resulting data. The file is in a
particular format, specified by my professor, though this is not
homework (it will be used to do homework later). The file is in the
format:
l
vx vy z
vx vy z

where l is either D or U and x, y, and z are numbers. Anyway, I have
the following lines:
  f=open(self.file, "r")
  self.original=f.read() #I thought self.original would now be a
string of all the data in self.file
  txt=str(self.original).split(r"\n+") #create an array where elements
are lines in file
  print txt

I fully expected to see txt be an array of strings since I figured
self.original would have been split on one or more new lines. It turns
out, though, that I get this instead:
['l\nvx vy z\nvx vy z']

How is it that txt is not an array of the lines in the file, but
instead still holds \n characters? I thought the manual said read()
returns a string:

"To read a file's contents, call  f.read(size), which reads some
quantity of data and returns it as a string. size is an optional
numeric argument. When size is omitted or negative, the entire
contents of the file will be read and returned; it's your problem if
the file is twice as large as your machine's memory. Otherwise, at
most size bytes are read and returned. If the end of the file has been
reached, f.read()
 will return an empty string ( ""). "

I know I can use f.readline(), and I was doing that before and it all
worked fine. However, I saw that I was reading the file twice and, in
the interest of good practice if I ever have this sort of project with
a huge file, I thought I would try to be more efficient and read it
once. I will use self.original later again, so I need it either way,
and I figured I could use it since I had already read the file to get
it. TIA.



-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] just what does read() return?

2010-09-30 Thread Alex Hall
On 9/30/10, Walter Prins  wrote:
> On 30 September 2010 23:32, Alex Hall  wrote:
>
>> txt=str(self.original).split(r"\n+") #create an array where elements
>>
>
> OK, consider this Python shell session:
>
>>>> s = "line1\nline2"
>>>> s.split()
> ['line1', 'line2']
>>>> s.split(r"\n+")
> ['line1\nline2']
>
> Hmm, so split doesn't like that seperator.
>
> Taking a step back -- It looks like you're trying to specify a regular
> expression as a split string.  A string object's split method doesn't
> support regular expressions.  The split function in the "re" module however
> does.
Ah-ha!!
re.split(r"\n+", self.original)
That did it, and my program once again runs as expected. Thanks!
>
> HTH
Very much.
>
> Walter
>
-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] just what does read() return?

2010-09-30 Thread Alex Hall
On 9/30/10, Steven D'Aprano  wrote:
> On Fri, 1 Oct 2010 08:32:40 am Alex Hall wrote:
>
>> I fully expected to see txt be an array of strings since I figured
>> self.original would have been split on one or more new lines. It
>> turns out, though, that I get this instead:
>> ['l\nvx vy z\nvx vy z']
>
> There's no need to call str() on something that already is a string.
> Admittedly it doesn't do much harm, but it is confusing for the person
> reading, who may be fooled into thinking that perhaps the argument
> wasn't a string in the first place.
Agreed. I was having some (unrelated) trouble and was desperate enough
to start forcing things to the data type I needed, just in case.
>
> The string split method doesn't interpret its argument as a regular
> expression. r'\n+' has no special meaning here. It's just three literal
> characters backslash, the letter n, and the plus sign. split() tries to
> split on that substring, and since your data doesn't include that
> combination anywhere, returns a list containing a single item:
>
>>>> "abcde".split("ZZZ")
> ['abcde']
Yes, that makes sense.
>
>> How is it that txt is not an array of the lines in the file, but
>> instead still holds \n characters? I thought the manual said read()
>> returns a string:
>
> It does return a string. It is a string including the newline
> characters.
>
>
> [...]
>> I know I can use f.readline(), and I was doing that before and it all
>> worked fine. However, I saw that I was reading the file twice and, in
>> the interest of good practice if I ever have this sort of project
>> with a huge file, I thought I would try to be more efficient and read
>> it once.
>
> You think that keeping a huge file in memory *all the time* is more
> efficient?
Ah, I see what you mean now. I work with the data later, so you are
saying that it would be better to just read the file as necessary,
then then, when I need the file's data later, just read it again.
> It's the other way around -- when dealing with *small* files
> you can afford to keep it in memory. When dealing with huge files, you
> need to re-write your program to deal with the file a piece at a time.
> (This is often a good strategy for small files as well, but it is
> essential for huge ones.)
>
> Of course, "small" and "huge" is relative to the technology of the day.
> I remember when 1MB was huge. These days, huge would mean gigabytes.
> Small would be anything under a few tens of megabytes.
>
>
> --
> Steven D'Aprano
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] regexp: a bit lost

2010-09-30 Thread Alex Hall
Hi, once again...
I have a regexp that I am trying to use to make sure a line matches the format:
[c*]n [c*]n n
where c* is (optionally) 0 or more non-numeric characters and n is any
numeric character. The spacing should not matter. These should pass:
v1 v2   5
2 someword7 3

while these should not:
word 2  3
1 2

Here is my test:
s=re.search(r"[\d+\s+\d+\s+\d]", l)
if s: #do stuff

However:
1. this seems to pass with *any* string, even when l is a single
character. This causes many problems and cannot happen since I have to
ignore any strings not formatted as described above. So if I have
for a in b:
  s=re.search(r"[\d+\s+\d+\s+\d]", l)
  if s: c.append(a)

then c will have every string in b, even if the string being examined
looks nothing like the pattern I am after.

2. How would I make my regexp able to match 0-n characters? I know to
use \D*, but I am not sure about brackets or parentheses for putting
the \D* into the parent expression (the \d\s one).

3. Once I get the above working, I will need a way of pulling the
characters out of the string and sticking them somewhere. For example,
if the string were
v9 v10 15
I would want an array:
n=[9, 10, 15]
but the array would be created from a regexp. This has to be possible,
but none of the manuals or tutorials on regexp say just how this is
done. Mentions are made of groups, but nothing explicit (to me at
least).

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] regexp: a bit lost

2010-10-01 Thread Alex Hall
On 10/1/10, Steven D'Aprano  wrote:
> On Fri, 1 Oct 2010 12:45:38 pm Alex Hall wrote:
>> Hi, once again...
>> I have a regexp that I am trying to use to make sure a line matches
>> the format: [c*]n [c*]n n
>> where c* is (optionally) 0 or more non-numeric characters and n is
>> any numeric character. The spacing should not matter. These should
>> pass: v1 v2   5
>> 2 someword7 3
>>
>> while these should not:
>> word 2  3
>> 1 2
>>
>> Here is my test:
>> s=re.search(r"[\d+\s+\d+\s+\d]", l)
>
> Try this instead:
>
> re.search(r'\d+\s+\D*\d+\s+\d', l)
>
> This searches for:
> one or more digits
> at least one whitespace char (space, tab, etc)
> zero or more non-digits
> at least one digit
> at least one whitespace
> exactly one digit
Makes sense.
>
>
>> However:
>> 1. this seems to pass with *any* string, even when l is a single
>> character. This causes many problems
> [...]
>
> I'm sure it does.
>
> You don't have to convince us that if the regular expression is broken,
> the rest of your code has a problem. That's a given. It's enough to
> know that the regex doesn't do what you need it to do.
Understood. My intent was to ask why my regexp would match anything at all.
>
>
>> 3. Once I get the above working, I will need a way of pulling the
>> characters out of the string and sticking them somewhere. For
>> example, if the string were
>> v9 v10 15
>> I would want an array:
>> n=[9, 10, 15]
>
>
> Modify the regex to be this:
>
> r'(\d+)\s+\D*(\d+)\s+(\d)'
>
> and then query the groups of the match object that is returned:
>
>>>> mo = re.search(r'(\d+)\s+\D*(\d+)\s+(\d)', 'spam42   eggs239')
>>>> mo.groups()
> ('42', '23', '9')
>
> Don't forget that mo will be None if the regex doesn't match, and don't
> forget that the items returned are strings.
Alright that worked perfectly, after a lot of calls to int()! I also
finally understand what a group is and, at a basic level, how to use
it. I have wondered how to extract matched text from a string for a
long time, and this has finally answered that. Thanks!
>
>
>
> --
> Steven D'Aprano
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] regexp: a bit lost

2010-10-01 Thread Alex Hall
On 10/1/10, Steven D'Aprano  wrote:
> On Sat, 2 Oct 2010 01:14:27 am Alex Hall wrote:
>> >> Here is my test:
>> >> s=re.search(r"[\d+\s+\d+\s+\d]", l)
>> >
>> > Try this instead:
>> >
>> > re.search(r'\d+\s+\D*\d+\s+\d', l)
> [...]
>> Understood. My intent was to ask why my regexp would match anything
>> at all.
>
> Square brackets create a character set, so your regex tests for a string
> that contains a single character matching a digit (\d), a plus sign (+)
> or a whitespace character (\s). The additional \d + \s in the square
> brackets are redundant and don't add anything.
Oh, that explains it then. :) Thanks.
>
> --
> Steven D'Aprano
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] trying it again: p2p for game

2010-10-14 Thread Alex Hall
Hi all,
Alright: after a few months letting it rest, I am trying this
Battleship thing again. I found a p2p library (attached) and have
tried to implement it (p2p.py). However, I am always getting the same
error: errno2: no connection could be made because the target machine
actively refused it.
I suspect my ip addresses are at fault. I am on a public network here
at school, and I keep getting 130... addresses. However, my friend
several cities away cannot use 130, since that is local, right? I am
not sure where to get my ip; that is, where to get an ip that, coupled
with the hard-coded port number, will let my computer connect to his
and vice versa. This does not work for two instances on my computer,
it does not work for my computer and my friend's (different networks),
and it does not work for my friend when he runs two computers on the
same network and tries to connect the two... always that same error
once we try to connect.
This library came with no documentation, and I suspect it was not
intended as a public release, but it is the only p2p file I could
find. I asked the professor here who taught networking, but she just
gave me some Microsoft pages on p2p (helpful for concepts, but not
Python-specific), and no one here knows Python well (CS is not a
popular degree here anyway, so there are not too many of us). If
anyone can spot what is going on, that would be wonderful. Sorry to
keep sending messages about this - I know it must be frustrating for
those who keep responding - but I am hoping that coming at it from a
p2p angle, instead of a server/client angle, will help to clear things
up...

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
#!/usr/bin/python

# btpeer.py

import socket
import struct
import threading
import time
import traceback


def btdebug( msg ):
""" Prints a messsage to the screen with the name of the current thread """
print "[%s] %s" % ( str(threading.currentThread().getName()), msg )


#==
class BTPeer:
""" Implements the core functionality that might be used by a peer in a
P2P network.

"""

#--
def __init__( self, maxpeers, serverport, myid=None, serverhost = None ):
#--
""" Initializes a peer servent (sic.) with the ability to catalog
information for up to maxpeers number of peers (maxpeers may
be set to 0 to allow unlimited number of peers), listening on
a given server port , with a given canonical peer name (id)
and host address. If not supplied, the host address
(serverhost) will be determined by attempting to connect to an
Internet host like Google.

"""
self.debug = 0

self.maxpeers = int(maxpeers)
self.serverport = int(serverport)
if serverhost: self.serverhost = serverhost
else: self.__initserverhost()

if myid: self.myid = myid
else: self.myid = '%s:%d' % (self.serverhost, self.serverport)

self.peerlock = threading.Lock()  # ensure proper access to
# peers list (maybe better to use
# threading.RLock (reentrant))
self.peers = {}# peerid ==> (host, port) mapping
self.shutdown = False  # used to stop the main loop

self.handlers = {}
self.router = None



#--
def __initserverhost( self ):
#--
""" Attempt to connect to an Internet host in order to determine the
local machine's IP address.

"""
s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
s.connect( ( "www.google.com", 80 ) )
self.serverhost = s.getsockname()[0]
s.close()



#--
def __debug( self, msg ):
#--
if self.debug:
btdebug( msg )



#--
def __handlepeer( self, clientsock ):
#--
"""
handlepeer( new socket connection ) -> ()

Dispatches messages from the socket connection
"""

self.__debug( 'New child ' + str(threading.currentThread().getName()) )
self.__debug( 'Connected ' + str(clientsock.getpeername()) )

host, port = clientsock.getpeername()
peerconn = BTPeerConnection( None, host, port, clientsock, debug=False )

try:
msgtype, msgdata

Re: [Tutor] trying it again: p2p for game

2010-10-14 Thread Alex Hall
On 10/14/10, Steven D'Aprano  wrote:
> On Fri, 15 Oct 2010 01:30:56 pm Alex Hall wrote:
>> Hi all,
>> Alright: after a few months letting it rest, I am trying this
>> Battleship thing again. I found a p2p library (attached) and have
>> tried to implement it (p2p.py). However, I am always getting the same
>> error: errno2: no connection could be made because the target machine
>> actively refused it.
>
> None of this is a Python problem. You could be using any language.
>
>> I suspect my ip addresses are at fault. I am on a public network here
>> at school, and I keep getting 130... addresses. However, my friend
>> several cities away cannot use 130, since that is local, right? I am
>> not sure where to get my ip; that is, where to get an ip that,
>> coupled with the hard-coded port number, will let my computer connect
>> to his and vice versa.
>
> http://whatismyipaddress.com/
This, too, reports a 130... address and places me in the central hub
for all state university traffic, not my own city. I am not surprised
by this inaccuracy.
>
> Also, be prepared to diagnose firewall issues next. If you're trying to
> connect from a computer in one school to a computer in another school,
> both firewalls will almost certainly try to stop you.
Hmmm... I hate firewalls. :) Still, it failed on my friend's network
when he (said he had) disabled all firewalls and other potential
problem programs for the network...
>
>
> --
> Steven D'Aprano
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] pydoc?

2010-10-18 Thread Alex Hall
Hi all,
Below is part of an email I got from someone in reply to a question
about a program called brlapi. I am on Windows. Can someone explain
what is going on here?

> Hmm... I am relatively new to Python and have not found this pydoc.

Well, I don't know how this is supposed to work on Windows. On Linux,
you simply run

pydoc brlapi

in a shell. Alternatively, you can have a look in brltty's source code,
in Bindings/Python/brlapi.pyx, which is the source for that pydoc.


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] 2.6 vs 2.7: package compatibility?

2010-10-24 Thread Alex Hall
Hi all,
I want to run a certain program from source. One dependency, Durus,
keeps giving me an error that no one can figure out. Someone said that
it will work if I use 2.7 instead of 2.6, but a lot of packages I have
installed work only on 2.6. I know I can install both, but here is the
question: all these packages that say they need 2.6... would they work
on 2.7? That is, is the 2.6 the only version of python with which they
will work, or just the minimum version (I know about the
incompatibility between 2.x and 3). I would rather have just one
version of python running; it makes keeping track of what packages I
have installed easier, and I never could get my idea of two system
variables, one for each version, to work properly. TIA.

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 2.6 vs 2.7: package compatibility?

2010-10-25 Thread Alex Hall
On 10/25/10, Tim Golden  wrote:
> On 25/10/2010 02:20, Alex Hall wrote:
>> Hi all,
>> I want to run a certain program from source. One dependency, Durus,
>> keeps giving me an error that no one can figure out. Someone said that
>> it will work if I use 2.7 instead of 2.6, but a lot of packages I have
>> installed work only on 2.6. I know I can install both, but here is the
>> question: all these packages that say they need 2.6... would they work
>> on 2.7?
>
> I'm going to assume that you're running on Windows -- because
> you usually are :) The answer, then, is that pure python modules
> would need to be reinstalled into (or at least made visible to)
> the newer Python version, but that extension modules would need
> to be recompiled against the newer version -- possibly making use
> of a precompiled binary.
When I ran the source of the program (http://www.qwitter-client.net)
on 2.7 it worked, but it mentioned adding
c:\python26\lib\site-packages to sys.path. I am not sure if this means
it is accessing packages from 2.6...
>
> Just to try, I've compiled Durus without issue on Python 2.6
> from the tarball on their website:
>
>http://www.mems-exchange.org/software/durus/Durus-3.9.tar.gz
>
> but it's not clear from your message above whether it's the
> build which is the issue or some aspect of using it. Can
> you clarify? I'm quite happy to post up an .msi or something
> for you to use if that'll help.
It tells me that persistent_dict does not exist, when it clearly does.
Another user had the exact same problem when running the source on
2.6, but he had no problem when running 2.7. If you had an msi to
install Durus for 2.6 specifically, it would be interesting to see if
the persistent_dict error went away...
>
> TJG
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 2.6 vs 2.7: package compatibility?

2010-10-25 Thread Alex Hall
On 10/25/10, Tim Golden  wrote:
>> It tells me that persistent_dict does not exist, when it clearly does.
>> Another user had the exact same problem when running the source on
>> 2.6, but he had no problem when running 2.7. If you had an msi to
>> install Durus for 2.6 specifically, it would be interesting to see if
>> the persistent_dict error went away...
>
> http://timgolden.me.uk/python/downloads/Durus-3.9.win32-py2.6.msi
>
> TJG
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
Thanks! I get an error in the source, but it is related to the
program, not Durus; there seems to be no Durus error anymore.
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] decorators (the "at" sign)?

2010-10-25 Thread Alex Hall
Hi all,
Now that I am able to run the source code of an open source
application I hope to one day help develop, I am trying to understand
how it works. One thing I keep seeing is an at sign followed by a
word, usually (maybe always) immediately preceeding a function
definition. For example, and I know this exact code will not make much
sense, but it gives the idea:
class Bing(Messages, Updating, Dismissable):

 @set_index
 def get_url(self, index=None):
  return self.storage[index]['Url']

What is the "@set_index" for? Specifically, what is the at sign doing?
Google was only able to provide me with a very vague idea of what is
going on, though it seems to crop up a lot in classmethod and
staticmethod calls (not sure about those either). I read PEP 318, but
it was not much help since I am coming at this having no idea what I
am looking at. The PEP did explain why I have never run into this
before, though - it is apparently specific to Python. I see this sort
of thing all over this source code so it seems like a good idea to get
exactly what it is for. TIA!


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] decorators (the "at" sign)?

2010-10-27 Thread Alex Hall
Thanks to all for the explanations. I think I understand how this
works, basically. I doubt I will use the concept anytime soon, but I
think I get it enough to follow what is happening in the source code
of the application I am examining.

On 10/27/10, Siren Saren  wrote:
> Alex,
>
> Many people have trouble wrapping their minds around decorators.  I couldn't
> find a decent explanation either until reading an allegedly 'advanced'
> python book (b/c 'advanced' is in the title, I guess).
>
> An easy explanation might be sufficient, if you don't intend to use them
> yourself.  A decorator is a way of changing a function's behavior.  Most of
> the time you see a decorator, the person using it could have merely
> rewritten the function or method itself and given it some additional
> capability or modified it in some way.  But, as you may have noticed,
> programmers prefer to 'abstract' when they can, so they can avoid
> 'duplicating code.'  (These are buzzwords you'll encounter a lot).
>
> Let's say your program needs to set an index in a lot of different
> functions, and let's further imagine that setting an index is either more
> than a line of code or that the index itself may change over the development
> cycle, or that the index will vary according to some simple pattern
> consistently defined in these other functions.
>
> To avoid writing the same code over and over and having the value of index
> set in many different places, the developers chose instead to write the code
> once and refer to it in all the other functions through a decorator, which
> takes all the functions, modifies them so they get the index values they
> need, and sets them back in their places (more or less).
>
> If you want the more complicated answer, I think I can take a reasonable
> shot at showing how this works too and making an example.  But you may just
> want a general description.  Also, I'm only about 4 months into learning to
> program so you may prefer a more expert opinion.
>
> Cheers,
>
> Soren
>
> --- On Tue, 10/26/10, Alex Hall  wrote:
>
> From: Alex Hall 
> Subject: [Tutor] decorators (the "at" sign)?
> To: "tutor" 
> Date: Tuesday, October 26, 2010, 2:46 AM
>
> Hi all,
> Now that I am able to run the source code of an open source
> application I hope to one day help develop, I am trying to understand
> how it works. One thing I keep seeing is an at sign followed by a
> word, usually (maybe always) immediately preceeding a function
> definition. For example, and I know this exact code will not make much
> sense, but it gives the idea:
> class Bing(Messages, Updating, Dismissable):
>
>  @set_index
>  def get_url(self, index=None):
>   return self.storage[index]['Url']
>
> What is the "@set_index" for? Specifically, what is the at sign doing?
> Google was only able to provide me with a very vague idea of what is
> going on, though it seems to crop up a lot in classmethod and
> staticmethod calls (not sure about those either). I read PEP 318, but
> it was not much help since I am coming at this having no idea what I
> am looking at. The PEP did explain why I have never run into this
> before, though - it is apparently specific to Python. I see this sort
> of thing all over this source code so it seems like a good idea to get
> exactly what it is for. TIA!
>
>
> --
> Have a great day,
> Alex (msg sent from GMail website)
> mehg...@gmail.com; http://www.facebook.com/mehgcap
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] if statement

2010-11-02 Thread Alex Hall
On 11/2/10, Glen Clark  wrote:
>  File "/home/glen/workspace/test.py", line 19
> if confirmed == "y":
>^
> SyntaxError: invalid syntax
>
> Why does this not work??? PyDev says "Expected:else"
It may help to see the rest of the file, or at least more of the code
surrounding this statement.
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] program hangs in while loop using wx.yield

2010-11-13 Thread Alex Hall
Hi all,
I had this working back in the summer, but have since had to
restructure some things in the code. Now, my program is hanging while
it waits for the human player to take his/her turn, and I am not sure
how to free it; as long as it hangs, the player cannot do anything, so
it continues to hang... You get the idea. Here is the loop:

  while not self.grid.turnOver:
   print("in while") #just a test to make sure I got this far
   wx.Yield()
   time.sleep(1)
  #end while

self.grid is a Grid object which, among other things, is a wx frame
with a sizer inside of it. This Grid class has many functions, and
some of them change the Grid's "turnOver" variable. Therefore, I loop
until I see that the user performed an action on the grid that sets
the Grid's turnOver to true, at which point the loop stops and the
other user (a computer in this case) can go. The problem is that this
loop makes the app hang, with Windows saying it is not responding. Of
course, the user can now not do anything at all, so I have to use
ctrl-c from the cmd window where I launched it to kill it. Does anyone
have a thought? Grid has no loops in it where the program could be
getting stuck and, besides, it hangs immediately, not even giving me
time to call any Grid function. Is this solvable, or should I just use
threads? I hate to launch every new turn in a separate thread as it
seems that this would quickly get out of hand, but if I have to I can
do it. TIA.


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] program hangs in while loop using wx.yield

2010-11-14 Thread Alex Hall
On 11/14/10, Alan Gauld  wrote:
> "Alex Hall"  wrote
>
>> I had this working back in the summer, but have since had to
>> restructure some things in the code. Now, my program is hanging
>> while
>> it waits for the human player to take his/her turn, and I am not
>> sure
>> how to free it;
>
> I don't really understand this concept in a GUI?
> Why would you be waitying for the user?
> Surely you should just go back to the mainloop
> and let the GUI control the users input? Then
> after processing that call the computer move code.
> Something like:
>
> def handle_user_move_event():
>  processMoveOnGUI()
>  movedata = generateComputerMove()
>  processMoveOnGUI()
>  return
>
> Thats what I would expect to see.
The problem is that I want to go until there is a winner. You are
right about just letting the mainloop of the gui handle input (I
forgot the gui is already looping and waiting for input) but I would
like to make the user pause while the computer goes, this way the user
cannot just keep hammering out moves as fast as possible and input can
be given to the user properly. Therefore, I have gotten rid of the
loop I sent originally, but I still have a loop which switches between
the two players as well as passing the results of one player's move to
the other. If I fire (it is Battleship) and hit your ship,and I am the
computer, then this loop will give you the information about where I
fired. You will check to see if it was a hit and, since it was, pass
back information about what was hit. You will also update the gui to
reflect the new status of the damaged ship. However, while I am doing
this, I do not want you firing as fast as possible, and I want you to
take in the results before you are allowed to fire.
I realize it is all rather confusing without seeing the code, but the
loop itself is somewhat complex unless you can see what all the
functions are doing. Still, here is the new loop:

 while not player1.isWinner or not player2.isWinner:
  if player1.grid.turnOver:
   print("player2 is going")
   player1.grid.speak("player 2 is going.")
   player2.enemyMove=player1.grid.cmd #tell p2 what p1 just did
   player1.lock() #so p1 cannot interact with the gui
   player2.takeTurn() #decides what to do and updates its Grid object
accordingly
   player1.grid.speak(helpers.interpret(player2.grid.cmd)) #just
output what p2 did after takeTurn() is over
  elif player2.grid.turnOver:
   print("player1 is going")
   player1.enemyMove=player2.grid.cmd
   player1.unlock() #p1 can now interact with the gui
   player1.grid.speak("It is now your turn.")
   player1.takeTurn()
  #end if
  #wx.Yield()
  time.sleep(.1)
 #end while

>
>>  while not self.grid.turnOver:
>>   print("in while") #just a test to make sure I got this far
>>   wx.Yield()
>>   time.sleep(1)
>>  #end while
>
> So this is presumably buried in some very long and complex method
> that you have written and you are briefly giving control back to
> wxPython
> before continuing your processing? Except that you appear to just
> cycle continually giving back control? It doesn't seem to make sense.
I am honestly not sure how all the control flows, but this loop is
gone so hopefully it will not be a problem.
>
>> some of them change the Grid's "turnOver" variable. Therefore, I
>> loop
>> until I see that the user performed an action on the grid that sets
>> the Grid's turnOver to true, at which point the loop stops and the
>> other user (a computer in this case) can go.
>
> Why are you doing all this inside ane event handler? Why don't
> you just make your move and hand back to the GUI?
>
>
>> The problem is that this loop makes the app hang,
>> with Windows saying it is not responding. Of
>> course, the user can now not do anything at all, so I have to use
>> ctrl-c from the cmd window where I launched it to kill it.
>
> No idea why its doing that. Have you tried playing with the
> Yield parameter and return value to see if they give a clue?
>
> But frankly I'd look to reconstruct the code to avoid the use
> of Yield completely. Yield should almost be a last resort...
>
>> time to call any Grid function. Is this solvable, or should I just
>> use
>> threads?
>
>
> Based on the loop you posted you shouldn't need threads,
> just exit your method and wait for the user to do something
> and catch that event to restart your code. Leave it to the GUI.
>
> HTH,
>
> --
> Alan Gauld
> 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
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] program hangs in while loop using wx.yield

2010-11-14 Thread Alex Hall
On 11/14/10, Alan Gauld  wrote:
> "Alex Hall"  wrote
>
>> The problem is that I want to go until there is a winner. You are
>> right about just letting the mainloop of the gui handle input (I
>> forgot the gui is already looping and waiting for input) but I would
>> like to make the user pause while the computer goes, this way the
>> user
>> cannot just keep hammering out moves as fast as possible
>
> Thats fine so you simple stop accepting input while the computer goes.
> I'm sure your computer can keep up with aeven the fastest typist/mouse
> clicker. If you really want to add a delay simply add a short pause in
> your event handler - 1 second say. Or even better set a semaphore
> which blocks any input and then a timer to reset it after a given
> delay.
>
> This is all fairly satandard GUI practice none of which requires
> complex
> loops. You need to start thinking about a world controlled by the GUI
> firing events( or messages if you like) telling you what is happening
> which you catch and process.
Is there a basic tutorial for this sort of thing? I think part of the
problem is that both players have a Grid object. The human's grid
includes a gui. For example, clicking a square will fire on that
square. The computer has a grid as well, but (of course) with no gui
element; its grid is simply an array holding its ships. All this to
say that when the human fires, something happens to the gui but there
is a lot of other updating going on behind the gui, in the human's
grid object. When the computer "fires", its grid is updated as well,
but not any gui, so message passing by the gui would not seem to
apply.
>
>> be given to the user properly. Therefore, I have gotten rid of the
>> loop I sent originally, but I still have a loop which switches
>> between
>> the two players
>
> Is it two players or is it a player and a computer.
A human and a computer for now. I hope to one day add peer-to-peer
support for two humans to play, but that was not working out at all so
for now I am just trying to give myself some, even if it is digital,
to play against.
> If its the former you need a semaphore to block input from one
> player until the other has gone. In chess terms the values might
> be black and white and the semaphore called player. You then
> either need two input handlers, one for black and one for white
> which call a common utility fuction after checking the semaphor
> or a single function that somehow can identify the player.
>
> If its the latter then the computer should be faster than a hiuman
> so there should be little problem...
Little problem for the computer, since its decision will be made in a
fraction of a second. However, I need to wait for as long as the human
takes to make a turn-ending move. Firing ends a turn, while moving the
mouse or arrows does not. The computer does not have this problem, but
I still need to know when the computer is done.
>
>> the other. If I fire (it is Battleship) and hit your ship,and I am
>> the
>> computer, then this loop will give you the information about where I
>> fired. You will check to see if it was a hit and, since it was, pass
>> back information about what was hit. You will also update the gui to
>> reflect the new status of the damaged ship.
>
> I'm confusing you and I, its safer to use explicit trerms when
> describing
> interactions. But the displaing of information and updating the GUI
> can
> all happen in a blink of an eye if its the computer playing.
You are right, that was confusing. What I am saying is that, each time
a player goes (human or ai) a string gets updated. The opponent can
then examine that string to see what happened, updating the gui (in
the case of the human) accordingly and recording the information for
consideration in future moves (in the case of the ai).
>
>> this, I do not want you firing as fast as possible, and I want you
>> to
>> take in the results before you are allowed to fire.
>
> Why do you care if the human "takes in the results" - if they want
> to trust in randomness surely thats their problem. You as a computer
> can match them blast for blast...
Part of it is that I hope to eventually add sound, and the other part
is that I have always found games that make a move instantly to be a
bit too far from what I am used to. If it is easy to build in a delay,
I would rather have it there.
>
>> while not player1.isWinner or not player2.isWinner:
>>  if player1.grid.turnOver:
>>   print("player2 is going")
>>   player1.grid.speak("player 2 is going.")
>>   player2.enemyMove=player1.grid.cmd #tell p2 what p1 just did
>>   player1.lock() #so p1 cannot interact with the gui
>>   play

Re: [Tutor] age program

2010-11-29 Thread Alex Hall
On 11/29/10, Andre Jeyarajan  wrote:
> Write a short program that will perform the following:It will ask the user
> for his age,it will then present the user with a menu, with 4 choices:Tell
> the user whether his age is an even or an odd number
> Tell the user his age squared
> Tell the user how many years until he’s 100 years old, or tell him that he’s
> alerady over 100!  If the user is exactly 100 years old, congratulate him
> for being a centurion.
> I have tried everything i can. Can you please explain it to me?
Explain which part exactly? That is, what have you gotten to work so
far? If you have not gotten anything yet, I recommend looking up the
input() and raw_input() methods for age and menu. After that it is
just a couple math operations and some if statements inside a while
loop.


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] permutations?

2010-12-01 Thread Alex Hall
Hi all,
I am wondering if there is a python package that will find
permutations? For example, if I have (1, 2, 3), the possibilities I
want are:
12
13
23
123
132
231

Order does not matter; 21 is the same as 12, but no numbers can
repeat. If no package exists, does someone have a hint as to how to
get a function to do this? The one I have right now will not find 132
or 231, nor will it find 13. TIA.

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] permutations?

2010-12-01 Thread Alex Hall
Thanks to everyone for the itertools hint; that sounds like it will work.

Sorry I was not clearer:
1. Order matters; I meant to say that direction does not. That is, 123
is not the same as 213, but 123 is the same as 321 since the second
example is simply a reversal.
2. I am looking for all permutations and subpermutations (if that is a
word) of 1-n where the list must have at least 2, but no more than n,
unique numbers (so 1 is not valid, nor is 1231 since it repeats 1 and
is too long for n=3).
I hope that makes sense. However, hopefully itertools will do it; if I
run into problems I will respond to this email to keep it in the same
thread. Thanks again! Oh, to the person who asked, I have 2.6 and 2.7
installed, with the default being 2.6.

On 12/1/10, bob gailer  wrote:
> On 12/1/2010 5:45 PM, Alex Hall wrote:
>> Hi all,
>> I am wondering if there is a python package that will find
>> permutations? For example, if I have (1, 2, 3), the possibilities I
>> want are:
>> 12
>> 13
>> 23
>> 123
>> 132
>> 231
>>
>> Order does not matter; 21 is the same as 12, but no numbers can
>> repeat. If no package exists, does someone have a hint as to how to
>> get a function to do this? The one I have right now will not find 132
>> or 231, nor will it find 13. TIA.
>
> According to Wikipedia " there are six permutations of the set {1,2,3},
> namely [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1]."
>
> Above you show some "combinations" and a subset of the permutations.
>
> What rules did you apply to come up with your result?
>
> --
> Bob Gailer
> 919-636-4239
> Chapel Hill NC
>
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] permutations?

2010-12-01 Thread Alex Hall
Alright, I have it working. Now the problem is that it does not throw
out reversals. I tried to do this myself with a couple loops, but I
get index errors. My total list of permutations is called l.

for i in range(0, len(l)):
 r=l[i]; r.reverse()
 for j in range(0, len(l)):
  print l[j], r, i, j

  if r==l[j]: l.remove(r)


  if r==l[j]: l.remove(r)
IndexError: list index out of range

When it has found two repeats (oddly, they are the same repeat - 2,1)
and removed them, there are ten of the twelve items left. Once j hits
10, it errors out, obviously, since it is looking for l[10] which no
longer exists. However, should the loop not re-evaluate len(l) each
time, so this should not be a problem? Why is it still looking for an
index that is no longer in the range (0, len(l)), and how can I fix
this? Also, why would it find several items twice? For example, it
picks up (2,1), then picks it up again.
Is there a better way of doing this that would avoid me having to
write the function?

On 12/1/10, Alex Hall  wrote:
> Thanks to everyone for the itertools hint; that sounds like it will work.
>
> Sorry I was not clearer:
> 1. Order matters; I meant to say that direction does not. That is, 123
> is not the same as 213, but 123 is the same as 321 since the second
> example is simply a reversal.
> 2. I am looking for all permutations and subpermutations (if that is a
> word) of 1-n where the list must have at least 2, but no more than n,
> unique numbers (so 1 is not valid, nor is 1231 since it repeats 1 and
> is too long for n=3).
> I hope that makes sense. However, hopefully itertools will do it; if I
> run into problems I will respond to this email to keep it in the same
> thread. Thanks again! Oh, to the person who asked, I have 2.6 and 2.7
> installed, with the default being 2.6.
>
> On 12/1/10, bob gailer  wrote:
>> On 12/1/2010 5:45 PM, Alex Hall wrote:
>>> Hi all,
>>> I am wondering if there is a python package that will find
>>> permutations? For example, if I have (1, 2, 3), the possibilities I
>>> want are:
>>> 12
>>> 13
>>> 23
>>> 123
>>> 132
>>> 231
>>>
>>> Order does not matter; 21 is the same as 12, but no numbers can
>>> repeat. If no package exists, does someone have a hint as to how to
>>> get a function to do this? The one I have right now will not find 132
>>> or 231, nor will it find 13. TIA.
>>
>> According to Wikipedia " there are six permutations of the set {1,2,3},
>> namely [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1]."
>>
>> Above you show some "combinations" and a subset of the permutations.
>>
>> What rules did you apply to come up with your result?
>>
>> --
>> Bob Gailer
>> 919-636-4239
>> Chapel Hill NC
>>
>>
>
>
> --
> Have a great day,
> Alex (msg sent from GMail website)
> mehg...@gmail.com; http://www.facebook.com/mehgcap
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] permutations?

2010-12-03 Thread Alex Hall
Thanks, everyone! While I do not understand the function provided a
few messages back, it works perfectly. The rest of the responses were
very interesting. I need to try, yet again, to really understand list
comprehensions, possibly the most difficult topic I have yet come
across, along with the colon when used in lists.
Thanks again to all!

On 12/2/10, Steven D'Aprano  wrote:
> Alan Gauld wrote:
>>
>> "Alex Hall"  wrote
>>
>>> Alright, I have it working. Now the problem is that it does not throw
>>> out reversals. I tried to do this myself with a couple loops, but I
>>> get index errors. My total list of permutations is called l.
>>>
>>> for i in range(0, len(l)):
>>> r=l[i]; r.reverse()
>>
>> You don''t need to specify the 0, its the default.
>> But you don't need to use indexing either.
>>
>> for r,i in enumerate(l): r.reverse()
>>
>>> for j in range(0, len(l)):
>>>  print l[j], r, i, j
>>
>> Here you are comparing the reversed item to every item in the
>> list, including the ones you have already reversed, including the
>> item itself. So you will always find a match when i==j...
>>
>> Using the in operator and list slicing would be easier
>>
>> if r in l[i:]: l.remove(r)
>>
>> but...
>>
>>>  if r==l[j]: l.remove(r)
>>
>> Its never a good idea to remove items from a list you are iterating
>> over, its like the old cartoon of the guy cutting down the tree branch
>> he is sitting on.
>
> You can cut off the branch you're sitting on so long as you remember to
> cut on the correct side :)
>
> Back in Ancient Days when dinosaurs walked the earth, and I programmed
> in Pascal, computers didn't have much memory, and were slow.
> Consequently it wasn't practical to make a copy of a list if you wanted
> to delete a few items. The only practical way to modify lists was to
> modify them in place, and if you needed to delete items, you had to work
> backwards. It took me a while to break myself of the habit of doing this:
>
> for i in range(len(mylist)-1, -1, -1):
>  if mylist[i] == "something":
>   del mylist[i]
>
> (Note that you only need to work backwards if you're *deleting* entries,
> not if you replace them with something else.)
>
> This is still a useful technique to have in your toolbox, but generally
> speaking the above is better written as:
>
> mylist = [x for x in mylist if x != "something"]
>
>
> If you really need to modify the list in place, and not just re-bind the
> name "mylist" to the new list, then one tiny change will do it:
>
> mylist[:] = [x for x in mylist if x != "something"]
>
>
>
> --
> Steven
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Newline

2010-12-03 Thread Alex Hall
On 12/3/10, Ashley Blackwell  wrote:
> Hello everybody, I'm new to the mailing list so I'm pretty sure I'll have
> lots of questions:)
That is what the list is for. :)
>
> It's a very basic question I have and everybody might look at this
> question and say, "Wow, she reallly doesn't get it?" But oh well. Here's my
> question: I'm in Chapter 2 of my Python Programming Third Editition book.
> I've gotten to the section of the chapter where it talks about a "newline
> character. Exactly what is a newline character? I keep reading the same
> section of the book and I'm just not really understanding. Here's the code
> that the book uses to explain the newline character:
>
> print("Here", end="  ")
> print("it is...")
>
> The book says that I can specify that a space be the final character printed
> instead of a newline. In the first print() statement I specify that a space
> be the final string printed. So the text "Here" appears but no newline
> character. The next print() statement prints the text "it is"..." right
> after the space following the final "e" in the "Here" text. You do it by
> passing a space to the end parameter of the print() function with the code
> end"  ".
>
> My Operating System is Windows 7 and the Python version is 3.1.3. That's it.
> Thanks to anybody who responds to my question.
A newline character is just a character telling the computer to move
to the next line. Understand that all characters, from basic letters
(a, b, c, ...) to strange characters that you never see are
represented by numbers. For example, the letter a is 97, b is 98, and
so on. A space character is 32. A newline has a number as well, since
it is, after all, just another character.

Instead of using numbers, though, Python (like most programming
languages) lets you use what I believe are called escape sequences
(someone correct me here). Basically, putting a backslash (\) followed
by a letter will sometimes represent a character. \t is tab, for
example. In this case, try passing \n to your function (remember to
put it in quotes, since it is still a string!) and see if that does
it. I hope this makes some sense.
>
> --
> *Ava Durand*
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Newline

2010-12-04 Thread Alex Hall
On 12/4/10, Alan Gauld  wrote:
>
> "Steven D'Aprano"  wrote
>
>> >>> for i in (1, 2, 3):
>> ... print(i, "spam", end="\n" if i==3 else "***")
>
> Ooooh! A new trick.
> I hadn't thought of using the conditional expression there but it
> makes a lot of sense.
> Definitely more fun and flexible than the old comma at the end of a
> print in v2 :-)
So is this a python3.x feature only? Is there an equivallent in 2.x? I
had not realized if statements could be used in calling functions like
that or that they could be arranged in that way, but I am sticking to
python2 since most packages are still written for it.
>
> Thanks for that,
>
> Alan G.
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Newline

2010-12-04 Thread Alex Hall
On 12/4/10, Steven D'Aprano  wrote:
> Alex Hall wrote:
>> On 12/4/10, Alan Gauld  wrote:
>>> "Steven D'Aprano"  wrote
>>>
>>>>>>> for i in (1, 2, 3):
>>>> ... print(i, "spam", end="\n" if i==3 else "***")
>>> Ooooh! A new trick.
>>> I hadn't thought of using the conditional expression there but it
>>> makes a lot of sense.
>>> Definitely more fun and flexible than the old comma at the end of a
>>> print in v2 :-)
>> So is this a python3.x feature only? Is there an equivallent in 2.x? I
>> had not realized if statements could be used in calling functions like
>> that or that they could be arranged in that way, but I am sticking to
>> python2 since most packages are still written for it.
>
>
> Python has had "if" expressions (also known as the ternary operator)
> since Python2.5. You can write:
>
> true_value if condition else false_value
How cool!! I never knew that.
>
> anywhere that will accept an expression. E.g.:
>
> len("chicken" if today == tuesday else "fish")
>
> Since Python2.6, you can get the print function by using:
>
> from __future__ import print_function
>
> Note that there are TWO underscores at the start and end of
> "__future__", and that like all __future__ imports it must be the first
> executable line of your script or module.
>
>
> --
> Steven
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] 'or' in assignment (not if statement)?

2010-12-09 Thread Alex Hall
Hi all,
I am reading the source of a project I hope to help with
(http://www.qwitter-client.net). I sometimes see something like:
val=val or 1
I am guessing that val is an int. If val==0, the 'or' kicks in and
val=1, else the or is not needed and val=val. Am I close? Can other
words or symbols be used in contexts where one would not normally
think of them?
Thanks.

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 'or' in assignment (not if statement)?

2010-12-09 Thread Alex Hall
Thanks to all for the quick responses. Python always surprises me with
its shortcuts...

On 12/9/10, Alan Gauld  wrote:
>
> "Alex Hall"  wrote
>
>> val=val or 1
>
>> I am guessing that val is an int. If val==0, the 'or' kicks in and
>> val=1, else the or is not needed and val=val. Am I close?
>
> Yes this is a combination of what is known as short circuit
> evaluation of boolean expressions and a quirk of Python that
> returns the actual value of something that is being treated as
> a boolean.
>
> There is a section on this in the Functional Programming
> topic in my tutor which explains and illustrates in much
> more detail.
>
> This particular trick is now deprecated in favour of the new
> conditional expressiion, so your code would now be written as:
>
> val = val if val else 1
>
>> Can other words or symbols be used in contexts where one
>> would not normally think of them?
>
> See my tutor, it shows how and can be used in similar ways...
>
> HTH,
>
> --
> Alan Gauld
> 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
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] the "**" operator?

2010-12-10 Thread Alex Hall
Hi all,
I was googling a way to do something like
mydict=mydict.extend(additionaldict)

and someone on a forum recommends this:
mydict=dict(mydict, **additionaldict)
What is the ** doing here? I tried to look it up, but Google seems to
ignore it since it is punctuation. The poster on the forum says it
will put all elements of additionaldict in mydict that are not already
in mydict, which is the behavior I am looking for, but I am not sure
why this would be so. TIA.

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] the "**" operator?

2010-12-10 Thread Alex Hall
Thanks all! I thought update() would add an item even if it would be a
duplicate, but apparently not. I also now better understand why I am
always passing around *args and **kwargs when calling super(). Very
interesting...

On 12/10/10, Hugo Arts  wrote:
> On Fri, Dec 10, 2010 at 8:14 PM, Alex Hall  wrote:
>> Hi all,
>> I was googling a way to do something like
>> mydict=mydict.extend(additionaldict)
>>
>
> mydict.update(additionaldict)
>
> see also:
> http://docs.python.org/library/stdtypes.html#dict.update
>
>> and someone on a forum recommends this:
>> mydict=dict(mydict, **additionaldict)
>> What is the ** doing here? I tried to look it up, but Google seems to
>> ignore it since it is punctuation. The poster on the forum says it
>> will put all elements of additionaldict in mydict that are not already
>> in mydict, which is the behavior I am looking for, but I am not sure
>> why this would be so. TIA.
>>
>
> The * and **, when calling functions, are what's called extended
> calling syntax. It's a bit hard to explain, so I'm going to do a sort
> of clarify by example here:
>
>>>> def f(a, b, c):
> ... print a, b, c
> ...
>>>> f(1, 2, 3)
> 1 2 3
>>>> a = [1, 2, 3]
>>>> f(*a)
> 1 2 3
>>>> b = {'a': 2, 'b': 1, 'c': 3}
>>>> f(*b)
> a c b
>>>> f(**b)
> 2 1 3
>
> In short, if a = [1, 2, 3], f(*a) is the same as f(1, 2, 3). if b =
> {'a': 2, 'b': 1, 'c': 3}, then f(**b) is the same as f(a=2, b=1, c=3).
>
> The * will iterate over its argument, and supply the resulting values
> as arguments to the function (iterating over a dict will return its
> keys, which is what you see with f(*b) here). ** requires a mapping
> type, and supplies the keys and values to the function as keyword
> arguments.
>
> * and ** are very flexible, and you can use them alongside with
> regular arguments:
>
>>>> f(1, *[2, 3])
> 1 2 3
>>>> f(1, **{'b': 2, 'c': 3})
> 1 2 3
>
> * and ** also have uses in function definition, where they sort of do
> the reverse. They can capture any number of regular or keyword
> arguments in a tuple or dictionary:
>
>>>> def f(*args, **kwargs):
> ... print args, kwargs
> ...
>>>> f()
> () {}
>>>> f(1, 2, 3)
> (1, 2, 3) {}
>>>> f(1, 2, 3, a=4, b=5)
> (1, 2, 3) {'a': 4, 'b': 5}
>>>> f(a=4, b=5)
> () {'a': 4, 'b': 5}
>
> Like with function calls, you can mix up regular arguments and */**
> arguments, as long as the resulting function is unambiguous:
>
>>>> def f(a, *args, **kwargs):
> ... print a, args, kwargs
> ...
>>>> f()
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: f() takes at least 1 argument (0 given)
>>>> f(1)
> 1 () {}
>>>> f(1, 2, 3)
> 1 (2, 3) {}
>>>> f(1, 2, 3, b=4, c=5)
> 1 (2, 3) {'c': 5, 'b': 4}
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Problem with print

2010-12-19 Thread Alex Hall
Sorry to top-post (gMail mobile).
This looks like you missed a quote, colon, or something on a line
elsewhere in the file (likely above it). Find that and this should be
fixed.

On 12/19/10, jtl999  wrote:
>  File "GettingStarted.py", line 91
> print ("Lesson Two")
> ^
> SyntaxError: invalid syntax
>
> Python 2.6.5
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] subclass not inheriting attributes?

2011-01-03 Thread Alex Hall
Hi all,
I have a solitaire game in which I use a "Pile" class. This class is
meant to hold a bunch of cards, so I subclass it for the deck, the ace
stacks, and the seven main stacks, defining rules and methods for each
but also relying on the parent Pile class's methods and attributes.
However, I keep getting an error that an attribute in the parent does
not exist in the child. Below is a simplified example, but it gives me
the exact same error: child object has no attribute l.

class parent(object):
 def __init__(self, l=None):
  if l is None: l=[]

class child(parent):
 def __init__(self, *args, **kwords):
  super(parent, self).__init__(*args, **kwords)
  self.l.append(5)

c=child()
print c.l

Again, I get an error saying that 'child' object has no attribute 'l'.
Python 2.7 on win7x64. Thanks.

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


  1   2   >