Python Forum
[Help] A function that generates an n x n sized board?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Help] A function that generates an n x n sized board?
#1
Hi Python Experts,

I'm trying to solve this problem but I am having a hard time understanding what exactly it is that I'm supposed to do? Or what is the desired output?

I have spent hours in Google/YouTube trying to help myself understand the tasks but I haven't found one, unfortunately.

If anyone of you could give me any ideas how to solve this, I would really appreciate it. Thank you

The tasks:

1. There is one small bug in the continent counter. Can you find it and fix it? (Hint: change the world so that the continent borders the edge)

2. Write a function that generates an n x n sized board with either land or water chosen randomly.

==============================================================================
M = "land"
o = "water"
world = [
		 [o,o,o,o,o,o,o,o,o,o,o],
		 [o,o,o,o,M,M,o,o,o,o,o],
		 [o,o,o,o,o,o,o,o,M,M,o],
		 [o,o,o,M,o,o,o,o,o,M,o],
		 [o,o,o,M,o,M,M,o,o,o,o],
		 [o,o,o,o,M,M,M,M,o,o,o],
		 [o,o,o,M,M,M,M,M,M,M,o],
		 [o,o,o,M,M,o,M,M,M,o,o],
		 [o,o,o,o,o,o,M,M,o,o,o],
		 [o,M,o,o,o,M,o,o,o,o,o],
		 [o,o,o,o,o,o,o,o,o,o,o]
		]

def continent_counter(world, x, y):
	if world[y][x] != "land":
		return 0

	size = 1
	world[y][x] = "counted land"
	#row above
	size = size + continent_counter(world, x-1, y-1)
	# print("first recursion size: ", size)
	size = size + continent_counter(world, x, y-1)
	size = size + continent_counter(world, x+1, y-1)
	#same row
	size = size + continent_counter(world, x-1, y)
	size = size + continent_counter(world, x+1, y)
	#row below
	size = size + continent_counter(world, x-1, y+1)
	size = size + continent_counter(world, x, y+1)
	size = size + continent_counter(world, x+1, y+1)
	return size


print(continent_counter(world, 5, 5))
Blockchain Visionary & Aspiring Encipher/Software Developer
me = {'Python Learner' : 'Beginner\'s Level'}
http://bit.ly/JoinMeOnYouTube
Reply
#2
2. Write a function that generates an n x n sized board with either land or water chosen randomly

What have you tried?
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#3
(Aug-13-2018, 11:47 AM)perfringo Wrote: 2. Write a function that generates an n x n sized board with either land or water chosen randomly

What have you tried?

Hi @perfringo, I am a beginner so without me understanding the question or what is the desired output (in plain english) it is difficult for me to find ways to solve it?

Hope that makes sense? Thank you
Blockchain Visionary & Aspiring Encipher/Software Developer
me = {'Python Learner' : 'Beginner\'s Level'}
http://bit.ly/JoinMeOnYouTube
Reply
#4
To generate a 2d matrix, you have to use nested loops or maybe itertools.
You generate one col, which is the inner loop, and the row generation is the outer loop.

To get a feeling for it, just try some code:

for a in 'abcdefg':
    for b in range(10):
        print(a, b)
Print some pattern to understand it better:
for a in 'abcdefg':
    for b in range(10):
        print(a + str(b), end=' ')
        # no line break, print in the same line
    print() # next line
Instead of printing, you need a list to save your columns and rows.

import random


def gen_maze(width=11, height=11):
    rows = []
    # list for complete row
    for _ in range(height):
        col = []
        # for each row a new list for cols
        for _ in range(width):
            value = random.choice(['o', 'M'])
            col.append(value)
        # append the complete col to the row
        rows.append(col)
    return rows

gen_maze()
As generator it is a bit cleaner:
def gen_maze(width=11, height=11):
    for _ in range(height):
        col = []
        for _ in range(width):
            value = random.choice(['o', 'M'])
            col.append(value)
        yield col

# list consumes the generator
list(gen_maze())
Or as a one-liner:
def gen_maze(width=11, height=11):
    return [[random.choice(['o', 'M']) for _ in range(width)] for _ in range(height)]
PS: The _ (underscore) is a throw away name in Python. We assign objects to it, if we don't need them. In interactive mode the _ holds the last returned object from a function, when there was no assignment.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#5
In plain english? <You can ignore following rant>Good start would be to talk to your teacher and ask him/her to avoid ambiguous tasks. What does "generate" means? By definition function returns value to caller (Documentation >>> Glossary >>> function). Does generate means return n x n sized matrix or have output (print) said matrix? Or should this function generate something and return nothing? Or should this code work as replicator in Star Trek i.e. generate actual board?</end rant>

You should break your task into smaller pieces.

- values should be either land (M) or water (o) chosen randomly

There is built-in module conveniently name random. You just:

>>> import random
>>> random.          # two times TAB key
random.betavariate(     random.lognormvariate(  random.seed(           
random.BPF              random.normalvariate(   random.setstate(       
random.choice(          random.NV_MAGICCONST    random.SG_MAGICCONST   
random.choices(         random.paretovariate(   random.shuffle(        
random.expovariate(     random.randint(         random.SystemRandom(   
random.gammavariate(    random.Random(          random.triangular(     
random.gauss(           random.random(          random.TWOPI           
random.getrandbits(     random.randrange(       random.uniform(        
random.getstate(        random.RECIP_BPF        random.vonmisesvariate(
random.LOG4             random.sample(          random.weibullvariate( 
If you scan this you will see some promising names like random.choice() or random.choices().

You can find out what these promising names do:

>>> help(random.choice)
Help on method choice in module random:

choice(seq) method of random.Random instance
    Choose a random element from a non-empty sequence.
(END)
It sounds like what you need. Let's try it:

>>> random.choice(['M', 'o'])
'M'
>>> random.choice(['M', 'o'])
'o'
>>> random.choice(['M', 'o'])
'M'
>>> random.choice(['M', 'o'])
'o'
>>> random.choice(['M', 'o'])
'o'
It seems that we found a way choose randomly between land and ocean.

Now we have to make n x n board. Supposedly it means that you need to have n x n matrix. Matrix a.k.a. list of lists is generated (in plain english): you create empty list, you append empty list into that list, you append values to last list which is inside the list. In Python code it is something like that:

>>> matrix = []
>>> for i in range(2):
...    matrix.append([])
...    for j in range(4):
...        matrix[-1].append(0)
...
>>> matrix
[[0, 0, 0, 0], [0, 0, 0, 0]]
If you understand this code and know also list comprehension you can express this with following one-liner.

[[0 for i in range(4)] for j in range(2)]
Your task was not to append zeros but random choices:

[[random.choice(['M', 'o']) for i in range(4)] for j in range(2)]
If there is task to have n x n board then probably you need to replace arbitrary 4 and 2 in current code and wrap it up in function:

>>> def board(rows, cols):
...    return [[random.choice(['M','o']) for i in range(cols)] for j in range(rows)]
...
>>> board(2, 3)
[['M', 'o', 'o'], ['M', 'o', 'M']]
While I was ranting Dead_EyE ninjad me and posted quite similar solution.

EDIT:

I should stand corrected. In n x n matrix you don't need two parameters (rows, columns) as it's a square and requires only one parameter. You need to import random as well, so correct version is:

>>> import random
>>> def board(n):
...    return [[random.choice(['M','o']) for i in range(n)] for j in range(n)]
...
>>> board(3)
[['M', 'M', 'M'], ['M', 'o', 'o'], ['o', 'o', 'o']]
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#6
Hi @DeaD_EyE & @perfringo, thank you so much for being so generous in sharing your inputs above. Just know, that I really appreciate your time in trying to help me understand the task(s) as it wasn't explained to us in a beginner's level way in class, sadly.

It took me some time to reply because I had to understand your inputs and do some more research. I sort of understand that this tasks' topic is about 2D list/Matrix using nested loops (for loops) so I gathered some additional info and managed to structure the code below. #FingerCrossed

When I was trying to run this code in my terminal, it wouldn't give me any output for some reason? Do you have any ideas what could be the reason?

import random

M = 'land'
o = 'water'
w = 11 #number of rows
h = 11 #number of columns
matrix = []
world = [
         [o,o,o,o,o,o,o,o,o,o,o],
         [o,o,o,o,M,M,o,o,o,o,o],
         [o,o,o,o,o,o,o,o,M,M,o],
         [o,o,o,M,o,o,o,o,o,M,o],
         [o,o,o,M,o,M,M,o,o,o,o],
         [o,o,o,o,M,M,M,M,o,o,o],
         [o,o,o,M,M,M,M,M,M,M,o],
         [o,o,o,M,M,o,M,M,M,o,o],
         [o,o,o,o,o,o,M,M,o,o,o],
         [o,M,o,o,o,M,o,o,o,o,o],
         [o,o,o,o,o,o,o,o,o,o,o]
        ]

def gen_maze():
	rows = []
	for i in range(w):
		matrix.append([])
		col = []
		for j in range(h):
			# matrix[-1].append(0)
			value = random.choice(['o', 'M'])
			col.append(value)
		rows.append(col)
	return rows

gen_maze()
==============================================================================

[Image: a_zpsy5xebirk.png]

Thank you kindly.
Blockchain Visionary & Aspiring Encipher/Software Developer
me = {'Python Learner' : 'Beginner\'s Level'}
http://bit.ly/JoinMeOnYouTube
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Trying to make a board with turtle, nothing happens when running script Quascia 3 608 Nov-01-2023, 03:11 PM
Last Post: deanhystad
  unittest generates multiple files for each of my test case, how do I change to 1 file zsousa 0 918 Feb-15-2023, 05:34 PM
Last Post: zsousa
Photo HOW FIX MY BOARD GAME LAZABI 3 1,435 Apr-01-2022, 04:23 PM
Last Post: BashBedlam
  The game should now run and terminate once the board is full, but still can’t identif rango 0 1,431 Jul-22-2021, 03:24 AM
Last Post: rango
  Enabling interrupt on Adafruits button/led board Moris526 0 1,987 Apr-30-2021, 03:29 PM
Last Post: Moris526
  High-Precision Board Voltage Reading from Python into PD Liam484 1 2,051 Mar-29-2021, 02:57 PM
Last Post: Marbelous
  Interrupt for Adafruits Neotrellis button/led board Moris526 0 1,769 Dec-28-2020, 05:42 AM
Last Post: Moris526
  Why does Cython generates bad code for Gentoo? AlekseyPython 1 1,819 Dec-26-2019, 01:57 PM
Last Post: AlekseyPython
  OverflowError: cannot fit 'int' into an index-sized integer vipinv23 2 9,194 Jan-17-2019, 04:08 AM
Last Post: vipinv23
  upgrading google-api generates an error ineuw 3 3,619 Jul-07-2018, 06:47 AM
Last Post: ineuw

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020