python语言算法_数据结构与算法 Python语言实现 第二章练习

1 #项目

2 #P-2.33

3 #class FirstDerivative:

4 importtime5

6

7 defcalculate(d):8 d_split =d.split()9 #print(d_split)

10 new_d = ''

11

12 for x ind_split:13 if 'X' inx:14

15 X_split = x.split('X')16 X_split.reverse()17 #print(X_split)

18 new_l1 =019 new_l2 =020 l2 =021 for l inX_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 andl2:28 new_l1 = str(int(l_split[0]) *l2)29 l2 =030 elif len(l_split) == 2 and notl2:31 new_l1 =l_split[0]32 elif len(l_split) == 1 andl2:33 new_l1 =l234 l2 =035 if new_l1 andnew_l2:36 new_d += '%s*X**%s+' %(new_l1, new_l2)37 elif new_l1 and notnew_l2:38 new_d += '%s' %new_l139 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 classDocumentReader:67

68 def __init__(self, filepath):69 self._filepath =filepath70 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 inall_text:79 if ord('a') <= ord(char) <= ord('z'):80 if char not inself._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 inself._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 importrandom140

141

142 classAlice:143 CHANCE_OF_ACT = 0.3

144

145 def __init__(self):146 self.package =None147

148 defact(self):149 if random.random() <150 self.package="self._package()151" returntrue152 returnfalse153>

154 @staticmethod155 def_package():156 char = ''

157 for i in range(5):158 char += chr(ord('a') + random.randint(0, ord('z') - ord('a')))159 returnchar160

161 def_delete_package(self):162 self.package =None163 print('Delete Package !!!')164

165

166 classInternet:167

168 def __init__(self):169 self._sender =None170

171 defcheck_package(self):172 ifself._sender.package:173 returnself._sender.package174 else:175 returnNone176

177 defdelete_package(self):178 self._sender.package =None179 print('Delete package!')180

181 defassign_sender(self, sender):182 self._sender =sender183

184

185 classBob:186

187 @staticmethod188 defcheck_package(other):189 print('Bob Get package: %s' %other.check_package())190

191 @staticmethod192 defdelete_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 classRiverEcosystem:212 classBear:213 def __init__(self, location):214 self._location =location215

216 classFish:217 def __init__(self, location):218 self._location =location219

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] *length225

226 self._bears =self.assign_object(self.Bear, bears)227 self._fish =self.assign_object(self.Fish, fish)228

229 self._time =0230

231 def __len__(self):232 returnlen(self._ecosystem)233

234 def __getitem__(self, index):235 returnself._ecosystem[index]236

237 def __setitem__(self, key, value):238 self._ecosystem[key] =value239

240 defassign_object(self, obj, number):241 assigned =0242 object_list =[]243 maximum_attempts = 100

244 attempts =0245 while assigned < number and attempts <246 attempts>

247 i = random.randint(0, len(self) - 1)248 if self[i] isNone:249 new_obj =obj(i)250 assigned += 1

251 self[i] =new_obj252 object_list.append(new_obj)253 returnobject_list254

255 deftime_step(self):256 self._time += 1

257 for f inself._fish:258 self.determine_action(f)259 for b inself._bears:260 self.determine_action(b)261

262 defdetermine_action(self, obj):263 if random.random() <264 if random.random self._attempt_move obj._location else:267>

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 returnFalse273 elif self[target_location] isNone: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 elifisinstance(obj, self.Fish):280 self._delete_object(obj, self._fish)281 elifisinstance(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 =None286

287 for i inrange(len(obj_list)):288 if obj isobj_list[i]:289 target =i290 if target is notNone:291 delobj_list[target]292

293 def __repr__(self):294 output_string =[]295 for element inself._ecosystem:296 if element isNone:297 output_string += '-'

298 elifisinstance(element, self.Bear):299 output_string += 'B'

300 elifisinstance(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 importrandom323

324

325 #These should be nested in theory and then accessed using self.Bear, or self.Fish

326

327

328 classRiverEcosystem:329 classBear:330 def __init__(self, location):331 self._location =location332

333 classFish:334 def __init__(self, location):335 self._location =location336

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] *length342

343 self._bears =self.assign_object(self.Bear, bears)344 self._fish =self.assign_object(self.Fish, fish)345

346 self._time =0347

348 def __len__(self):349 returnlen(self._ecosystem)350

351 def __getitem__(self, index):352 returnself._ecosystem[index]353

354 def __setitem__(self, index, value):355 self._ecosystem[index] =value356

357 defassign_object(self, obj, number):358 assigned =0359 object_list =[]360 maximum_attempts = 100

361 attempts =0362 while assigned < number and attempts <363 attempts>

364 i = random.randint(0, len(self) - 1)365 if self[i] isNone:366 new_obj =obj(i)367 assigned += 1

368 self[i] =new_obj369 object_list.append(new_obj)370 returnobject_list371

372 def __repr__(self):373 output_string =[]374 for element inself._ecosystem:375 if element isNone:376 output_string += '-'

377 elifisinstance(element, self.Bear):378 output_string += 'B'

379 elifisinstance(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 =None389

390 for i inrange(len(obj_list)):391 if obj isobj_list[i]:392 target =i393 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 returnFalse399 elif self[target_location] isNone: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 elifisinstance(obj, self.Fish):406 self._delete_object(obj, self._fish)407 elifisinstance(self[target_location], self.Fish):408 self._delete_object(self[target_location], self._fish)409

410 defdetermine_action(self, obj):411 if random.random() <412 if random.random self._attempt_move obj._location>

415 else:416 self._attempt_move(obj, obj._location + 1)417

418 deftimestep(self):419 self._time += 1

420 for f inself._fish:421 self.determine_action(f)422 for b inself._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 classRiverEcosystem2(RiverEcosystem):445 classBear():446 def __init__(self, location):447 self._location =location448 self._strength =random.random()449 self._gender = True if random.random() > 0.5 elseFalse450

451 classFish():452 def __init__(self, location):453 self._location =location454 self._strength =random.random()455 self._gender = True if random.random() > 0.5 elseFalse456

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 returnFalse461 elif self[target_location] isNone: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=lambdax: x._strength)470 object_list = self._fish if isinstance(obj, self.Fish) elseself._bears471 #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 elifisinstance(obj, self.Fish):476 self._delete_object(obj, self._fish)477 elifisinstance(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 classMockSystem:498

499 def __init__(self, name, books=None):500 self.name =name501 self.books = books or[]502

503 defbuy_book(self, book_name, read_method):504 self.books.append({book_name: read_method})505

506 defcheckout_book(self):507 returnself.books508

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 importABCMeta,abstractmethod518

519

520 class Polygon(metaclass=ABCMeta):521

522 @abstractmethod523 defarea(self):524 pass

525

526 @abstractmethod527 defperimeter(self):528 pass

529

530

531 classTriangle(Polygon):532

533 def __init__(self, a, b, c, height):534 self._a =a535 self._b =b536 self._c =c537 self._height =height538

539 defarea(self):540 return (self._c * self._height)/2

541

542 defperimeter(self):543 return self._a + self._b +self._c544

545

546 classQuadrilateral(Polygon):547

548 def __init__(self, a, b, c, d, height):549 self._a =a550 self._b =b551 self._c =c552 self._d =d553

554 defarea(self):555 pass

556

557 defperimeter(self):558 return self._a + self._b + self._c + self._d

412>363>264>246>150>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值