本文主要是介绍Python实现一维数组、二维网格和杂乱网格,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
前言
代码整体框架已经实现,但细节方面如创建数组长度是否允许为0等并未实现。
1. 一维数组
arrays.py
"""
数组
<variable> = Array(<capacity>, <option fill value>)
"""
class Array(object):def __init__(self, capacity, fill_value=None):self._items = []for count in range(capacity):self._items.append(fill_value)def __len__(self):return len(self._items)def __str__(self):return str(self._items)def __iter__(self):return iter(self._items)def __getitem__(self, index):return self._items[index]def __setitem__(self, index, new_item):self._items[index] = new_item
运行示例:
2. 二维网格
grid.py
"""
网格
"""from arrays import Arrayclass Grid(object):def __init__(self, rows, columns, fill_value=None):self._data = Array(rows)for row in range(rows):self._data[row] = Array(columns, fill_value)def get_height(self):return len(self._data)def get_width(self):return len(self._data[0])def __getitem__(self, index):return self._data[index]def __str__(self):result = ""for row in range(self.get_height()):for col in range(self.get_width()):result += str(self._data[row][col]) +" "result += "\n"return result
运行示例:
3. 杂乱网格
messy_grid.py
"""
杂乱网格
"""from arrays import Arrayclass MessyGrid(object):def __init__(self, rows, columns, fill_value=None):self._data = Array(rows)for row in range(rows):self._data[row] = Array(columns[row], fill_value)def get_height(self):return len(self._data)def get_width(self):all_width = []for i in range(self.get_height()):all_width.append(len(self._data[i]))return all_widthdef all_width(self):max_width = 1min_width = 1for i in range(self.get_height()):width = len(self._data[i])if width > max_width:max_width = widthif width < min_width:max_width = widthresult = ""result += "Min Width: {}".format(min_width) + "\n"result += "Max Width: {}".format(max_width) + "\n"result += "All Width: {}".format(self.get_width())return resultdef __getitem__(self, index):return self._data[index]def __str__(self):result = ""for row in range(self.get_height()):for col in range(self.get_width()[row]):result += str(self._data[row][col]) +" "result += "\n"return result
运行示例:
完!
这篇关于Python实现一维数组、二维网格和杂乱网格的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!