数据结构(python语言描述)第四章答案

以下是个人做法。仅作参考

练习4.3

3、

# -*- coding=utf-8 -*-
__author__ = 'junhao'
__date__ = '2018/9/30 10:41'

"""
File: arrays.py

An Array is like a list, but the client can use only [], len, iter, and str.

To instantiate, use

<variable> = Array(<capacity>, <optional fill value>)

The fill value is Noe by default
"""


class Array(object):
    """Represents an array."""

    def __init__(self, capacity, fillValue=None):
        """Capacity is the static size of the array.
        fillValue is placed at each position."""
        self._items = list()
        for count in range(capacity):
            self._items.append(fillValue)

    def __len__(self):
        """-> The capacity of the array."""
        return len(self._items)

    def __str__(self):
        """-> The string representation of the array."""
        return str(self._items)

    def __iter__(self):
        """Supports traversal with a for loop."""
        return iter(self._items)

    def __getitem__(self, index):
        """Subscript operator for access at index."""
        return self._items[index]

    def __setitem__(self, index, newItem):
        """Subscript operator for replacement at index."""
        self._items[index] = newItem

    def get(self):
        """获取数组内容"""
        return self._items



# -*- coding=utf-8 -*-
__author__ = 'junhao'
__date__ = '2018/9/30 10:41'

from arrays import Array


class Grid(object):
    """Represents a two-dimensional array."""

    def __init__(self, rows, columns, fillValue = None):
        self._data = Array(rows)
        for row in range(rows):
            self._data[row] = Array(columns, fillValue)

    def get(self):
        return self._data

    def getHeight(self):
        """Returns the number of rows."""
        return len(self._data)

    def getWidth(self):
        """Returns thr number of columns."""
        return len(self._data[0])

    def __getitem__(self, index):
        """Supports two-dimensional indexing with [row][column]."""
        return self._data[index]

    def __str__(self):
        """Returns a string representation of the grid."""
        result = ""
        for row in range(self.getHeight()):
            for col in range(self.getWidth()):
                result += str(self._data[row][col]) + " "
            result += "\n"
        return result

from grid import Grid


grid1 = Grid(3, 4, 2)
grid1[1][3] = -1

rows = grid1.getHeight()
cols = grid1.getWidth()

for i in range(rows):
    for j in range(cols):
        if grid1[i][j] < 0:
            row = i
            col = j
            break
        if i == rows and j == cols:
            row = rows
            col = cols

print(row)
print(col)

6、

# -*- coding=utf-8 -*-
__author__ = 'junhao'
__date__ = '2018/9/30 10:43'

from grid import Grid
from arrays import Array


class ThreeGrid(object):

    def __init__(self, deepth, height, width, fillValue = None):
        self._data = Array(deepth, fillValue)
        for i in range(deepth):
            grid1 = Grid(height, width, fillValue)
            self._data[i] = grid1

    def getDeepth(self):
        """Returns the number of deepth."""
        return len(self._data)

    def getHeight(self):
        """Returns the number of rows."""
        return self._data[0].getHeight()

    def getWidth(self):
        """Returns the number of column."""
        return self._data[0].getWidth()

    def __getitem__(self, index):
        """Supports three-dimensional indexing with [row][column]."""
        return self._data[index]

    def __str__(self):
        """Returns a string representation of the grid."""
        result = ""
        for d in range(self.getDeepth()):
            for h in range(self.getHeight()):
                for w in range(self.getWidth()):
                    result += str(self._data[d][h][w]) + " "
                result += "\n"
            result += "\n"
        return result

编程项目

1到6、

# -*- coding=utf-8 -*-
__author__ = 'junhao'
__date__ = '2018/10/1 13:46'

from arrays import Array


class ArrayList(Array):

    def __init__(self, capacity, fillValue=None):
        super(ArrayList, self).__init__(capacity, fillValue)
        # Array.__init__(self, capacity=capacity, fillValue=fillValue)
        self._oricapacity = capacity
        self._capacity = capacity
        self._data = super(ArrayList, self).get()
        self._logicalSize = 0
        if fillValue is None:
            self._logicalSize = self._capacity

    def get(self):
        return self._data

    def size(self):
        return self._logicalSize

    def __getitem__(self, index):
        if 0 <= index < self.size():
            return super(ArrayList, self).__getitem__(index)
        else:
            raise Exception("The index out of range")

    def __setitem__(self, index, newItem):
        if 0 <= index < self.size():
            return super(ArrayList, self).__setitem__(index, newItem)
        else:
            raise Exception("The index out of range")

    def set(self, index, newItem):
        return super(ArrayList, self).__setitem__(index, newItem)

    def grow(self):
        """使数组扩大一倍"""
        temp = Array(self._capacity * 2)
        for i in range(self.size()):
            temp[i] = self._data[i]
        self._data = temp
        self._capacity *= 2

    def shrink(self):
        """若数组容量/2之后小于原来默认值,则数组大小为默认值,否则缩小一倍"""
        if self._oricapacity <= self._capacity // 2:
            temp = Array(self._capacity // 2)
            for i in range(self._capacity // 2):
                temp[i] = self._data[i]
            self._data = temp
            self._capacity = self._capacity // 2
        else:
            temp = Array(self._oricapacity)
            for i in range(self._oricapacity):
                temp[i] = self._data[i]
            self._data = temp
            self._capacity = self._oricapacity

    def insert(self, index, newItem):
        """在指定位置插入一项"""
        if self.size() >= self._capacity:
            self.grow()
        if index >= self.size():
            self.set(self.size(), newItem)
            self._logicalSize += 1
        else:
            for i in range(self.size()-1, index-1, -1):
                self._data[i+1] = self._data[i]
            self._data[index] = newItem
            self._logicalSize += 1

    def pop(self, index):
        """删除一项,并返回删除项的值"""
        if 0 <= index < self.size():
            temp = self._data[index]
            for i in range(index+1, self.size()):
                self._data[i-1] = self._data[i]
            self._logicalSize -= 1
            return temp

    def __eq__(self, obj):
        """判断相等"""
        if isinstance(obj, ArrayList) and self.size() == obj.size():
            for i in range(self.size()):
                if self._data[i] == obj.get()[i]:
                    pass
                else:
                    return False
            return True
        else:
            return False

    def __iter__(self):
        """覆盖父类方法,删除此方法"""
        pass

    def __str__(self):
        result = ""
        if self.size() > 0:
            for i in range(self.size()):
                result += str(self._data[i]) + " "
        return result


7、

# -*- coding=utf-8 -*-
__author__ = 'junhao'
__date__ = '2018/10/2 10:15'

from grid import Grid


class Matrix(Grid):

    def __init__(self, rows, columns, fillValue = None):
        super(Matrix, self).__init__(rows, columns, fillValue)
        self._data = super(Matrix, self).get()
        self.rows = rows
        self.columns = columns

    def __add__(self, obj):
        """矩阵加法"""
        if self.rows == obj.rows and self.columns == obj.columns:
            temp = Grid(self.rows, self.columns)
            for i in range(self.rows):
                for j in range(self.columns):
                    temp[i][j] = self._data[i][j] + obj[i][j]
            return temp
        else:
            raise Exception("矩阵维度不一致")

    def __sub__(self, obj):
        """矩阵减法"""
        if self.rows == obj.rows and self.columns == obj.columns:
            temp = Grid(self.rows, self.columns)
            for i in range(self.rows):
                for j in range(self.columns):
                    temp[i][j] = self._data[i][j] - obj[i][j]
            return temp
        else:
            raise Exception("矩阵维度不一致")

    def __eq__(self, obj):
        """判断两个矩阵是否相等"""
        if self.rows == obj.rows and self.columns == obj.columns:
            for i in range(self.rows):
                for j in range(self.columns):
                    if self._data[i][j] != obj[i][j]:
                        return False
            return True
        else:
            return False

    def __mul__(self, obj):
        if self.columns == obj.rows:
            temp = Grid(self.rows, obj.columns)
            for i in range(self.rows):
                for j in range(obj.columns):
                    for m in range(self.columns):
                        pass
        else:
            raise Exception("矩阵A的列数和矩阵B的行数不一致")



  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值