6.6题目

# ! /usr/bin/env python
# -*- coding: utf-8 -*-

'''
@author: liudaoqiang
@file: studycase
@time: 2018/8/31 7:44
'''

import time


class Array(object):
	"""Represent Array"""

	def __init__(self, capacity, fillValue=None):
		self._items = list()
		for count in range(capacity):
			self._items.append(fillValue)

	def __iter__(self):
		return iter(self._items)

	def __len__(self):
		return len(self._items)

	def __str__(self):
		return str(self._items)

	def __getitem__(self, index):
		return self._items[index]

	def __setitem__(self, index, newItem):
		self._items[index] = newItem


class Node(object):

	def __init__(self, data, next=None):
		self.data = data
		self.next = next

	def __iter__(self):
		# 链表必须是可迭代的,才能被加入到LinkedBag实例对象中
		cursor = self
		while cursor != None:
			yield cursor.data
			cursor = cursor.next


class LinkedBag(object):

	def __init__(self, sourceCollection=None):
		self._items = None
		self._size = 0
		if sourceCollection != None:
			for item in sourceCollection:
				self.add(item)

	def isEmpty(self):
		return len(self) == 0

	def __len__(self):
		return self._size

	def __add__(self, other):
		result = LinkedBag(self)
		for item in other:
			result.add(item)
		return result

	def __eq__(self, other):
		if self == other:
			return True
		if type(self) != type(other) or \
				len(self) != len(other):
			return False
		for item in self:
			if item not in other:
				return False
		return True

	def __str__(self):
		return "{" + ", ".join(map(str, self)) + "}"

	def __iter__(self):
		cursor = self._items
		while cursor != None:
			yield cursor.data
			cursor = cursor.next

	def add(self, item):
		self._items = Node(item, self._items)
		self._size += 1

	def removeItem(self, targetItem):
		"""删除元素"""
		if targetItem not in self:
			raise KeyError(str(targetItem) + "not in bag")

		probe = self._items
		trailor = None
		for item in self:
			if targetItem == item:
				break
			trailor = probe
			probe = probe.next

		if probe == self._items:  # 如果probe没有移动
			self._items = self._items.next  # 要删除的item就是第一个元素
		else:
			trailor.next = probe.next  # trailor是probe的前一个节点,probe就是要删除的节点
		self._size -= 1

	def removeIndex(self, index):
		"""删除下标对应的元素"""
		if index >= self.__len__():
			raise KeyError(index + "not in bag")
		else:
			probe = self._items
			if index <= 0 or self._items.next == None:
				self._items = self._items.next
			else:
				while index > 1 and self._items.next.next != None:
					probe = probe.next
					index -= 1
				probe.next = probe.next.next
			return self._items


class ArraySotrtedBag(object):
	""" An array-based bag implementation"""

	# Class variable
	DEFAULT_CAPACITY = 10

	# Constructor
	def __init__(self, sourceCollection=None):
		"""Sets the initial state of self, which  includes the contents of sourceCollection,
		if it`s present	"""
		self._items = Array(ArraySotrtedBag.DEFAULT_CAPACITY)
		self._size = 0
		if sourceCollection:
			for item in sourceCollection:
				self.add(item)

	# Accessor methods
	def isEmpty(self):
		"""Returns True if len(self) == 0, or False otherwise."""
		return len(self) == 0

	def __len__(self):
		"""Returns the logical number of items in self"""
		return self._size  # 返回逻辑大小

	# Mutator methods
	def clear(self):
		"""Makes self become empty"""
		self._size = 0
		self._items = Array(ArraySotrtedBag.DEFAULT_CAPACITY)

	def add(self, item):
		"""Add item to self"""
		# check array memmory here and increase it if necessary

		# 插入排序
		if self._size == 0:
			self._items[0] = item
		else:
			index = len(self) - 1
			while index >= 0:
				if self._items[index] > item:
					self._items[index + 1] = self._items[index]
					index -= 1
				else:
					break
			self._items[index + 1] = item
		self._size += 1
		# 当数组的逻辑大小超过ArrayBag.DEFAULT_CAPACITY=10(物理大小)时,增加数组容量
		if self._size == ArraySotrtedBag.DEFAULT_CAPACITY:
			temp = Array(ArraySotrtedBag.DEFAULT_CAPACITY + 1)
			for i in range(len(self) - 1):
				temp[i] = self._items[i]
			self._items = temp

	def __iter__(self):
		"""Supports iteration over a view of self"""
		cursor = 0
		while cursor < len(self):
			yield self._items[cursor]  # 通过yield方法,将每一项都发送给for循环调用
			cursor += 1

	def __str__(self):
		"""returns the  string representation of self"""
		return "{" + ", ".join(map(str, self)) + "}"

	def __add__(self, other):
		"""returns a new bag containing the contents of self and other"""
		result = ArraySotrtedBag(self)
		for item in other:
			result.add(item)
		return result

	def __eq__(self, other):
		"""returns true if self equals other, or false otherwise"""
		if self is other: return True
		if type(self) != type(other) or \
				len(self) != len(other):
			return False
		# for item in self:
		# 	if item not in other:
		# 		return False
		# 用for和迭代器两种迭代可以将
		otherIter = iter(other)
		for item in self:
			if item != next(otherIter):
				return False
		return True

	def remove(self, item):
		"""check precondition and raise if necessary"""
		if item not in self:
			raise KeyError(str(item) + " not in bag")
		targetIndex = 0
		for targetItem in self:
			if targetItem == item:
				break
			targetIndex += 1
		for i in range(targetIndex, len(self) - 1):
			self._items[targetIndex] = self._items[targetIndex + 1]
		self._size -= 1
		# 当数组逻辑大小小于或等于物理大小的四分之一,并且其物理大小至少
		# 是创建数组的默认容量的两倍的时候。
		if self._size <= ArraySotrtedBag.DEFAULT_CAPACITY:
			temp = Array(ArraySotrtedBag.DEFAULT_CAPACITY // 2)
			for i in range(self._size):
				temp[i] = self._items[i]
			self._items = temp

	def __contains__(self, item):
		# 二叉搜索已经排好序的数组
		left = 0
		right = len(self) - 1
		while left < right:
			middle = (left + right) // 2
			if item == self._items[middle]:
				return True
			elif item < self._items[middle]:
				right = middle - 1
			else:
				left = middle + 1
		return False

	def insertSorted(self):
		length = len(self)
		i = 1
		while i < length:
			insertItem = self._items[i]
			j = i - 1
			while j > 0:
				if self._items[j] > insertItem:
					self._items[j + 1] = self._items[j]
					j -= 1
				else:
					break
			self._items[j + 1] = insertItem
			i += 1


if __name__ == "__main__":
	lyst = list(range(6, 1, -1))
	# print(lyst)
	head = None
	for count in range(5):
		head = Node(lyst[count], head)

	probe = head
	linkedBag = LinkedBag(probe)
	linkedBag.removeItem(4)  # {6, 5, 3, 2}
	linkedBag.removeIndex(1)  # {6, 3, 2}
	print(linkedBag)

	"""
	2 3 4 5 6
	"""
	probe = head
	while probe != None:
		print(probe.data, end=" ")
		probe = probe.next
	print()  # 添加一个换行符
	arraySortedBag = ArraySotrtedBag(lyst)
	# arraySortedBag: {2, 3, 4, 5, 6}
	print("arraySortedBag:", arraySortedBag)
	print(2 in arraySortedBag)  # True
	print(1 in arraySortedBag)  # False
	# add方法按顺序添加项
	# {2, 3, 4, 5, 6, 9, 10}
	arraySortedBag.add(10)
	arraySortedBag.add(9)
	print(arraySortedBag)
	# 题目1
	"""
	__eq__实现1
		def __eq__(self, other):
		if self is other: return True
		if type(self) != type(other) or \
				len(self) != len(other):
			return False
		# for item in self:
		# 	if item not in other:
		# 		return False
		# 用for和迭代器两种迭代可以将
		otherIter = iter(other)
		for item in self:
			if item != next(otherIter):
				return False
		return True
		# 返回
		{2, 3, 4, 5, 6, 9, 10}
		{2, 3, 3, 4, 5}
		False
		interval  time: 6.564099871138514e-06 # 时间更短
	__eq__实现2
		def __eq__(self, other):
		if self is other: return True
		if type(self) != type(other) or \
				len(self) != len(other):
			return False
		for item in self:
			if item not in other:
				return False
		# 用for和迭代器两种迭代可以将
		# otherIter = iter(other)
		# for item in self:
		# 	if item != next(otherIter):
		# 		return False
		return True
		# 返回
		{2, 3, 4, 5, 6, 9, 10}
		{2, 3, 3, 4, 5}
		False
		interval  time: 9.435893564761614e-06
	"""
	lyst1 = lyst
	lyst1[0] = 3
	arraySortedBag1 = ArraySotrtedBag(lyst1)
	print(arraySortedBag1)
	start = time.clock()
	print(arraySortedBag1 == arraySortedBag)
	end = time.clock()
	print("interval  time:", end)

猜你喜欢

转载自blog.csdn.net/liudaoqiang_tj/article/details/82312949
6.6