数据结构与算法 Python语言实现 第二章练习
巩固
1 # R-2.4 2 import random 3 import time 4 from datetime import datetime 5 6 7 class Flower: 8 """描述花的类,包含花的名字,花瓣的数量,价格""" 9 10 def __init__(self, name, num, price): 11 if not isinstance(name, str): 12 raise TypeError('Name should be str!') 13 if not isinstance(num, int): 14 raise TypeError('Num should be int!') 15 if not isinstance(price, float): 16 raise TypeError('Price should be float!') 17 self._name = name 18 self._num = num 19 self._price = price 20 21 22 # f = Flower('牵牛花', 12, 3.8) 23 # print(f._name) 24 25 26 # R-2.5 ~ R-2.7 27 class CreditCard: 28 """A consumer credit card.""" 29 30 def __init__(self, customer, bank, acnt, limit, balance=0): 31 self._customer = customer 32 self._bank = bank 33 self._account = acnt 34 self._limit = limit 35 self._balance = balance # R-2.7 36 37 def get_customer(self): 38 return self._customer 39 40 def get_bank(self): 41 return self._bank 42 43 def get_account(self): 44 return self._account 45 46 def get_limit(self): 47 return self._limit 48 49 def get_balance(self): 50 return self._balance 51 52 def charge(self, price): 53 if not (isinstance(price, int) or isinstance(price, float)): # R-2.5 54 raise TypeError('Price should be number!') 55 if price + self._balance > self._limit: 56 return False 57 else: 58 self._balance += price 59 return True 60 61 def make_payment(self, amount): 62 if not (isinstance(amount, int) or isinstance(amount, float)): # R-2.5 63 raise TypeError('Amount should be number!') 64 if amount < 0: # R-2.6 65 raise ValueError('Amount should not be negative!!!') 66 self._balance -= amount 67 68 def _set_balance(self, b): 69 self._balance += b 70 71 72 # Murray_Card = CreditCard('Murray', 'BOC', 123, 10000) 73 # Murray_Card.charge(20) 74 # Murray_Card.make_payment(30) 75 # print(Murray_Card.get_balance()) 76 # 77 # Fu = CreditCard('Fu', 'BOC', 1234, 10000, 100) 78 # print(Fu.get_balance()) 79 80 81 # R-2.8 82 # 第三张信用卡超支,可以假设第三张charge 5100 超支,前两张都未超支 83 84 85 # R-2.9 -- R-2.15 86 class Vector: 87 88 def __init__(self, d): 89 if isinstance(d, int): 90 self._coords = [0] * d 91 elif isinstance(d, list): 92 self._coords = d 93 94 def __len__(self): 95 return len(self._coords) 96 97 def __getitem__(self, item): 98 return self._coords[item] 99 100 def __setitem__(self, key, value): 101 self._coords[key] = value 102 103 def __add__(self, other): 104 # print(self) 105 if len(self) != len(other): 106 raise ValueError('dimensions must agree') 107 result = Vector(len(self)) 108 for j in range(len(self)): 109 result[j] = self[j] + other[j] 110 return result 111 112 def __radd__(self, other): 113 return self.__add__(other) 114 115 def __eq__(self, other): 116 return self._coords == other._coords 117 118 def __ne__(self, other): 119 return not self == other 120 121 def __str__(self): 122 return '<' + str(self._coords)[1:-1] + '>' 123 124 def __sub__(self, other): 125 if len(self) != len(other): 126 raise TypeError('Dimensions must agree!') 127 result = Vector(len(self)) 128 for i in range(len(self)): 129 result[i] = self[i] - other[i] 130 return result 131 132 def __neg__(self): 133 for i in range(len(self)): 134 self[i] = -self[i] 135 return self 136 137 def __mul__(self, other): 138 if isinstance(other, int): 139 result = Vector(len(self)) 140 for i in range(len(self)): 141 result[i] = other * self[i] 142 return result 143 elif isinstance(other, Vector): 144 result = Vector(len(self)) 145 for i in range(len(self)): 146 result[i] = self[i] * other[i] 147 return result 148 149 def __rmul__(self, other): 150 return self.__mul__(other) 151 152 153 # v1 = Vector(3) 154 # v1[0] = 1 155 # v1[1] = 2 156 # v1[2] = 3 157 # # v2 = Vector(3) 158 # # v2[0] = 0 159 # # v2[1] = 1 160 # # v2[2] = 2 161 # # v3 = Vector(4) 162 # # print(v1 == v2) 163 # # print(v1 != v2) 164 # # print(v2 - v1) 165 # # print(v2) 166 # # print(-v2) 167 # # v = v2 + [1, 1, 1] 168 # # print(v) 169 # # print(v * 3) 170 # # print(3 * v) 171 # # 172 # # print(v1 * v2) 173 # print(v1) 174 # v1.name = 123 175 # print(v1.name) 176 177 # vv = Vector([1, 2, 3, 4]) 178 # print(vv) 179 # print(3 * vv) 180 181 182 # R-2.16 183 # start stop step 184 # start + step * (len - 1) <= stop - 1 185 # ----> len <= (stop - start + step - 1) / step 186 # --- > len = (stop - start + step - 1) // step 187 188 189 # R-2.17 190 # object ===>Goat self._tail milk() jump() 191 # ===>Pig self._nose eat(food) wallow() 192 # ===>Horse self._height, self._color run() jump() --->Racer race() 193 # --->Equestrian self._weight trot() is_trained() 194 195 196 # R-2.18 197 class Progression: 198 199 def __init__(self, start=0): 200 self._current = start 201 202 def _advance(self): 203 self._current += 1 204 205 def __next__(self): 206 if self._current is None: 207 raise StopIteration() 208 else: 209 answer = self._current 210 self._advance() 211 return answer 212 213 def __iter__(self): 214 return self 215 216 def print_progression(self, n): 217 print(' '.join(str(next(self)) for j in range(n))) 218 219 220 # p = Progression(0) 221 # print(next(p)) 222 # print(next(p)) 223 # print(next(p)) 224 # print(next(p)) 225 # p.print_progression(3) 226 227 228 class FibonacciProgression(Progression): 229 230 def __init__(self, first=0, second=1): 231 super().__init__() 232 self._prev = second - first 233 234 def _advance(self): 235 self._prev, self._current = self._current, self._prev + self._current 236 237 238 f = FibonacciProgression() 239 240 # FibonacciProgression(2, 2).print_progression(8) 241 242 243 # R-2.19 244 class ArithmeticProgression(Progression): 245 246 def __init__(self, increment=1, start=0): 247 super().__init__(start) 248 self._increment = increment 249 250 def _advance(self): 251 self._current += self._increment 252 253 254 times = 0 255 a = ArithmeticProgression(128, 0) 256 n = next(a) 257 # while n <= 2 ** 63: 258 # n = next(a) 259 # times += 1 260 # print(times) 261 262 263 # print(2 ** 63) 264 265 266 # R-2.20 267 # 继承树很深的劣势 268 # 1/查找方法不方便,在使用新的方法时,需要确认父类是否有同名方法 269 # 2/实例化子类时,需要初始化的类比较多 270 # 271 # 272 # # R-2.21 273 # 1/需要类Z通用性非常强,类中的方法需要满足子类使用,否则需要在子类中重新写此方法进行覆盖 274 275 276 # R-2.22 277 from abc import ABCMeta, abstractmethod 278 279 280 class Sequence(metaclass=ABCMeta): 281 282 @abstractmethod 283 def __len__(self): 284 """Return the length of the sequence""" 285 286 @abstractmethod 287 def __getitem__(self, item): 288 """Return the element at index j of the sequence""" 289 290 def __contains__(self, item): 291 for j in range(len(self)): 292 if self[j] == item: 293 return True 294 return False 295 296 def index(self, val): 297 for j in range(len(self)): 298 if self[j] == val: 299 return j 300 raise ValueError('value not in sequence') 301 302 def count(self, val): 303 k = 0 304 for j in range(len(self)): 305 if self[j] == val: 306 k += 1 307 return k 308 309 def __eq__(self, other): 310 if len(self) != len(other): 311 return False 312 else: 313 for j in range(len(self)): 314 if self[j] != other[j]: 315 return False 316 return True 317 318 # R-2.23 319 def __lt__(self, other): 320 for key in self: 321 if self[key] != other[key]: 322 return False 323 if len(self) < len(other): 324 return True
创新
1 # 创新 2 # C-2.24 3 # 购买方式 4 # 时间,价格,折扣 5 # 6 # 购书清单 7 # 已付款,待付款,已过期 8 # 9 # 已购书籍查看 10 11 12 # C-2.25 详见R-2.12测试部分 13 14 15 # C-2.26 16 class ReversedSequenceIterator: 17 18 def __init__(self, sequence): 19 self._seq = sequence 20 self._k = len(self._seq) 21 22 def __next__(self): 23 self._k -= 1 24 if self._k >= 0: 25 return self._seq[self._k] 26 else: 27 raise StopIteration() 28 29 def __iter__(self): 30 return self 31 32 33 # r = ReversedSequenceIterator([1, 2, 3, 4, 5]) 34 # print(next(r)) 35 # print(next(r)) 36 # print(next(r)) 37 # for i in r: 38 # print(i) 39 40 41 # C-2.27 42 class Range: 43 44 def __init__(self, start, stop=None, step=1): 45 46 if step == 0: 47 raise ValueError('step cannot be 0') 48 49 if stop is None: 50 start, stop = 0, start 51 52 self._length = max(0, (stop-start+step-1)//step) 53 54 self._start = start 55 self._step = step 56 57 def __len__(self): 58 return self._length 59 60 def __getitem__(self, k): 61 if k < 0: 62 k += len(self) 63 64 if not 0 <= k <= self._length: 65 raise IndexError('Index out of range!') 66 67 return self._start + k * self._step 68 69 def __contains__(self, item): 70 quotient, remainder = divmod((item - self._start), self._step) 71 if remainder == 0 and 0 <= quotient <= self._length: 72 return True 73 else: 74 return False 75 76 # r = Range(10) 77 # print(r[-1]) 78 # print(2 in Range(10000000)) 79 # print(9999999 in Range(10000000)) 80 81 82 # C-2.28 - C-2.30 83 class PredatoryCreditCard(CreditCard): 84 85 def __init__(self, customer, bank, acnt, limit, apr, min_pay): 86 super().__init__(customer, bank, acnt, limit) 87 self._apr = apr 88 self.call_times_per_month = {} 89 self._min_pay = min_pay 90 self._pay_amount = 0 91 92 def charge(self, price): 93 success = super().charge(price) 94 if not success: 95 self._balance += 5 96 return success 97 98 def process_month(self): 99 if self._balance > 0: 100 monthly_factor = pow((1 + self._apr), 1/12) 101 self._balance *= monthly_factor 102 103 def call_per_monty(self): 104 year = datetime.now().year 105 month = datetime.now().month 106 if "%s:%s" % (year, month) not in self.call_times_per_month: 107 self.call_times_per_month["%s:%s" % (year, month)] = 1 108 else: 109 self.call_times_per_month["%s:%s" % (year, month)] += 1 110 if self.call_times_per_month["%s:%s" % (year, month)] > 10: 111 self._balance += 1 112 print(self.call_times_per_month) 113 114 def make_payment(self, amount): 115 super().make_payment(amount) 116 self._pay_amount += amount 117 118 def evaluate_delay_fee(self): 119 if self._pay_amount < self._min_pay: 120 pass # 评估延迟费用 121 122 def _set_balance(self, b): 123 super()._set_balance(b) 124 125 126 # p = PredatoryCreditCard('Murry', 'BOC', 123456, 100, 6.01) 127 # p.call() 128 # p.call() 129 # p.call() 130 # p.call() 131 # print(p.get_balance()) 132 133 134 # C-2.31 135 class MyProgression(Progression): 136 137 def __init__(self, first=2, second=200): 138 super().__init__() 139 self._first = first 140 self._second = second 141 self._current = abs(self._first - self._second) 142 143 def _advance(self): 144 self._first, self._second = self._second, self._current 145 self._current = abs(self._first - self._second) 146 147 148 # mp = MyProgression() 149 # print(next(mp)) 150 # print(next(mp)) 151 # print(next(mp)) 152 # print(next(mp)) 153 # print(next(mp)) 154 155 156 class SqrProgression(Progression): 157 158 def __init__(self, num): 159 super().__init__() 160 self._current = pow(num, 1/2) 161 162 def _advance(self): 163 self._current = pow(self._current, 1/2) 164 165 166 # s = SqrProgression(65536) 167 # print(next(s)) 168 # print(next(s)) 169 # print(next(s)) 170 # print(next(s)) 171 # print(next(s))
项目
1 # 项目 2 # P-2.33 3 # class FirstDerivative: 4 import time 5 6 7 def calculate(d): 8 d_split = d.split() 9 # print(d_split) 10 new_d = '' 11 12 for x in d_split: 13 if 'X' in x: 14 15 X_split = x.split('X') 16 X_split.reverse() 17 # print(X_split) 18 new_l1 = 0 19 new_l2 = 0 20 l2 = 0 21 for l in X_split: 22 l_split = l.split('*') 23 # print('l_split', l_split, len(l_split)) 24 if len(l_split) == 3: 25 l2 = int(l_split[2]) # X的幂 26 new_l2 = str(int(l_split[2]) - 1) # 转换为降幂 27 elif len(l_split) == 2 and l2: 28 new_l1 = str(int(l_split[0]) * l2) 29 l2 = 0 30 elif len(l_split) == 2 and not l2: 31 new_l1 = l_split[0] 32 elif len(l_split) == 1 and l2: 33 new_l1 = l2 34 l2 = 0 35 if new_l1 and new_l2: 36 new_d += '%s*X**%s+' % (new_l1, new_l2) 37 elif new_l1 and not new_l2: 38 new_d += '%s' % new_l1 39 else: 40 new_d += '1' 41 if new_d.endswith('+'): 42 new_d = '+'.join(new_d.split('+')[0:-1]) 43 44 print(new_d) 45 46 47 # d = '3*X**4 + 2*X**2 + 3*X + 1' 48 # calculate(d) 49 50 # P-2.34 51 # from collections import Counter 52 # import matplotlib.pyplot as plt 53 # 54 # 55 # def counter(s): 56 # c = Counter(s) 57 # return c 58 59 60 # s = 'abcdefghijklmn,abcdefg!abcd.abc?a' 61 # c = counter(s) 62 # plt.bar(c.keys(), c.values()) 63 # plt.show() 64 65 # 上面是使用python模块,下面方法是不使用python模块 66 class DocumentReader: 67 68 def __init__(self, filepath): 69 self._filepath = filepath 70 self._char_dic = {} 71 72 self._read_file() 73 self._show_char() 74 75 def _read_file(self): 76 fp = open(self._filepath) 77 all_text = fp.read().lower() 78 for char in all_text: 79 if ord('a') <= ord(char) <= ord('z'): 80 if char not in self._char_dic: 81 self._char_dic[char] = 1 82 else: 83 self._char_dic[char] += 1 84 85 def _show_char(self): 86 for char in self._char_dic: 87 print(char, '*' * self._char_dic[char]) 88 89 # DocumentReader('text_test') 90 91 92 # P-2.35 93 # import time 94 # 95 # 96 # class Alice: 97 # 98 # def __init__(self, q): 99 # self.q = q 100 # self.n = 0 101 # while True: 102 # self.send_package() 103 # self.n += 1 104 # time.sleep(10) 105 # 106 # def send_package(self): 107 # self.q.put('%s Hello Bob!' % self.n) 108 # print('Send msg! %s' % self.n) 109 # 110 # 111 # class Bob: 112 # 113 # def __init__(self, q): 114 # self.q = q 115 # while True: 116 # self.receive_package() 117 # time.sleep(6) 118 # 119 # def receive_package(self): 120 # msg = self.q.get() 121 # print('Bob get the message: %s' % msg) 122 123 124 # if __name__ == '__main__': # 多进程 125 # from multiprocessing import Process, Queue 126 # 127 # qq = Queue() 128 # 129 # a = Process(target=Alice, args=(qq,)) 130 # b = Process(target=Bob, args=(qq, )) 131 # 132 # a.start() 133 # b.start() 134 # a.join() 135 # b.join() 136 137 138 # 不适用多进程通讯Queue,创建 139 import random 140 141 142 class Alice: 143 CHANCE_OF_ACT = 0.3 144 145 def __init__(self): 146 self.package = None 147 148 def act(self): 149 if random.random() < self.CHANCE_OF_ACT: 150 self.package = self._package() 151 return True 152 return False 153 154 @staticmethod 155 def _package(): 156 char = '' 157 for i in range(5): 158 char += chr(ord('a') + random.randint(0, ord('z') - ord('a'))) 159 return char 160 161 def _delete_package(self): 162 self.package = None 163 print('Delete Package !!!') 164 165 166 class Internet: 167 168 def __init__(self): 169 self._sender = None 170 171 def check_package(self): 172 if self._sender.package: 173 return self._sender.package 174 else: 175 return None 176 177 def delete_package(self): 178 self._sender.package = None 179 print('Delete package!') 180 181 def assign_sender(self, sender): 182 self._sender = sender 183 184 185 class Bob: 186 187 @staticmethod 188 def check_package(other): 189 print('Bob Get package: %s' % other.check_package()) 190 191 @staticmethod 192 def delete_package(other): 193 other.delete_package() 194 195 196 # alice = Alice() 197 # bob = Bob() 198 # internet = Internet() 199 # 200 # for i in range(20): 201 # if alice.act(): 202 # internet.assign_sender(alice) 203 # bob.check_package(internet) 204 # bob.delete_package(internet) 205 # else: 206 # time.sleep(1) 207 # print('No message......') 208 209 210 # P-2.36 211 class RiverEcosystem: 212 class Bear: 213 def __init__(self, location): 214 self._location = location 215 216 class Fish: 217 def __init__(self, location): 218 self._location = location 219 220 MOVE_CHANCE = 0.3 221 LR_CHANCE = 0.5 # 向左向右移动概率相同 222 223 def __init__(self, length=100, bears=3, fish=10): 224 self._ecosystem = [None] * length 225 226 self._bears = self.assign_object(self.Bear, bears) 227 self._fish = self.assign_object(self.Fish, fish) 228 229 self._time = 0 230 231 def __len__(self): 232 return len(self._ecosystem) 233 234 def __getitem__(self, index): 235 return self._ecosystem[index] 236 237 def __setitem__(self, key, value): 238 self._ecosystem[key] = value 239 240 def assign_object(self, obj, number): 241 assigned = 0 242 object_list = [] 243 maximum_attempts = 100 244 attempts = 0 245 while assigned < number and attempts < maximum_attempts: 246 attempts += 1 247 i = random.randint(0, len(self) - 1) 248 if self[i] is None: 249 new_obj = obj(i) 250 assigned += 1 251 self[i] = new_obj 252 object_list.append(new_obj) 253 return object_list 254 255 def time_step(self): 256 self._time += 1 257 for f in self._fish: 258 self.determine_action(f) 259 for b in self._bears: 260 self.determine_action(b) 261 262 def determine_action(self, obj): 263 if random.random() < self.MOVE_CHANCE: 264 if random.random() < self.LR_CHANCE: 265 self._attempt_move(obj, obj._location - 1) 266 else: 267 self._attempt_move(obj, obj._location + 1) 268 269 def _attempt_move(self, obj, target_location): 270 if target_location < 0 or target_location >= len(self): 271 # Move is out of bounds 272 return False 273 elif self[target_location] is None: 274 self[obj._location], self[target_location] = self[target_location], self[obj._location] 275 elif type(obj) == type(self[target_location]): 276 # if there are the same type, create one new instance of that object 277 self.assign_object(type(obj), 1) 278 # if not the same, check who is the fish... 279 elif isinstance(obj, self.Fish): 280 self._delete_object(obj, self._fish) 281 elif isinstance(self[target_location], self.Fish): 282 self._delete_object(self[target_location], self._fish) 283 284 def _delete_object(self, obj, obj_list): 285 target = None 286 287 for i in range(len(obj_list)): 288 if obj is obj_list[i]: 289 target = i 290 if target is not None: 291 del obj_list[target] 292 293 def __repr__(self): 294 output_string = [] 295 for element in self._ecosystem: 296 if element is None: 297 output_string += '-' 298 elif isinstance(element, self.Bear): 299 output_string += 'B' 300 elif isinstance(element, self.Fish): 301 output_string += 'F' 302 else: 303 output_string += '?' 304 return ''.join(output_string) 305 306 307 Gamel = RiverEcosystem(100) 308 print('Currently playing a game with 3 bears and 10 fish') 309 for _ in range(40): 310 print(Gamel) 311 Gamel.time_step() 312 print('\n\n') 313 314 Game2 = RiverEcosystem(100, 10, 10) 315 print('Currently playing a game with 10 bears and 10 fish') 316 for _ in range(40): 317 print(Game2) 318 Game2.time_step() 319 320 321 # -------------------P2-36--------------------- 322 import random 323 324 325 # These should be nested in theory and then accessed using self.Bear, or self.Fish 326 327 328 class RiverEcosystem: 329 class Bear: 330 def __init__(self, location): 331 self._location = location 332 333 class Fish: 334 def __init__(self, location): 335 self._location = location 336 337 MOVE_CHANCE = 0.3 338 LR_CHANCE = 0.5 339 340 def __init__(self, length=100, bears=3, fish=10): 341 self._ecosystem = [None] * length 342 343 self._bears = self.assign_object(self.Bear, bears) 344 self._fish = self.assign_object(self.Fish, fish) 345 346 self._time = 0 347 348 def __len__(self): 349 return len(self._ecosystem) 350 351 def __getitem__(self, index): 352 return self._ecosystem[index] 353 354 def __setitem__(self, index, value): 355 self._ecosystem[index] = value 356 357 def assign_object(self, obj, number): 358 assigned = 0 359 object_list = [] 360 maximum_attempts = 100 361 attempts = 0 362 while assigned < number and attempts < maximum_attempts: 363 attempts += 1 364 i = random.randint(0, len(self) - 1) 365 if self[i] is None: 366 new_obj = obj(i) 367 assigned += 1 368 self[i] = new_obj 369 object_list.append(new_obj) 370 return object_list 371 372 def __repr__(self): 373 output_string = [] 374 for element in self._ecosystem: 375 if element is None: 376 output_string += '-' 377 elif isinstance(element, self.Bear): 378 output_string += 'B' 379 elif isinstance(element, self.Fish): 380 output_string += 'F' 381 else: 382 output_string += '?' 383 384 return ''.join(output_string) 385 386 def _delete_object(self, obj, obj_list): 387 # Challenge is to also delete it from the list of bears/fish 388 target = None 389 390 for i in range(len(obj_list)): 391 if obj is obj_list[i]: 392 target = i 393 if target is not None: del (obj_list[target]) 394 395 def _attempt_move(self, obj, target_location): 396 if target_location < 0 or target_location >= len(self): 397 # print ('Move is out of bounds') 398 return False 399 elif self[target_location] is None: 400 self[obj._location], self[target_location] = self[target_location], self[obj._location] 401 elif type(obj) == type(self[target_location]): 402 # if they are the same type, create one new instance of that object 403 self.assign_object(type(obj), 1) 404 # if not the same, check who is the fish... 405 elif isinstance(obj, self.Fish): 406 self._delete_object(obj, self._fish) 407 elif isinstance(self[target_location], self.Fish): 408 self._delete_object(self[target_location], self._fish) 409 410 def determine_action(self, obj): 411 if random.random() < self.MOVE_CHANCE: 412 if random.random() < self.LR_CHANCE: 413 self._attempt_move(obj, obj._location - 1) 414 415 else: 416 self._attempt_move(obj, obj._location + 1) 417 418 def timestep(self): 419 self._time += 1 420 for f in self._fish: 421 self.determine_action(f) 422 for b in self._bears: 423 self.determine_action(b) 424 425 426 Game1 = RiverEcosystem(100) 427 print('Currently playing a game with 3 bears and 10 fish') 428 for _ in range(40): 429 print(Game1) 430 Game1.timestep() 431 print('\n\n') 432 433 Game2 = RiverEcosystem(100, 10, 10) 434 print('Currently playing a game with 10 bears and 10 fish') 435 for _ in range(40): 436 print(Game2) 437 Game2.timestep() 438 439 440 # ----------------P2-37------------------------ 441 # Note, you must run the cell from P2-36 to get the RiverEcosystem class 442 443 444 class RiverEcosystem2(RiverEcosystem): 445 class Bear(): 446 def __init__(self, location): 447 self._location = location 448 self._strength = random.random() 449 self._gender = True if random.random() > 0.5 else False 450 451 class Fish(): 452 def __init__(self, location): 453 self._location = location 454 self._strength = random.random() 455 self._gender = True if random.random() > 0.5 else False 456 457 def _attempt_move(self, obj, target_location): 458 if target_location < 0 or target_location >= len(self): 459 # print ('Move is out of bounds') 460 return False 461 elif self[target_location] is None: 462 self[obj._location], self[target_location] = self[target_location], self[obj._location] 463 464 elif type(obj) == type(self[target_location]): 465 # if they are the same type and gender, create one new instance of that object 466 if obj._gender != self[target_location]._gender: 467 self.assign_object(type(obj), 1) 468 else: 469 to_delete = min(obj, self[target_location], key=lambda x: x._strength) 470 object_list = self._fish if isinstance(obj, self.Fish) else self._bears 471 # print(f'A fight!! Of strengths {obj._strength} and {self[target_location]._strength}, {to_delete._strength} loses') 472 self._delete_object(to_delete, object_list) 473 474 # if not the same, check who is the fish... 475 elif isinstance(obj, self.Fish): 476 self._delete_object(obj, self._fish) 477 elif isinstance(self[target_location], self.Fish): 478 self._delete_object(self[target_location], self._fish) 479 480 481 Game1 = RiverEcosystem2(100) 482 print('Currently playing a game with 3 bears and 10 fish') 483 for _ in range(40): 484 print(Game1) 485 Game1.timestep() 486 print('\n\n') 487 488 Game2 = RiverEcosystem2(100, 10, 10) 489 print('Currently playing a game with 10 bears and 10 fish') 490 for _ in range(40): 491 print(Game2) 492 Game2.timestep() 493 494 495 496 # P-2.38 497 class MockSystem: 498 499 def __init__(self, name, books=None): 500 self.name = name 501 self.books = books or [] 502 503 def buy_book(self, book_name, read_method): 504 self.books.append({book_name: read_method}) 505 506 def checkout_book(self): 507 return self.books 508 509 510 # m = MockSystem('Murray') 511 # m.buy_book('小人书', 'read-on-line') 512 # m.buy_book('大人书', 'read-off-line') 513 # print(m.checkout_book()) 514 515 516 # P-2.39 517 from abc import ABCMeta,abstractmethod 518 519 520 class Polygon(metaclass=ABCMeta): 521 522 @abstractmethod 523 def area(self): 524 pass 525 526 @abstractmethod 527 def perimeter(self): 528 pass 529 530 531 class Triangle(Polygon): 532 533 def __init__(self, a, b, c, height): 534 self._a = a 535 self._b = b 536 self._c = c 537 self._height = height 538 539 def area(self): 540 return (self._c * self._height)/2 541 542 def perimeter(self): 543 return self._a + self._b + self._c 544 545 546 class Quadrilateral(Polygon): 547 548 def __init__(self, a, b, c, d, height): 549 self._a = a 550 self._b = b 551 self._c = c 552 self._d = d 553 554 def area(self): 555 pass 556 557 def perimeter(self): 558 return self._a + self._b + self._c + self._d
View Code
查看代码

浙公网安备 33010602011771号