当前位置: 首页>>代码示例>>Python>>正文


Python Matrix.row方法代码示例

本文整理汇总了Python中matrix.Matrix.row方法的典型用法代码示例。如果您正苦于以下问题:Python Matrix.row方法的具体用法?Python Matrix.row怎么用?Python Matrix.row使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在matrix.Matrix的用法示例。


在下文中一共展示了Matrix.row方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_iter_over_one_row

# 需要导入模块: from matrix import Matrix [as 别名]
# 或者: from matrix.Matrix import row [as 别名]
 def test_iter_over_one_row(self):
     m = Matrix(3, 3)
     m[1][0] = 1
     m[1][1] = 2
     m[1][2] = 3
     self.assertEqual([x for x in m.row(1)], [1, 2, 3])
     self.assertEqual([x for x in m[1]], [1, 2, 3])
开发者ID:plilja,项目名称:project-euler,代码行数:9,代码来源:test_matrix.py

示例2: TestMatrix

# 需要导入模块: from matrix import Matrix [as 别名]
# 或者: from matrix.Matrix import row [as 别名]
class TestMatrix(TestCase):

    def setUp(self):	
        self.m1 = Matrix([[1, 2], 
		          [3, 4]])

	self.m2 = Matrix([[-1, 5], 
		          [0, 9]])

	self.m3 = Matrix([[-1, 5, 4],
			  [0, 9, 1],
			  [4, 5, 2]]) 

	self.m4 = Matrix([[-1, 5], 
		          [0, 9],
			  [3, 2]])

    def test_bad_matrix(self):
        """Make sure the input matrix is valid"""

        # should raise an exception for an empty matrix
        self.assertRaises(TypeError, Matrix, [])
	
        # should raise an exception for an invalid matrix
        self.assertRaises(TypeError, Matrix, ['a'])

        # should raise an exception for an incorrect matrix
	# must be 2-dimensional
        self.assertRaises(TypeError, Matrix, [1, 2])

    def test_row_col_getters(self):
	# get row with index 1
	self.assertEqual(self.m1.row(1), [3, 4])

	# get col with index 1
	self.assertEqual(self.m1.col(1), [2, 4])

    def test_transposal(self):
	self.m1.transpose()
	self.assertEqual(self.m1.matrix, [[1, 3], [2, 4]])

    def test_addition(self):
	# should raise an exception for addition of matrices with 
	# different lengths
	self.assertRaises(IndexError, self.m1.__add__, self.m3)

	# test simple addition
	self.assertEqual((self.m1 + self.m2).matrix, [[0, 7], [3, 13]])

    def test_multiplication(self):
	# test whether number of columns in multiplicand
	# is equal to number of rows in multiplier
        self.assertRaises(IndexError, self.m1.__mul__, self.m3)
	
	# test multiplication
	self.assertEqual((self.m3 * self.m4).matrix, [[13, 48], 
                                                      [3, 83], 
	                                              [2, 69]])
开发者ID:Obie-Wan,项目名称:matrix-operations,代码行数:60,代码来源:tests.py

示例3: Gomoku

# 需要导入模块: from matrix import Matrix [as 别名]
# 或者: from matrix.Matrix import row [as 别名]
class Gomoku(object):

    COMPUTER = 'C'

    def __init__(self, size, empty_spot):
        self.size = size
        self.empty_spot = empty_spot
        self.m = Matrix(self.size, self.size, self.empty_spot)
        self.musashi = Musashi(self.m, self.COMPUTER)

    # Check for a spot to be placed a move
    def check_spot(self, row, col):
        return self.m[row,col] == self.empty_spot

    # Do the move
    def do_move(self, row, col, player):
        self.m[row,col] = player
        return self.copy_matrix()
    
    # Copy the matrix
    def copy_matrix(self):
        return self.m[(0,0):]

    # Show the matrix
    def show_matrix(self):
        return str(self.m)
        
    # TODO: Computer turn
    def computer_turn(self):
        comp_move = self.musashi.domove(self.m)
        return self.do_move(comp_move[0], comp_move[1], self.COMPUTER) 
        
    # Check for a final state of the game
    def is_over(self):
        r = False
        for direction in directions:
            r = (r or self.check_over(direction))
        return r

    # Check if its over on one direction
    def check_over(self, direction):
        # mes(direction)
        if direction == 'H':
            return self.iterate_over('row')
        elif direction == 'V':
            return self.iterate_over('col')
        elif direction == 'D':
            return self.iterate_diagonal()
        else:
            return False
	
    # Iterate over a line to search a sequence of 5
    def iterate_over(self, where):
        sequence = 0
        sym_list = []
        for line in range(0,self.size):
            if where == 'row':
                sym_list = self.m.row(line)
            elif where == 'col':
                sym_list = self.m.col(line)
            else:
                return False
            back_pos = 0
            for symbol in sym_list:
                if symbol != self.empty_spot:
                    if symbol == sym_list[back_pos]:
                        sequence += 1
                    else:
                        sequence = 0
                else:
                    sequence = 0
                if sequence == SEQUENCE:
                    return True
                back_pos += 1
            sequence = 0
        return False
    
    # Iterate over the diagonals to search a sequence of 5
    def iterate_diagonal(self):
        sequence = 0
        sym_list = []
        for diagonal in range(-((self.size*2)-1),self.size*2):
            back_pos = 0
            sym_list = self.m.diagonal(diagonal)
            for symbol in sym_list:
                if symbol != self.empty_spot:
                    if symbol == sym_list[back_pos]:
                        sequence += 1
                    else:
                        sequence = 0
                else:
                    sequence = 0
                if sequence == SEQUENCE:
                    return True
                back_pos += 1
            sequence = 0
        return False
开发者ID:blebougge,项目名称:grad,代码行数:99,代码来源:gomoku.py

示例4: print

# 需要导入模块: from matrix import Matrix [as 别名]
# 或者: from matrix.Matrix import row [as 别名]
    #  9 10 11 12
    print('\n{} turn:\n{}'.format(turn, board))

    while True:
        try:
            play = input(turn + ': ')
            # Player entered a number, now search for this number in our board.
            row, col = board.index(play)
            assert board[row, col] not in ('x', 'o')
            board[row, col] = turn
            break
        except Exception as e:
            print(e)

    # Make a list of all lines that pass through the cell played.
    directions = [board.row(row),
                  board.col(col),
                  board.diagonal(row, col, +1),
                  board.diagonal(row, col, -1)]

    # Convert lines to a single space separated string.
    str_directions = ' '.join(''.join(line) for line in directions)

    # Verify if there are three of the player symbols in a row.
    if turn * 3 in str_directions:
        # Maps every cell removing the ones that are still numbers.
        clean_board = board.map(lambda i: i if i in 'xo' else '')
        print('\n{} wins!\n{}'.format(turn, clean_board))
        break()

    if all(i in ('x', 'o') for i in board):
开发者ID:boppreh,项目名称:matrix,代码行数:33,代码来源:tic_tac_toe.py

示例5: test_extract_row_from_one_number_matrix

# 需要导入模块: from matrix import Matrix [as 别名]
# 或者: from matrix.Matrix import row [as 别名]
 def test_extract_row_from_one_number_matrix(self):
     matrix = Matrix("1")
     self.assertEqual(matrix.row(1), [1])
开发者ID:NSteinhoff,项目名称:exercism,代码行数:5,代码来源:matrix_test.py

示例6: test_can_extract_row_from_non_square_matrix

# 需要导入模块: from matrix import Matrix [as 别名]
# 或者: from matrix.Matrix import row [as 别名]
 def test_can_extract_row_from_non_square_matrix(self):
     matrix = Matrix("1 2 3\n4 5 6\n7 8 9\n8 7 6")
     self.assertEqual(matrix.row(3), [7, 8, 9])
开发者ID:NSteinhoff,项目名称:exercism,代码行数:5,代码来源:matrix_test.py

示例7: test_extract_row_where_numbers_have_different_widths

# 需要导入模块: from matrix import Matrix [as 别名]
# 或者: from matrix.Matrix import row [as 别名]
 def test_extract_row_where_numbers_have_different_widths(self):
     matrix = Matrix("1 2\n10 20")
     self.assertEqual(matrix.row(2), [10, 20])
开发者ID:NSteinhoff,项目名称:exercism,代码行数:5,代码来源:matrix_test.py

示例8: test_can_extract_row

# 需要导入模块: from matrix import Matrix [as 别名]
# 或者: from matrix.Matrix import row [as 别名]
 def test_can_extract_row(self):
     matrix = Matrix("1 2\n3 4")
     self.assertEqual(matrix.row(2), [3, 4])
开发者ID:NSteinhoff,项目名称:exercism,代码行数:5,代码来源:matrix_test.py

示例9: Scene

# 需要导入模块: from matrix import Matrix [as 别名]
# 或者: from matrix.Matrix import row [as 别名]
class Scene(QtGui.QWidget, FileHandler):
    print_ = pyqtSignal(str)
    error_sig = pyqtSignal(str)
    prompt_sig = pyqtSignal(str)
    window_title_changed = pyqtSignal(str)

    def __init__(self, config, get_hsbar_pos, get_vsbar_pos):
        super().__init__()
        self.theme = config['theme']

        self.get_hsbar_pos = get_hsbar_pos
        self.get_vsbar_pos = get_vsbar_pos

        self.horizontal_time = False
        self.modified_flag = False
        self.file_path = ''

        self.grid = Matrix()
        self.undo_stack = []

        font = QtGui.QFont(self.theme['font'], self.theme['font size'])
        boldfont = QtGui.QFont(self.theme['font'], self.theme['font size'],
                               weight=QtGui.QFont.Bold)
        self.font_data = {'def': (font, QtGui.QFontMetrics(font)),
                          'bold': (boldfont, QtGui.QFontMetrics(boldfont))}

        self.draw_scene()


    def paintEvent(self, ev):
        painter = QtGui.QPainter(self)
        painter.drawPixmap(0, 0, self.scene_image)
        rx, ry = self.get_hsbar_pos(), self.get_vsbar_pos()
        painter.drawPixmap(0, ry, self.header_row)
        painter.drawPixmap(rx, 0, self.header_col)
        painter.drawPixmap(rx, ry, self.corner)

    def draw_scene(self):
        border = self.theme['border']
        row_padding, col_padding = 20, 20
        row_heights = [max([x[1][1] for x in self.grid.row(row) if x[0]] + [0]) + row_padding
                       for row in range(self.grid.count_rows())]
        col_widths = [max([x[1][0] for x in self.grid.col(col) if x[0]] + [0]) + col_padding
                      for col in range(self.grid.count_cols())]

        width = sum(col_widths) + border
        height = sum(row_heights) + border
        self.scene_image = QtGui.QPixmap(width, height)

        # Begin paint
        self.scene_image.fill(QColor(self.theme['background']))
        painter = QtGui.QPainter(self.scene_image)
        painter.setRenderHints(QtGui.QPainter.Antialiasing | QtGui.QPainter.TextAntialiasing)
        painter.setFont(self.font_data['def'][0])
        painter.setBrush(QColor(self.theme['cell background']))

        # Draw header lines
        hy = int(border + row_heights[0])
        vx = int(border + col_widths[0])
        painter.setPen(QColor(self.theme['details']))
        painter.drawLine(0, hy, border + sum(col_widths), hy)
        painter.drawLine(vx, 0, vx, border + sum(row_heights))

        # Draw border numbers #TODO: fix the offsets
        for n, rh in list(enumerate(row_heights))[1:]:
            painter.drawText(4, border + sum(row_heights[:n]) + rh/2 + 5, str(n))
        for n, cw in list(enumerate(col_widths))[1:]:
            painter.drawText(border + sum(col_widths[:n]) + cw/2 - 5, 16, str(n))

        # Draw plotline lines
        for n, size in enumerate((col_widths, row_heights)[self.horizontal_time]):
            if n == 0: continue
            if self.horizontal_time:
                x, y = col_widths[0]/2, sum(row_heights[:n]) + size/2 - 5
                w, h = sum(col_widths), 10
            else:
                x, y = sum(col_widths[:n]) + size/2 - 5, row_heights[0]/2
                w, h = 10, sum(row_heights)
            painter.fillRect(border + x, border + y, w, h, QColor('black'))

        # Draw cells
        painter.setPen(QColor(self.theme['cell border']))
        for r in range(self.grid.count_rows()):
            for c in range(self.grid.count_cols()):
                text, size = self.grid[c,r]
                if not text: continue
                if c == 0 or r == 0:
                    painter.setFont(self.font_data['bold'][0])
                else:
                    painter.setFont(self.font_data['def'][0])
                x = border + sum(col_widths[:c]) + col_widths[c]/2 - size[0]/2
                y = border + sum(row_heights[:r]) + row_heights[r]/2 - size[1]/2
                painter.drawRoundedRect(x-3, y-3, size[0]+6, size[1]+6, 5, 5)
                painter.drawText(x, y, size[0], size[1], Qt.TextWordWrap, text)

        painter.end()

        hw = border + col_widths[0]
        hh = border + row_heights[0]

#.........这里部分代码省略.........
开发者ID:nycz,项目名称:urd,代码行数:103,代码来源:scene.py

示例10: test_load_arff

# 需要导入模块: from matrix import Matrix [as 别名]
# 或者: from matrix.Matrix import row [as 别名]
 def test_load_arff(self):
     t = Matrix()
     t.load_arff("test/cm1_req.arff")
     self.assertListEqual(t.row(t.rows-1), [1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 3.0, 1.0, 1.0])
开发者ID:jhollowayj,项目名称:toolkitPython,代码行数:6,代码来源:test_matrix.py

示例11: test_init_from

# 需要导入模块: from matrix import Matrix [as 别名]
# 或者: from matrix.Matrix import row [as 别名]
 def test_init_from(self):
     m2 = Matrix(self.m, 1, 1, 2, 2)
     self.assertListEqual(m2.row(0), [-8, 2])
     self.assertListEqual(m2.row(1), [self.infinity, 2])
开发者ID:jhollowayj,项目名称:toolkitPython,代码行数:6,代码来源:test_matrix.py


注:本文中的matrix.Matrix.row方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。