我有一个Python脚本,需要计算以任意字体显示的任意字符串的确切大小,以生成简单的图表.我可以轻松地使用Tkinter.
import Tkinter as tk
import tkFont
root = tk.Tk()
canvas = tk.Canvas(root, width=300, height=200)
canvas.pack()
(x,y) = (5,5)
text = "yellow world"
fonts = []
for (family,size) in [("times",12),("times",24)]:
font = tkFont.Font(family=family, size=size)
(w,h) = (font.measure(text),font.metrics("linespace"))
print "%s %s: (%s,%s)" % (family,size,w,h)
canvas.create_rectangle(x,y,x+w,y+h)
canvas.create_text(x,y,text=text,font=font,anchor=tk.NW)
fonts.append(font) # save object from garbage collecting
y += h+5
tk.mainloop()
Run Code Online (Sandbox Code Playgroud)
结果似乎取决于Python和/或系统的版本:
在Ned Batchelder提到它之后,我发现字体的大小因平台而异.只要你坚持与自己保持一致的Tkinter,它可能不是一个交易破坏者.但我的整个程序并没有使用Tkinter的来执行实际的绘图:它只是依靠其字体大小计算,以产生一个输出(在SVG或Python脚本被发送到Nodebox).事情就是这样:
mocodo的输出http://grab.by/grabs/f67b951d092dd1f4f490e1469a53bca2.png
(请查看实际大小的 …
Python循环语句可能有一个else子句,当且仅当循环未被a终止时才执行该子句break.换句话说,当条件变为False(有while)或迭代器耗尽时(带for).
这个循环 - 其他构造是否源自另一种语言(理论上的或实际的)?它是否被任何较新的语言所采用?
也许我应该问问Guido的前任,但他肯定太忙了,无法进行如此徒劳的调查.;-)
相关讨论和示例: 在for循环中使用'else'的Pythonic方法
法国SécuritéSociale识别号码以两位数的校验码结束.我已经验证了可以检测到的每个可能的常见转录错误,并且发现了一些可能未被检测到的其他类型的错误(例如,滚动三个连续的数字).
def check_code(number):
return 97 - int(number) % 97
def single_digit_generator(number):
for i in range(len(number)):
for wrong_digit in "0123456789":
yield number[:i] + wrong_digit + number[i+1:]
def roll_generator(number):
for i in range(len(number) - 2):
yield number[:i] + number[i+2] + number[i] + number[i+1] + number[i+3:]
yield number[:i] + number[i+1] + number[i+2] + number[i] + number[i+3:]
def find_error(generator, number):
control = check_code(number)
for wrong_number in generator(number):
if number != wrong_number and check_code(wrong_number) == control:
return (number, wrong_number) …Run Code Online (Sandbox Code Playgroud) 我如何转换Python的旧式格式字符串,如下所示:
print("You: %s points. Me: %s points." % (score, total - score))
Run Code Online (Sandbox Code Playgroud)
进入以下?
print(f"You: {score} points. Me: {total - score} points.")
Run Code Online (Sandbox Code Playgroud)
实际上,对于两个例子%s,我已经写了这个正则表达式:
"(.*)%s(.*)%s(.*)" % \(([^,\)]+), ([^,\)]+)\)f"$1{$4}$2{$5}$3"一个人可以很容易地编写其他几个正则表达式来处理1,3,4,... %s的情况,但是我正在寻找一种更通用,更容易出错的方法。
注意:AFAIK,2013年在这里提出了类似的问题(从旧样式自动转换高级字符串格式器),当时f字符串不是问题(它们是在Python 3.6中引入的)。
出于教学目的,我想计算一个给定行在给定函数中执行多少次而不修改或装饰它.例如,对于功能:
def binary_search(seq, x):
(a, b) = (0, len(seq) - 1)
while a <= b:
m = (a + b) / 2
if x < seq[m]:
b = m - 1
elif x > seq[m]:
a = m + 1
else:
return m
Run Code Online (Sandbox Code Playgroud)
我会写这样的东西:
print count_exec(binary_search, range(100), 44, line_number = 4)
Run Code Online (Sandbox Code Playgroud)
......甚至是这样的:
print count_exec(binary_search(range(100), 44), line = "m = (a + b) / 2")
Run Code Online (Sandbox Code Playgroud)
...两者都应该打印执行第4行的次数(即7).最终目标是为任何功能的复杂性提供经验方法:
我目前的解决方案是添加一个函数属性:
def binary_search(seq, x):
binary_search.count = 0 # <------------------ added
(a, …Run Code Online (Sandbox Code Playgroud) python profiling metaprogramming decorator abstract-syntax-tree
我正在编写一个兼容Python 2.7和3.5的程序.它的某些部分依赖于随机过程.我的单元测试使用任意种子,这导致执行和语言相同的结果......除了使用的代码random.shuffle.
Python 2.7中的示例:
In[]: import random
random.seed(42)
print(random.random())
l = list(range(20))
random.shuffle(l)
print(l)
Out[]: 0.639426798458
[6, 8, 9, 15, 7, 3, 17, 14, 11, 16, 2, 19, 18, 1, 13, 10, 12, 4, 5, 0]
Run Code Online (Sandbox Code Playgroud)
Python 3.5中的相同输入:
In []: import random
random.seed(42)
print(random.random())
l = list(range(20))
random.shuffle(l)
print(l)
Out[]: 0.6394267984578837
[3, 5, 2, 15, 9, 12, 16, 19, 6, 13, 18, 14, 10, 1, 11, 4, 17, 7, 8, 0]
Run Code Online (Sandbox Code Playgroud)
注意,伪随机数是相同的,但是混洗列表是不同的.正如预期的那样,重新执行单元格不会改变它们各自的输出.
我怎么能为两个版本的Python编写相同的测试代码?
代替:
from .model import Foo, Bar
Run Code Online (Sandbox Code Playgroud)
我想:
import .model
Run Code Online (Sandbox Code Playgroud)
这会引发语法错误。有办法做到吗?
令我感到困惑的是,combSciPy的功能似乎比天真的Python实现慢.这是解决欧拉项目问题53的两个等效程序的测量时间.
%%timeit
from scipy.misc import comb
result = 0
for n in range(1, 101):
for k in range(1, n + 1):
if comb(n, k) > 1000000:
result += 1
result
Run Code Online (Sandbox Code Playgroud)
输出:
1 loops, best of 3: 483 ms per loop
Run Code Online (Sandbox Code Playgroud)
%%timeit
from math import factorial
def comb(n, k):
return factorial(n) / factorial(k) / factorial(n - k)
result = 0
for n in range(1, 101):
for k in range(1, n + 1):
if comb(n, …Run Code Online (Sandbox Code Playgroud) 这个问题已经在OR交换中进行了彻底的讨论和更新,我在其中交叉了它.
当我从命令行运行CPLEX 12.5.0.0时:
cplex -f my_instance.lp
Run Code Online (Sandbox Code Playgroud)
最佳整数解在19056.99滴答中找到.
但是通过Python API,在同一个实例上:
import cplex
problem = cplex.Cplex("my_instance.lp")
problem.solve()
Run Code Online (Sandbox Code Playgroud)
现在所需的时间为97407.10蜱(慢5倍以上).
在这两种情况下,模式都是并行的,确定性的,最多2个线程.想知道这个糟糕的性能是由于一些Python线程开销,我试过:
problem = cplex.Cplex("my_instance.lp")
problem.parameters.threads.set(1)
problem.solve()
Run Code Online (Sandbox Code Playgroud)
需要46513.04个刻度(即,使用一个核心比使用两个核心快两倍!).
作为CPLEX和LP的新手,我发现这些结果非常令人困惑.有没有办法提高Python API性能,还是应该切换到更成熟的API(即Java或C++)?
以下是2线程分辨率的完整细节,首先是(常见)前言:
Tried aggregator 3 times.
MIP Presolve eliminated 2648 rows and 612 columns.
MIP Presolve modified 62 coefficients.
Aggregator did 13 substitutions.
Reduced MIP has 4229 rows, 1078 columns, and 13150 nonzeros.
Reduced MIP has 1071 binaries, 0 generals, 0 SOSs, and 0 indicators.
Presolve time = 0.06 sec. (18.79 …Run Code Online (Sandbox Code Playgroud) line-magic命令%load将给定文件的内容加载到当前单元格中,例如,执行:
[cell 1] %load hello_world.py
Run Code Online (Sandbox Code Playgroud)
...将单元格转换为:
[cell 1] # %load hello_world.py
print("hello, world")
Run Code Online (Sandbox Code Playgroud)
我想创建一个%load_nextline-magic 命令,它将将此文件加载到下一个单元格中。例如,在以下笔记本中执行单元 1:
[cell 1] %load_next hello_world.py
[cell 2] print("hello, cruel world") # original content
Run Code Online (Sandbox Code Playgroud)
...将保持单元格 1 不变并使用新内容更新单元格 2:
[cell 1] %load_next hello_world.py
[cell 2] print("hello, world")
Run Code Online (Sandbox Code Playgroud)
我已经尝试过这个:
[cell 1] %load hello_world.py
Run Code Online (Sandbox Code Playgroud)
但它会在当前单元格和下一个单元格之间插入内容:
[cell 1] %load_next hello_world.py
[cell 2] print("hello, world")
[cell 3] print("hello, cruel world") # original content
Run Code Online (Sandbox Code Playgroud)
是否可以使其替换下一个单元格,或在插入下一个单元格之前删除下一个单元格?
python ×8
python-3.x ×3
benchmarking ×1
combinations ×1
converter ×1
cplex ×1
decorator ×1
fonts ×1
generator ×1
history ×1
if-statement ×1
ipython ×1
loops ×1
ocaml ×1
performance ×1
profiling ×1
python-2.7 ×1
random-seed ×1
scipy ×1
shuffle ×1
size ×1
syntax ×1
tkinter ×1