我想编写一个行为与给定函数完全相似的函数,只不过它会打印执行该函数所消耗的时间。像这样:
>>> fib = profile(fib)
>>> fib(20)
time taken: 0.1 sec
10946
Run Code Online (Sandbox Code Playgroud)
这是我的代码,它将在每个函数调用中打印消息。
import time
def profile(f):
def g(x):
start_time = time.clock()
value = f(x)
end_time = time.clock()
print('time taken: {time}'.format(time=end_time-start_time))
return value
return g
@profile
def fib(n):
if n is 0 or n is 1:
return 1
else:
return fib(n-1) + fib(n-2)
Run Code Online (Sandbox Code Playgroud)
我上面的代码将为每个fib(n-1)打印一条消息``耗时:...'',因此会有很多消息``耗时:...''。我可以找到一种方法来仅打印fib(20)的执行时间,而不是每个fib(n-1)的执行时间吗?
我写了一个函数来计算两点之间的航向,只有当车辆报告它正在移动并且车辆在两点之间移动了20厘米时.
该函数使用静态变量 - 或者至少它会起作用 - 来跟踪先前的位置和标题值.
这是代码:
def withCan(pos):
eastdist = pos[0]-previous_pos[0]
northdist = pos[1]-previous_pos[1]
canflag = pos[2]
if (canflag == 1 or canflag==2):
if (previous_canflag == 1 and canflag == 2):
previous_heading += 180.0
previous_canflag = canflag
elif (previous_canflag == 2 and canflag == 1):
previous_heading += 180.0
previous_canflag = canflag
else:
previous_canflag = canflag
if ( (canflag == 1 or canflag == 2) and math.sqrt(northdist*northdist+eastdist*eastdist) > canstep ):
previous_heading = math.degrees(math.atan2(eastdist, northdist))
previous_pos[0] = pos[0]
previous_pos[1] = pos[1] …Run Code Online (Sandbox Code Playgroud) 我的下一步是,如果输入不在斐波那契数列中,则程序必须给出一个输出,该数字的序列中的数字最接近输入。我不知道如何进行,有人可以帮助我吗?
def fibs():
a,b = 0,1
yield a
yield b
while True:
a,b = b,a+b
yield b
n = int(input("please, enter a number: "))
for fib in fibs():
if n == fib:
print("Yes! Your number is a Fibonacci number!")
break
if fib > n:
print("No! Your number is not a Fibonacci number!")
break
Run Code Online (Sandbox Code Playgroud) 我正在使用for loopPyQt中的多个信号/插槽。代码如下:
# Connect Scan Callbacks
for button in ['phase', 'etalon', 'mirror', 'gain']:
getattr(self.ui, '{}_scan_button' .format(button)).clicked.connect(
lambda: self.scan_callback(button))
Run Code Online (Sandbox Code Playgroud)
我的期望:
phase_scan_button单击“ 连接”按钮signal到,scan_callback slot然后将字符串phase作为参数发送到slot。同样的etalon,mirror和gain。我得到的是:
gain作为所有按钮的参数传递。不知道我是不是很愚蠢(可能是)或它是一个错误。作为参考,该slot方法:
def scan_callback(self, scan):
print(scan) # Here I always get 'gain'
if self.scanner.isWorking:
self.scanner.isWorking = False
self.scan_thread.terminate()
self.scan_thread.wait()
else:
self.scanner.isWorking = True
self.scan_thread.start()
getattr(self.ui, '{}_scan_button' .format(
scan)).setText('Stop Scan')
getattr(self, '_signal{}Scan' .format(scan)).emit()
Run Code Online (Sandbox Code Playgroud) def download():
upgrade = True
if upgrade:
# do a download using tftp
else:
# do a download via HTTP
Run Code Online (Sandbox Code Playgroud)
如您所见,我有一个设置为true的硬编码升级值.在此脚本中,它始终执行tftp下载.
如何在第一次迭代时更改脚本以执行tftp下载,在下一次迭代中调用函数下载时,它会进行http下载?
我正在尝试使用 python 类型注释创建树结构。代码是这样的:
from typing import List
class TNode:
def __init__(self, parent: 'TNode', data: str, children: List['TNode'] = []):
self.parent = parent
self.data = data
self.children = children
root = TNode(None, 'example')
Run Code Online (Sandbox Code Playgroud)
但是代码存在类型不匹配的问题,Pycharm 会引发Expected type 'TNode', got 'None' instead. 有没有办法解决这个问题,或者是否有更好的方法来设计类构造函数?
我注意到 python 中有一个奇怪的行为,有人能给我这种行为的原因吗?
如果我调用没有属性的函数,则默认值将保留其状态。您可以查看以下示例以更好地理解
class EvenStream(object):
def __init__(self):
self.current = 0
def get_next(self):
to_return = self.current
self.current += 2
return to_return
class OddStream(object):
def __init__(self):
self.current = 1
def get_next(self):
to_return = self.current
self.current += 2
return to_return
def print_from_stream(n, stream=EvenStream()):
for _ in range(n):
print(stream.get_next())
print_from_stream(2)
print('*****')
print_from_stream(2)
print('*****')
print_from_stream(2, OddStream())
print('*****')
print_from_stream(2, OddStream())
Run Code Online (Sandbox Code Playgroud)
输出:我期待 0,2,0,2 但它给了我 0,2,4,6
0
2
*****
4
6
*****
1
3
*****
1
3
Run Code Online (Sandbox Code Playgroud) 好的,所以这让我整天疯狂.
为什么会这样:
class Foo:
def __init__(self, bla = {}):
self.task_defs = bla
def __str__(self):
return ''.join(str(self.task_defs))
a = Foo()
b = Foo()
a.task_defs['BAR'] = 1
print 'B is ==> %s' % str(b)
print 'A is ==> %s' % str(a)
Run Code Online (Sandbox Code Playgroud)
给我输出:
B is ==> {'BAR': 1}
A is ==> {'BAR': 1}
Run Code Online (Sandbox Code Playgroud)
我知道它与python通过引用传递所有内容有关.
但为什么会这样呢?这实际上让我一整天都疯了,基本上让我把我的东西拆开了.难道python不应该足够聪明来处理这样的事情吗?
我有点像python的菜鸟,但我正在尝试创建一个递归函数,就像内置范围函数一样:
def Range (lo, hi):
if lo >= hi:
return []
else:
return [lo, Range (lo+1,hi)]
Run Code Online (Sandbox Code Playgroud)
但它返回多个列表.
而不是[3,4,5,6],这就是我想要的,它的归还[3,[4,[5,[6,[]]]]]
为什么是这个以及如何解决它?
我有一个模块,其中定义了一些常量,并在多个函数中使用。我如何从我的主文件中覆盖它们的值?
说这是模块,test_import.py
MY_CONST = 1
def my_func(var = MY_CONST):
print(var)
Run Code Online (Sandbox Code Playgroud)
这是我的main.py文件:
import test_import
MY_CONST = 2
test_import.MY_CONST = 3
test_import.my_func()
Run Code Online (Sandbox Code Playgroud)
这段代码仍然打印“1”。我希望它打印一些其他值(显然,在调用时不传递值my_func())