Discusión:2011/Nodos/Programación colectiva (Dojo)

De Hackmeeting

(Diferencias entre revisiones)

Anonima (Discutir | contribuciones)
(Página nueva: <pre> #!/usr/bin/python from sys import stdin from time import sleep def read_input(): lineas = stdin.readlines() matrix = [] for linea in lineas: linea = list(...)
Ir a las siguientes diferencias →

Revisión de 11:17 23 oct 2011

#!/usr/bin/python

from sys import stdin
from time import sleep

def read_input():
    lineas = stdin.readlines()
    matrix = []

    for linea in lineas:
        linea = list(linea.strip())
        matrix.append(linea)

    return matrix


class Matrix(list):
    def is_inside(self, position):
        limits = len(self), len(self[0])
        x, y = position

        return x in range(limits[0]) and \
        y in range(limits[1])

    def siblings(self, position):
        x, y = position
        rows = x-1, x, x+1
        columns = y-1, y, y+1

        siblings = []
        for row in rows:
            for column in columns:
                if not (row, column) == position and \
                self.is_inside((row, column)):
                    siblings.append(self[row][column])
        return siblings

    def alive_siblings(self, position):
        siblings = self.siblings(position)
        return siblings.count('x')

class GameOfLife():
    def __init__(self,matrix):
        self.matrix = matrix

    def __iter__(self):
        return GameOfLife(self.next())

    def next(self):
        result = matrix

        for row in range(len(matrix)):
            for col in range(len(matrix[row])):
                alive = matrix.alive_siblings((row,col))
                result[row][col] = self.decide(alive, matrix[row][col])
        return result

    def decide(self, alive, current):
        if alive < 2 or alive > 3:
            return '*'
        elif alive == 2:
            return current
        else:
            return 'x'

    def __str__(self):
        printable = ''
        for line in self.matrix:
            printable += ''.join(line)
            printable += '\n'
        return printable

    def __repr__(self):
        return str(self)


matrix = Matrix(read_input())
gof = GameOfLife(matrix)
for state in gof:
    print(str(state))
    sleep(1)
Herramientas personales
wiki-navigation
project-navigation