[Python] Trying to debug my program

In summary, the code doesn't seem to work right, and the code might look more Pythonic if it were translated.
  • #1
fluidistic
Gold Member
3,923
261
Hi people,
I'm trying to figure out what's wrong with my code.
My goal is to calculate the average number of stones it takes so that 2 stones become adjascent on a 19x19 goban (the board of the game of go), when we randomly pick an intersection and place a stone on it. The answer should be almost 13 if I remember well.
Here's my code:
Python:
# Program that estimates the average number of stones required so that 2 stones
# become adjascent in an nxn goban. I want to plot the distribution of number
# of stones vs numbers of trial, i.e. an histogram.
import random
import numpy as np

# Size of the board
n = 19

# Number of trials
trials = 1000
# Initialize the board list of lists to 0. 0 means no stone, 1 means stone.
# Note that board[0][0] is the first element and board[20][20] is the last one
# , for when n=19. That's because I define the board
# as n+2 x n+2 for the edges...
board = [[0]*(n+2) for i in range(n+2)]
counter = 0
# Generate random coordinates inside of the 19x19 board
x_coordinates, y_coordinates = random.randint(1, n), random.randint(1, n)

# Now define a boolean function that I'll use as a condition in a while loopdef check_if_stones(x_coordinates, y_coordinates):
  if (board[x_coordinates-1][y_coordinates] == 1
  or board[x_coordinates][y_coordinates-1] == 1
  or board[x_coordinates+1][y_coordinates] == 1
  or board[x_coordinates][y_coordinates+1] == 1):
      return False
  else:
      return True

trial_list = []
for j in range(trials):
    while check_if_stones(x_coordinates, y_coordinates):
        if board[x_coordinates][y_coordinates] == 0:
            # Now replace a random element by 1
             board[x_coordinates][y_coordinates] = 1
             counter += 1
             x_coordinates, y_coordinates = random.randint(1, n), random.randint(1, n)
    x_coordinates, y_coordinates = random.randint(1, n), random.randint(1, n)
    # Update the counter when the boolean function returns false. Do this outside of the while loop.
    counter += 1
    trial_list.append(counter)
    x_coordinates, y_coordinates = random.randint(1, n), random.randint(1, n)
print(np.mean(trial_list))

Now, when trials = 1000 like in the code, one would expect the result to be close to 13. But it returns a number around 622. When trial is worth 5 I get an output of around 17...
So that np.mean(trial_list) depends heavily on "trials" while it shouldn't depend that heavily on it.
I've no idea what's wrong with the code and I'm desperate to fix it. I'd appreciate if you could spot anything weird, thanks!

P.D.:Sorry about the indentation, it seems to be broken when I paste it from Emacs. I've edited it manually but I may have goofed here on PF somewhere.
 
Last edited:
Technology news on Phys.org
  • #2
The trial_list append is outside the j loop, so append(counter) is executed once. The mean then is meaningless.
 
  • #3
mheslep said:
The trial_list append is outside the j loop, so append(counter) is executed once. The mean then is meaningless.
My bad... the indentation is really messed up. In my code it is well inside the for j loop.
EDIT: Problem solved! I had to reset both the counter and the board in the for j loop! It now works fine!
 
Last edited:
  • #4
You should look at using enumerate instead of defining "counter=0" to see if you like it more; it's more elegant to me.
 
  • Like
Likes fluidistic
  • #5
Arsenic&Lace said:
You should look at using enumerate instead of defining "counter=0" to see if you like it more; it's more elegant to me.
Thanks for the tip. That would look more pythonic indeed. I'll check it out... though my priority for now is to translate this code into common lisp. I'm just starting to learn CL, it looks quite hard.
 
  • #6
LISP = Lots of Infuriating Superfluous Parentheses o0)
 
  • Like
Likes fluidistic
  • #7
Chicken scheme is my preferred lisp-dialect frankly, since scheme is less nasty than lisp and chicken's c compiler allows you to write decently fast code.
 
  • #8
fluidistic said:
Thanks for the tip. That would look more pythonic indeed. I'll check it out... though my priority for now is to translate this code into common lisp. I'm just starting to learn CL, it looks quite hard.
First things first, why? (And why not Haskell, or Erlang, or OCaml?)

Secondly, why are you trying to transliterate? There's a name for the hilarious result that typically ensues when a Fortran program is translated, statement for statement, to C. It's called C-Tran (and that is a derogatory term). Don't transliterate. On trying to learn a new language, learn the language. Jump right in! Learn the language, learn the idioms. Start from scratch. Don't translate.

Thirdly, your code doesn't look pythonic to me. What's with the if statement in def check_if_stones? There's no need for an if. All you need is the boolean expression. Learn to do that and you'll be one step closer to functional programming.
 
  • Like
Likes fluidistic
  • #9
D H said:
First things first, why? (And why not Haskell, or Erlang, or OCaml?)
One of my dreams is to understand Maxima's code and eventually contribute to it. I'd like to fix bugs, make the program more efficient, etc.

Secondly, why are you trying to transliterate? There's a name for the hilarious result that typically ensues when a Fortran program is translated, statement for statement, to C. It's called C-Tran (and that is a derogatory term). Don't transliterate. On trying to learn a new language, learn the language. Jump right in! Learn the language, learn the idioms. Start from scratch. Don't translate.
Because as of now I don't know almost any lisp and as first program I want to be able to replicate what the Python's code is doing. I never started with the hello world program with python either, I jumped right into problem solving.
Thirdly, your code doesn't look pythonic to me. What's with the if statement in def check_if_stones? There's no need for an if. All you need is the boolean expression. Learn to do that and you'll be one step closer to functional programming.
Ok thanks for the tip. I don't see it now, but I'll think about it.
 

1. Why does my code keep throwing errors?

There could be several reasons for this. It could be a simple syntax error, a logical error, or a problem with your environment or dependencies. Try examining the error message and the line of code where it is occurring to get a better idea of the issue. You can also try using a debugger or printing out intermediate values to track down the problem.

2. How do I find and fix errors in my code?

One way to find and fix errors in your code is to use a debugger. A debugger allows you to step through your code line by line and see the values of variables at each step. You can also try using print statements to track the flow of your code and see the values of variables at different points. Additionally, reading through your code carefully and checking for common errors, such as missing parentheses or incorrect indentation, can also help you find and fix errors.

3. Why isn't my program producing the desired output?

There are a few possible reasons for this. It could be a problem with your input data, a mistake in your code, or an issue with your logic. Check your input data and make sure it is in the correct format and contains all the necessary information. Then, carefully examine your code and make sure it is doing what you expect it to do. If you are still having trouble, try breaking your code into smaller chunks and testing each part separately to isolate the issue.

4. How can I prevent errors from occurring in my code?

The best way to prevent errors from occurring in your code is to practice good coding habits. This includes using descriptive variable names, commenting your code, and testing your code frequently. It is also helpful to break your code into smaller, more manageable chunks and test each part separately before combining them. Additionally, familiarizing yourself with common errors and how to avoid them can also help prevent errors in your code.

5. How can I improve the performance of my program?

There are several ways to improve the performance of your program. One way is to use built-in functions or libraries instead of writing your own code for common tasks. Another way is to optimize your code by removing unnecessary loops or using more efficient data structures. It can also be helpful to profile your code to identify any bottlenecks and then focus on optimizing those areas. Finally, regularly reviewing and refactoring your code can also improve its performance over time.

Similar threads

  • Programming and Computer Science
Replies
8
Views
2K
  • Programming and Computer Science
Replies
1
Views
2K
  • Programming and Computer Science
Replies
2
Views
1K
  • Programming and Computer Science
Replies
9
Views
2K
  • Programming and Computer Science
Replies
16
Views
1K
  • Programming and Computer Science
Replies
11
Views
2K
  • Programming and Computer Science
Replies
22
Views
776
  • Programming and Computer Science
Replies
2
Views
903
  • Programming and Computer Science
Replies
8
Views
1K
  • Programming and Computer Science
Replies
4
Views
3K
Back
Top