我在Python中有两个递归函数,只是想知道它们的Big O表示法.每个人的大O是什么?
def cost(n):
if n == 0:
return 1
else:
return cost(n-1) + cost(n-1)
def cost(n):
if n == 0:
return 1
else:
return 2*cost(n-1)
Run Code Online (Sandbox Code Playgroud) 我在StackOverflow上看到过这种情况的其他例子,但是我不理解任何答案(我还是一个新程序员),我看到的其他例子看起来也不像我的,否则我不会发布这个题.
我在Windows 7上运行Python 3.2.
我之前从来没有遇到这种情况,而且我已经多次这样做过课,所以这次我真的不知道有什么不同.唯一的区别是我没有制作所有的Class文件; 我得到了一个填写的模板和一个测试文件来试试.它适用于测试文件,但不能处理我的文件.我一直在以与测试文件完全相同的方式调用类中的方法(例如Lineup.size())
这是我的班级:
class Queue:
# Constructor, which creates a new empty queue:
def __init__(self):
self.__items = []
# Adds a new item to the back of the queue, and returns nothing:
def queue(self, item):
self.__items.insert(0,item)
return
# Removes and returns the front-most item in the queue.
# Returns nothing if the queue is empty.
def dequeue(self):
if len(self.__items) == 0:
return None
else:
return self.__items.pop()
# Returns the front-most item in the queue, and DOES … 我在WingIDE 101(版本4)的Windows 7操作系统上运行Python 3.2.在这种情况下环境并不重要,但我认为我应该具体.
我的代码如下.它不是最佳的,只是找到素数的一种方法:
def isPrime2(n):
if n == 1:
return False
count = 0
for i in range(2,n+1,2):
if n%i == 0:
count = count + 1
if count > 2:
return False
for i in range(1,n+1,2):
if n%i == 0:
count = count + 1
if count > 2:
return False
if count == 2:
return True
start = time.time()
x = isPrime2(571)
end = time.time()
time_interval = end - start
print("%1.15f"%time_interval)
print(x)
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是time.time()函数似乎不是时间.当我运行这个程序时,我得到了
0.000000000000000
True
Run Code Online (Sandbox Code Playgroud)
我也尝试了这个最多30位数,所有这些都保持为零. …