`
dmhorse
  • 浏览: 24584 次
  • 来自: ...
最近访客 更多访客>>
社区版块
存档分类
最新评论

Python MIT OOPS

阅读更多




[b]



L3:




Italian program



commands

assignment

input/output

condition

loop



print x, 'hello world'


Defensive programming



@ToDo: To test the code List: mylist = [] mylist = mylist + [i] #Here the '+' is overridden already.

mytuple = () mytuple = mytuple + (i) # Does it really work? To be checked.

Answer: Both can be.




[code="python"]mytuple = ('abc')
mytuple = mytuple + ('de')
print mytuple #Show 'abcde' instead of ('abc','de')
[code="python"]mytuple = ('abc','cde')
[code="python"]mytuple += ('fg') #Cause error. Last example because, the tuple convert to string, and the () is ignored.



[img]/admin/blogs/images/callouts/1.png" border="0" alt="1" width="12" height="12[/img]

You can't add elements to a tuple. Tuples have no append
or extend
method.

[img]/admin/blogs/images/callouts/2.png" border="0" alt="2" width="12" height="12[/img]

You can't remove elements from a tuple. Tuples have no remove
or pop
method.

[img]/admin/blogs/images/callouts/3.png" border="0" alt="3" width="12" height="12[/img]

You can't find elements in a tuple. Tuples have no index
method.

[img]/admin/blogs/images/callouts/4.png" border="0" alt="4" width="12" height="12[/img]

You can, however, use in
to see if an element exists in the tuple.



L4:


@Todo: To simulate

return None , no value assign to variable, but when use '==' to check, it return 'true'. Too suprised


[code="python"]def returnNone():
   return None

result = returnNone()
print result # show None # In shell mode, it would be nothing
print (result == None) #show true



@Todo: 20heads, 56 legs, how many chicken and pigs

Done, looping all possible values


@Todo: to verify it return [None,None] return [a,b,c] #return more than 1 value a,b,c = return [a,b,c] #assign to more than 1 variable

Done, actually, it return the tuple or list



@Todo: check Fibonacci number Use recursive method to calculate the numbers

Done, remember to handle the 0 & 1 number.


@Todo:Palindrome, to be write program to test


LS5:


@Todo: 2**1000

In shell prompt, it would large number with 'L'. When use print, auto conver and remove L


@Todo
: x=0.1, print x IEEE 754 floating point @Todo 64bits?? modem computer 64bit? what's that? 1 bit negative/positive 11 bit exponent 52 bit number (mantissa) 17 decimal number @Todo: for i in range(10) s+=0.1 actual result 0.999999999999989, when print, it auto round it.




successive approxmaition (极限法)


bisection method (二分法)


@Todo , try assert in sqrt method

Done. assert (condition), 'not match condition , error and terminate'


@Todo: find out sqrt To solve decimal fraction issue, to tune the program for the espion.

Done, use x*x - y 0):
    ans *= a
    b -= 1
  return ans




Use big O notation



汉诺塔

@Todo: to simulate the twoner

Done


[code="python"]def move (element, from, target)
   print 'move',element, 'from', from, 'target', target

def tower(i, from, target, tmp)
    if (i == 1):
      move(i,from,target)
    elsif
      #move n tower to tmp
      tower(i-1,from,tmp,target)
      #move last one to target
      move(i,from,target)
      #move n-1 tower to target
      twoer(i-1,tmp,target,from)



Complexity calculation as below






t(n) = t(n-2) + t(n-2) + t(n-2) + t(n-2)

t(n) = 2^k ( t(n-k) )




t(n) = 2^(n-1) t(1)




4种算法


@Todo: compare the 4 different alg



@Todo: write Binary search, then compare the one by one search


[code="python"]bsearch(num, list, first, last):
   i= ( first + last ) / 2
   if list[i] == num:
      return true, i
   elif last - first == 1:
      return false
   elif list[i]  num:
      return bsearch (num, list, first, i)


#Complexity calculation

t(n) = t(n/2)
t(n) = t(n/2/2)
t(n) = t(n/2/2/2)
t(n) = t(n/2^k)


2^k= n
k = log2(n)


t(n) = O(

  






@Todo: check link list ,constant list


LinkList: use 2 cell, one for value, the other for next element memory address, when add new one, just change one element, if you find one, you need to iternative some element, next next to skip skip ...


Depends on what element on your hand, if next element is far away, it cost more time.



Constant List: fixed space of each cell value, if add new element, it would reconstrut list
.

Access each element cost same time. You can calculate each skip steps



L9
:

linear


list, python, list of list

use box to save the pointer, each pointer point to a special area contains value.


Before search, sorted or not?

Linear search

N times


@Todo: check linklist, how to store object of object


Sorted + Search

nlog2(n), + log2(n)


If only search 1 time, use linear search


ksearch times

@Use selection sorting method with binary search, found out how many element that worth to sort before search



@Todo: Bubble sorting & selection sorting

Sorting method


Swap the small one



Selection sorting

Bubble section


Done


@Todo, dynamic function.


val=int

val(x)


@Todo list have sort function, to be try to found out how fast of it.


@Todo try assert

raise 'exception'

assert precondition



LS11


function debugging

performance debugging

LS11



Defensive programming


Both validation & debugging


Test: examine input/output

Unit Testing: validate each piece of program indivually, functions classes

Integration testing: PUt whole program togather, see does the program work?


Rush to integration test, but it's big mistake.

Test each part of unit


Easier to test & debug small thing than big thing



Why testing is always challenge


2 best way

Print Statement

Reading


Be systemmatic


@Todo clone list


list = otherlist[:]


different


list = otherlist


LS12[/b]




code should not always grow

Add more code to fix bug


Big Packing

Shortest path

Travles sales person

Sequence alignment

Knapsack problem


Greedy algor


locall optimal decision do not always lead to global opt.


@Todo: Knapsack problem

@Todo: To check optimal fibionic sequence because overlapping problem
overlapping subproblem

optimal structure



Optimal fibionic sequence

fibnoic, optimal to save the value





[code="python"]memres = {0:0,1:1} #init first elements
def getfib(num=10):
  if num in memres: #check key exist:
      return memres[num]

  memres[num] = getfib(num-1) + getfib(num-2)

  return memres[num]

#complexity, O(n) if not save value, O(2^n)



Decision tree


w=5,3,2
V=9,7,8


Each n




2,5,0


index,weight still available,value


2,5,0


1,5,0


0,5,0


@todo, write a decision tree daigram and code


@Todo:use try and raise the exception to check whether list element existing





[code="python"]num=10
assert num>7, 'error' #Assume the exper is correct, otherwise prompt error msg.

 
 


decision tree @to check

1. Depth first , left first
2. Back check

 

 

LS14:

 

Binary decision tree

Size of the problem? Size of the solution?

 

@Todo: problem? Solution?

 

@Knapsack problem, constraint volumn also

 

@Todo: what's pseudo polynomic?

 

 

 

 

LS15

 

 

Shallow equality ( point to same reference)

 

Deep equality

 

pass keyword

 

__init__(self,x,y)

__str__

__cmp__

__eq__ @tocheck this overloading use ==

 

dir(class), you know how many methods

dir(1)

dir('1')

 

LS16

 

 

class template for data type

 

data hidding, encapution

 

class Person(object) #Extend from object

 

 

if type (xxx) == QQ 

@Todo type to judge class

 

LS17

class Location(object)
def __init_(self,x,y)
  x = float(x)
  y = y...
def move(xc,yc)
  return Location(x+xc,y+yc)
def get Coords
 return x,y

def getDis(other)
 cx,cy = getCoords(other)

  xd = x -xc
  yd = y-yc
  return math.sqrt(xd**2,yd**2)

class CompassPt(obj)
 possibles = {n,w,w,..}
 def init(pt)
  if pt in possibles, self.pt = pt
  else: raise error

def move (dist)
  if self.pt == n, return (0,dist)
  elif pt == S, return (0,-dist)
  w (dist,0)
  e (0,dist)
  else: raise error

class field(obj)
  def init (drunk, loc)
   self.d = d
   self.l = l
 def move (self, cp , dist)

   oldLoc = self.d
   xc,yc = cp.move(dist)
   self.loc = oldLoc.move(xc,yc)

def getLoc(self)
return self.loc

def getDrunk(self)
 return self.drunk

class Drunk(obj)

def init(self,name)
def move(self, field, time = 1)
 if field.getDrunk() == self:
  raise error
for i in range(time)
 pt = CompressPt(random.choice(CompressPt.possibles))
 field.move(pt,1)

def performTrial(time,f):
  start = f.getLoc()
  distance = [0,0]
for t in range(1,time+1):
 f.getDrunk().move(f)
newLoc = f.getLoc()
distance = newLoc.getDist(start)
distance.append(distance)
return distance

drunk = Drunk(hello world)
for i in range(j):
 f = Field(drunk, Location(0,0))
 distance = performTrial(500,f)
 pylab.plot(distances)
 pylab.title('hello')
 pylab.xlabel(ok)
 pylab.ylabel(okok)
pylab.show



 
分享到:
评论

相关推荐

    OOPS - Python Datastore-开源

    **OOPS - Python Datastore 开源详解** OOPS(Object-Oriented Persistent Storage)是一个针对Python的开源数据存储库,它的主要目标是提供一个简单、高效且灵活的方式来处理数据库操作,将面向对象的设计与数据库...

    oops:oops basic

    "Oops" 是一个在软件开发领域,特别是Java编程中经常遇到的术语,它代表了“对象导向编程系统”(Object-Oriented Programming System)或在出现异常情况时的错误提示。"Oops Basic" 可能是指针对初学者的面向对象...

    linux kernel oops定位

    linux kernel oops定位,内核开发出现oops的分析处理

    内核Panic和Oops现象调试手段

    【内核Panic和Oops现象调试手段】 在Linux操作系统中,内核Panic和Oops是两种严重的错误状态,它们通常发生在内核遇到无法恢复的错误时。了解这些现象的调试手段对于系统的稳定性和故障排查至关重要。 **内核Oops*...

    OOPS 定位故障代码行

    OOPS 定位故障代码行 OOPS(Linux Kernel Oops)是一种 Linux 内核故障机制,当内核出现致命错误时,OOPS 会生成崩溃信息,帮助开发者和维护者快速定位和解决问题。 在 OOPS 信息中,会提供大量有价值的信息,如...

    Python-3.8.0a3.tgz

    2 (1, 2, 3) # oops, missing comma! 3 (4, 5, 6) 4] 子类之间的算术运算datetime.date或 datetime.datetime与datetime.timedelta对象现在返回子类的实例,而不是基类。这也会影响其实现(直接或间接)使用datetime....

    Oops 控件 for delphi6

    "Oops 控件 for Delphi6" 是一组专为 Delphi6 开发的组件库,它扩展了 Delphi IDE 的功能,提供了丰富的控件和工具,旨在帮助开发者更高效地创建用户界面并提升应用程序的性能。Oops 控件集包含了多个特定用途的组件...

    PyPI 官网下载 | oops_amqp-0.0.8b1-py2-none-any.whl

    总的来说,"oops_amqp-0.0.8b1-py2-none-any.whl"是适用于Python 2的Oops_AMQP库的一个预发布版本,它是一个二进制的Wheel包,可在所有平台上运行。在实际使用时,开发者可以通过pip工具轻松地将此包安装到他们的...

    Python-3.8.0b2.tgz

    2 (1, 2, 3) # oops, missing comma! 3 (4, 5, 6) 4] 子类之间的算术运算datetime.date或 datetime.datetime与datetime.timedelta对象现在返回子类的实例,而不是基类。这也会影响其实现(直接或间接)使用datetime....

    python-3.8.0a4.exe

    2 (1, 2, 3) # oops, missing comma! 3 (4, 5, 6) 4] 子类之间的算术运算datetime.date或 datetime.datetime与datetime.timedelta对象现在返回子类的实例,而不是基类。这也会影响其实现(直接或间接)使用datetime....

    PyPI 官网下载 | oops_wsgi-0.0.12.tar.gz

    本文将聚焦于一个名为“Oops_WSGI”的Python库,具体版本为0.0.12,该库以tar.gz格式发布在PyPI官网上。通过深入解析这个库,我们可以了解到其在Web服务领域中的应用和使用方法。 Oops_WSGI,顾名思义,可能是一个...

    50道必备的Python面试题(附答案)

    5. 支持面向对象编程(OOPS):类和对象是其核心概念。 6. 丰富的标准库和第三方模块:如 NumPy、Pandas、Django 等,覆盖各种应用场景。 7. 可扩展性:允许使用 C 或 C++ 编写部分性能敏感的代码。 8. 用户友好的...

    python-3.8.0b2-amd64.exe

    2 (1, 2, 3) # oops, missing comma! 3 (4, 5, 6) 4] 子类之间的算术运算datetime.date或 datetime.datetime与datetime.timedelta对象现在返回子类的实例,而不是基类。这也会影响其实现(直接或间接)使用datetime....

    Y硬件加速 解决游戏oops

    在标题“Y硬件加速 解决游戏oops”中,我们可以推断出这个问题是关于利用硬件加速技术来优化游戏性能,特别是针对出现“oops”错误的情况。"Oops"通常表示程序运行时遇到了未预期的问题,可能是由于内存不足、资源...

    PyPI 官网下载 | oops_datedir2amqp-0.0.2.tar.gz

    《PyPI官网下载:Oops_datedir2amqp-0.0.2.tar.gz——Python在云原生环境中的分布式实践》 PyPI(Python Package Index)是Python开发者的重要资源库,提供了大量的开源软件包和模块供全球用户下载使用。在本次讨论...

    Python 80 道面试题及答案.docx

    5. OOPS 支持 6. 大量的标准库和第三方模块 7. 可扩展性(我们可以用 C 或 C++ 编写 Python 代码) 8. 用户友好的数据结构 Python 的应用 1. Web 开发 2. 桌面 GUI 开发 3. 人工智能和机器学习 4. 软件开发 5. ...

Global site tag (gtag.js) - Google Analytics