[Tutor] How to test for a remainder from division

2007-05-14 Thread Matt Smith
Hi there,

I'm trying to write a short function to test whether a year is a leap
year or not. To do this I need to check whether the year divides exactly
by 4, 100 and 400. I can't think of an easy way to test whether there is
a remainder or not. The best I can come up with so far is:

if (year / 4.0) - (year // 4.0) <> 0:

This doesn't seem to work, it is always True, is there a problem with
the comparison? The arithmetic seems to be the correct way to isolate
the remainder of the division.

Can anyone suggest a better way of performing this test or alternately,
how can I get the line above to work.

Thanks,

Matt


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to test for a remainder from division

2007-05-14 Thread Matt Smith
Hi,

Thanks for all the help, I guessed that there would be a module out
there providing a function to do this but wanted to go through the
process as a learning exercise. The modulus operator was just what I was
looking for, I had been trying to check for a difference between the
division and the floor division - a bit of a long winded way of doing
things. Here is the final code I have come up with, any comments?

# A program to determine whether a year is a leap year or not

def is_leap_year(year):
# Function that accepts a year as input and returns true if it is a leap
year, false if it is not
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
return True
else:
return False

# Main program logic
year = raw_input("What year? ")
year = int(year)
if is_leap_year(year):
print year, "is a leap year."
else:
print year, "is not a leap year"

Thanks,

Matt


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Help with excetion handing and making my code more efficient needed please

2007-05-18 Thread Matt Smith
Hi,

I am trying to write a simple program to display Conway's Game Of Life.
I have the bones of the program together but I'm struggling with the
function that tests for and applies the rules of the game (the important
bit). I have the current state of the game stored in a 2d matrix with
each cell represented by a 1 or 0 (alive or dead) i.e: [[0, 1, 0], [1,
0, 0], [0, 0, 0]]. I'm using a 15 * 15 matrix for testing purposes. I
have come up with the following function to update the matrix so far:

def update_matrix(matrix):
matrix_updated = [matrix]
# Perform check for each value in the matrix
for x in range(len(matrix[0])):
for y in range(len(matrix)):
neighbour_count = 0
if matrix[x-1][y+1]: neighbour_count = neighbour_count + 1 
if matrix[x][y+1]: neighbour_count = neighbour_count + 1
if matrix[x+1][y+1]: neighbour_count = neighbour_count + 1
if matrix[x+1][y]: neighbour_count = neighbour_count + 1
if matrix[x+1][y-1]: neighbour_count = neighbour_count + 1
if matrix[x][y-1]: neighbour_count = neighbour_count + 1
if matrix[x-1][y-1]: neighbour_count = neighbour_count + 1
if matrix[x-1][y]: neighbour_count = neighbour_count + 1
# Apply game of life rules to each item in the matrix
if 2 < neighbour_count > 3:
matrix_updated[x][y] = 0
elif neighbour_count == 3:
matrix_updated[x][y] = 1
# No need to change values if neighbour count == 2
return matrix_updated

I have two problems with this code: Firstly, when testing cells on the
edges of the matrix, I get an IndexError because I am testing an item in
the list that does not exist. I want the program to assume that cells
outside the bounds of the board are automatically dead. I am not sure
how to suppress or avoid this error so that neighbour_count is not
incremented for indexes outside the matrix.

My second problem is that this function seems to be very clunky to me
(even if it did work...). I cannot think of a way of checking each of
the 8 cells surrounding the one being tested without doing it this way.
Is there a better way of doing this?

Thanks in advance, Matt.


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with excetion handing and making my code more efficient needed please

2007-05-18 Thread Matt Smith
On Fri, 2007-05-18 at 23:49 +0200, Rikard Bosnjakovic wrote:
> Something like this:
> 
> try:
>the_index_outside_matrix_test()
> except IndexError:
>   suppress_the_error()

Thanks Rikard,

I'm not sure how I would go about actually suppressing the error - what
would suppress_the_error() actually call?

Cheers,

Matt


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with excetion handing and making my code more efficient needed please

2007-05-18 Thread Matt Smith
> > Is there a better way of doing this?
> 
> Perhaps something like this:
> 
> for n in (x, x+1, x-1):
>   for m in (y, y+1, y-1):
> if matrix[n, m]:
>   neighbour_count = neighbour_count + 1
> 

I need to not text matrix[x][y] is there a simple way to exclude this from the 
possible combinations of values from the two tuples?


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with excetion handing and making my code more efficient needed please

2007-05-19 Thread Matt Smith
> the possible combinations of values from the two tuples?
> see my other reply, Matt.
> -Luke

Hi Luke,

Sorry if I'm missing something but which other reply?

Matt


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with excetion handing and making my code more efficient needed please

2007-05-19 Thread Matt Smith
On Fri, 2007-05-18 at 17:03 -0500, Luke Paireepinart wrote:
> see my other reply, Matt.
> -Luke

Apologies Luke,

I have found your earlier post in the tutor archives - I don't seem to
have received it from the list yet.

Thanks for the help.

Matt


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Still having trouble with my game of life algorithm

2007-05-25 Thread Matt Smith
Hi,

First of all, thanks to everyone who helped with my last post
(http://mail.python.org/pipermail/tutor/2007-May/054360.html). I have
re-written the function that applies the rules but it still doesn't
return the expected result. I have been through it and corrected a
couple of bugs bet as far as I can tell it should return a matrix that
has had the rules of Conway's game of life
(http://en.wikipedia.org/wiki/Conway%27s_game_of_life) applied. Here is
my function:

def update_matrix(matrix):
matrix_updated = matrix
# Perform check for each value in the matrix
for x in range(len(matrix[0])):
for y in range(len(matrix)):
neighbour_count = 0
for n in (x-1, x, x+1):
for m in (y-1, y, y+1):
try:
if matrix[m][n]:
if (n,m) != (x,y):
neighbour_count = neighbour_count + 1
except IndexError:
pass
# Apply game of life rules to each item in the matrix
if neighbour_count < 2:
matrix_updated[y][x] = 0
elif neighbour_count > 3:
matrix_updated[y][x] = 0
elif neighbour_count == 3:
matrix_updated[y][x] = 1
# No need to change value if neighbour count == 2
return matrix_updated

I have also attached the full program and the input file that I am using
for testing in case anyone is interested. The program does use curses to
display the board so I guess it won't be any good for Windows users.

I hope someone can see where I am going wrong here.

Thanks,

Matt
#! /usr/bin/env python

import curses

def read_start():
# Read the starting configuration from a text file
file = open('/home/matt/Python/game_of_life/r-pentomino.txt', 'r')
matrix = []
for line in file:
line = line.rstrip('\n')
line_list=[]
for i in range(len(line)):
line_list.append(int(line[i]))
matrix.append(line_list)
return matrix

def draw_board(matrix, stdscr, generation):
# Draw the life board based on the matrix containing the current state
for x in range(len(matrix[0])):
for y in range(len(matrix)):
if matrix[y][x]:
stdscr.addch(y + 1, x + 1, '*')
else:
stdscr.addch(y + 1, x + 1, '.')
stdscr.addstr(len(matrix) + 1, 0, 'Generation: %s' % (generation))
stdscr.refresh()

def update_matrix(matrix):
matrix_updated = matrix
# Perform check for each value in the matrix
for x in range(len(matrix[0])):
for y in range(len(matrix)):
neighbour_count = 0
for n in (x-1, x, x+1):
for m in (y-1, y, y+1):
try:
if matrix[m][n]:
if (n,m) != (x,y):
neighbour_count = neighbour_count + 1
except IndexError:
pass
# Apply game of life rules to each item in the matrix
if neighbour_count < 2:
matrix_updated[y][x] = 0
elif neighbour_count > 3:
matrix_updated[y][x] = 0
elif neighbour_count == 3:
matrix_updated[y][x] = 1
# No need to change value if neighbour count == 2
return matrix_updated

def main(stdscr):
# Initialise some variables and put the screen in it's starting configuration
matrix = read_start()
generation = 1
draw_board(matrix, stdscr, generation)
stdscr.addstr(len(matrix) + 2, 0, 
'Press  to advance a generation,  to quit.')
# The main program loop - respont to keyboard input
while 1:
key_press = stdscr.getkey()
if key_press == 'q':
break
elif key_press == ' ':
generation = generation + 1
matrix = update_matrix(matrix)
draw_board(matrix, stdscr, generation)

# Run the main program inside the curses wrapper to ensure it leaves the screen in a usable state`
curses.wrapper(main)
000
000
000
000
000
000
0001100
0011000
0001000
000
000
000
000
000
000
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] More trouble debugging my game of life program

2007-06-03 Thread Matt Smith
Hi,

I've got my program working correctly (or so it seems) with my original
data file (r-pentomino.txt - attached) but when I run it with a larger
(30*30) file (big-r-pentomino - also attached) in an attempt to make it
work with out so many edge effects it returns the following error
message:

Traceback (most recent call last):
  File "Python/game_of_life/life.py", line 75, in 
curses.wrapper(main)
  File "curses/wrapper.py", line 44, in wrapper
  File "Python/game_of_life/life.py", line 60, in main
draw_board(matrix, stdscr, generation)
  File "Python/game_of_life/life.py", line 28, in draw_board
stdscr.addch(y + 1, x + 1, ' ')
_curses.error: addch() returned ERR

I thought I had designed the program to work with any text file as long
as the lines are all the same length so I cannot understand why I get
this error message. When I read through the code I cannot see a reason
why the program should work for one size file and not another. The part
of the program that is failing is just drawing a space character at a
particular location on the screen.

Here is the listing of the program that I have also attached:

#! /usr/bin/env python

# Curses based Game of Life program
# Written by Matt Smith

import curses
from copy import deepcopy

def read_start():
# Read the starting configuration from a text file
file = open('/home/matt/Python/game_of_life/r-pentomino.txt', 'r')
matrix = []
for line in file:
line = line.rstrip('\n')
line_list=[]
for i in range(len(line)):
line_list.append(int(line[i]))
matrix.append(line_list)
return matrix

def draw_board(matrix, stdscr, generation):
# Draw the life board based on the matrix containing the current
state
for x in range(len(matrix[0])):
for y in range(len(matrix)):
if matrix[y][x]:
stdscr.addch(y + 1, x + 1, '*')
else:
stdscr.addch(y + 1, x + 1, ' ')
stdscr.addstr(len(matrix) + 1, 0, 'Generation: %s' % (generation))
stdscr.refresh()

def update_matrix(matrix):
matrix_updated = deepcopy(matrix)
# Perform check for each value in the matrix
for x in range(len(matrix[0])):
for y in range(len(matrix)):
neighbour_count = 0
for n in (x-1, x, x+1):
for m in (y-1, y, y+1):
try:
if matrix[m][n]:
if (n,m) != (x,y):
neighbour_count = neighbour_count + 1
except IndexError:
pass
# Apply game of life rules to each item in the matrix
if neighbour_count < 2:
matrix_updated[y][x] = 0
elif neighbour_count > 3:
matrix_updated[y][x] = 0
elif neighbour_count == 3:
matrix_updated[y][x] = 1
# No need to change value if neighbour count == 2
return matrix_updated

def main(stdscr):
# Initialise some variables and put the screen in it's starting
configuration
matrix = read_start()
generation = 1
draw_board(matrix, stdscr, generation)
stdscr.addstr(len(matrix) + 2, 0, 
'Press  to advance a generation,  to quit.')
# The main program loop - respond to keyboard input
while 1:
key_press = stdscr.getkey()
if key_press == 'q':
break
elif key_press == ' ':
generation = generation + 1
matrix = update_matrix(matrix)
draw_board(matrix, stdscr, generation)

# Run the main program inside the curses wrapper to ensure it leaves the
screen
# in a usable state
curses.wrapper(main)

Can anyone come up with the reason why one input file works and the
other one doesn't??

Thanks,

Matt
0
0
0
0
0
0
0
0
0
0
0
0
0
00110
01100
00100
0
0
0
0
0
0
0
0
0
0
0
0
0
0
000
000
000
000
000
0011000
011

[Tutor] Suggestions for a first object orientated program

2007-06-03 Thread Matt Smith
Hi,

I have been reading up on OOP in Python recently and feel ready to
attempt my first program using OOP principals. Can anyone suggest a
suitable first OOP project for me to get my teeth into?

I haven't done any real GUI programming but I have started gutting to
grips with the curses module under Linux (see my posts about the game of
life program). The game of life program might also show the kind of
stage I am at with my learning of Python at the moment.

Thanks,

Matt




___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] More trouble debugging my game of life program

2007-06-04 Thread Matt Smith
On Sun, 2007-06-03 at 18:09 -0400, Brian van den Broek wrote:

> The first thing I would do to try to track down the problem would be 
> to try 15x30 and 30x15 matrices. If you have two cases where one 
> behaves as expected and one does not, it is usually very useful to try 
> to match the two cases as closely as possible as an aid to pinpointing 
> the problem.

Thanks Brian,

Initially 15*30 worked but 30*15 didn't. I have just gradually
increased the width of my text file up to 30 characters and it worked
at 30*30 so I guess the problem must be with the text file I was using.
Looking at my code - I can see it will break if the lists within the
big list making up the matrix are not all the same length. Maybe this
is something I need to test for in the program.

Cheers,

Matt


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Invoking Python from Vim

2007-06-07 Thread Matt Smith
Hi,

Bit of a Vim specific question this one but I hope someone might have an
answer. I currently have the following line in my .gvimrc file (I'm
using Ubuntu Linux):

map  :!gnome-terminal -e=python\ -i\ %

This opens a window and runs the Python program I am working on. I don't
really like the fact I can't do anything else in vim until I close the
window and I don't really need the interactive prompt that I am left
with. If I invoke Python without the -i then I don't get to see the
error message if my program exits with an error.

In 'normal' vim I use:

map  :w\|!python %

This doesn't work for GVim which I prefer to use.

Do any Vim users have a better way of running a Python program while it
is being edited in Vim?

Thanks,

Matt


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How to keep trying something until it doesn't return an error?

2007-11-12 Thread Matt Smith
Hi there,

I am currently working on a noughts and crosses program to try and teach 
myself some very simple AI programming and also to start to use OOP in 
Python.

I am currently writing the framework for the game so I can then write a 
number of functions or a class to deal with the strategy side of things.

I'm stuck trying to write a method which will only accept a legal move 
and will keep asking until it gets a legal answer. I can see that 
working out how to do this efficiently will be very useful in my future 
programming as well.

I currently have the following code.

while 1:
 try:
 xpos = input ("Where do you want to go? ")
 gameboard.addx(xpos)
 gameboard.draw()
 break
 except cantgo:
 print "You can't go there!"

which calls the following method:

 def addx(self,pos):
 if pos in range(1,10) and self.state[pos-1] == "":
 self.state[pos-1] = "X"
 else:
 raise cantgo

The cells of the game are referenced by the numbers 1 to 9. The code 
gave the following error:

Traceback (most recent call last):
   File "noughts_and_crosses.py", line 49, in 
 except cantgo:
NameError: name 'cantgo' is not defined

Interesting the first pass of the code above did not return an error but 
the second pass did. Currently I have the same code twice for X's and 
O's. Next, I defined the error using:

cantgo = "can't go"

And now I get:

noughts_and_crosses.py:33: DeprecationWarning: raising a string 
exception is deprecated
   raise cantgo
You can't go there!

But the program will not let me enter any (valid) move at all now. This 
looks like it is not breaking out of the while loop correctly, which, 
when I look back at my code, is to be expected.

Is there a typical 'Pythonic' way of dealing with this situation.




___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Use of sqrt() from math module

2007-12-01 Thread Matt Smith
Hi,

I need to find the square root of a number in a program I am writing. I have 
imported the 'math' module so I thought I could just call sqrt(x) but I get an 
error message. Extact from my code and error message below.


import sys, pygame, math

...

 if ypos >= 384 and velocity > 0:
 impactvel = sqrt(velocity ** 2 + (2 * gravity * (ypos - 384 * 160)))

...


Traceback (most recent call last):
   File "", line 32, in 
ValueError: math domain error

This one has me stumped as the usage of the module looks straight forward from 
the documentation. Thanks for looking.

Matt



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Use of sqrt() from math module

2007-12-01 Thread Matt Smith
Matt Smith wrote:
> import sys, pygame, math
> 
> ...
> 
> if ypos >= 384 and velocity > 0:
> impactvel = sqrt(velocity ** 2 + (2 * gravity * (ypos - 384 * 
> 160)))
> 
> ...
> 
> 
> Traceback (most recent call last):
>   File "", line 32, in 
> ValueError: math domain error

Apologies, the actual error I get when I run the code above is:

Traceback (most recent call last):
   File "", line 31, in 
NameError: name 'sqrt' is not defined

The error I quoted first was when I tried to call 'math.sqrt(x)'

Matt

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Use of sqrt() from math module

2007-12-01 Thread Matt Smith
Michael H.Goldwasser wrote:
> After using "import math" you will need to use the qualified name
> math.sqrt(blah) to call the square root function.   That explains the
> NameError when trying to use the unqualified name, sqrt.
> 
> As to your first message, the ValueError that you are reporting with
> the usage math.sqrt is likely due to an attempt to take the square
> root of a negative number (presumably because your (ypos - 384 * 160)
> factor is negative.

Thanks Michael and Ziyad, it seems I just had my brackets in the wrong place 
leading to trying to square root a number less than 0.

Matt

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor