小编mkr*_*er1的帖子

与Project Euler的速度比较:C vs Python vs Erlang vs Haskell

我已经采取了问题#12项目欧拉作为编程练习和我的(肯定不是最优的)实现在C,Python和Erlang和Haskell的比较.为了获得更高的执行时间,我搜索第一个三角形数字,其中有超过1000个除数而不是原始问题中所述的500.

结果如下:

C:

lorenzo@enzo:~/erlang$ gcc -lm -o euler12.bin euler12.c
lorenzo@enzo:~/erlang$ time ./euler12.bin
842161320

real    0m11.074s
user    0m11.070s
sys 0m0.000s
Run Code Online (Sandbox Code Playgroud)

蟒蛇:

lorenzo@enzo:~/erlang$ time ./euler12.py 
842161320

real    1m16.632s
user    1m16.370s
sys 0m0.250s
Run Code Online (Sandbox Code Playgroud)

Python与PyPy:

lorenzo@enzo:~/Downloads/pypy-c-jit-43780-b590cf6de419-linux64/bin$ time ./pypy /home/lorenzo/erlang/euler12.py 
842161320

real    0m13.082s
user    0m13.050s
sys 0m0.020s
Run Code Online (Sandbox Code Playgroud)

二郎:

lorenzo@enzo:~/erlang$ erlc euler12.erl 
lorenzo@enzo:~/erlang$ time erl -s euler12 solve
Erlang R13B03 (erts-5.7.4) [source] [64-bit] [smp:4:4] [rq:4] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.7.4  (abort with ^G)
1> 842161320

real    0m48.259s
user    0m48.070s
sys 0m0.020s
Run Code Online (Sandbox Code Playgroud)

哈斯克尔: …

c python erlang performance haskell

645
推荐指数
14
解决办法
13万
查看次数

将图表保存为PDF

绘图模块

def plotGraph(X,Y):
    fignum = random.randint(0,sys.maxint)
    plt.figure(fignum)
    ### Plotting arrangements ###
    return fignum
Run Code Online (Sandbox Code Playgroud)

主要模块

import matplotlib.pyplot as plt
### tempDLStats, tempDLlabels are the argument
plot1 = plotGraph(tempDLstats, tempDLlabels)
plot2 = plotGraph(tempDLstats_1, tempDLlabels_1)
plot3 = plotGraph(tempDLstats_2, tempDLlabels_2)
plt.show()
Run Code Online (Sandbox Code Playgroud)

我想将所有图形plot1,plot2,plot3保存到单个PDF文件中.有没有办法实现它?我不能plotGraph在主模块中包含该功能.

有一个名为的功能,pylab.savefig但只有当它与绘图模块一起放置时才会起作用.有没有其他方法可以实现它?

python matplotlib

72
推荐指数
4
解决办法
18万
查看次数

同时逐行读取两个文本文件

我有两种不同语言的文本文件,它们是逐行对齐的.即textfile1中的第一行对应于textfile2中的第一行,依此类推.

有没有办法同时逐行读取这两个文件?

下面是文件应该如何显示的示例,假设每个文件的行数大约为1,000,000.

textfile1:

This is a the first line in English
This is a the 2nd line in English
This is a the third line in English
Run Code Online (Sandbox Code Playgroud)

textfile2:

C'est la première ligne en Français
C'est la deuxième ligne en Français
C'est la troisième ligne en Français
Run Code Online (Sandbox Code Playgroud)

期望的输出

This is a the first line in English\tC'est la première ligne en Français
This is a the 2nd line in English\tC'est la deuxième ligne en Français
This is a the third line …
Run Code Online (Sandbox Code Playgroud)

python io file readfile

51
推荐指数
3
解决办法
4万
查看次数

具有可选属性的 python 数据类

如何制作数据类的可选属性?

from dataclasses import dataclass

@dataclass
class CampingEquipment:
    knife: bool
    fork: bool
    missing_flask_size: # what to write here?
    
kennys_stuff = {
    'knife': True,
    'fork': True
}

print(CampingEquipment(**kennys_stuff))
Run Code Online (Sandbox Code Playgroud)

我尝试过field(init=False),但它给了我:

TypeError: CampingEquipment.__init__() missing 1 required positional argument: 'missing_flask_size'
Run Code Online (Sandbox Code Playgroud)

我所说的“可选”是指__dict__可能包含或不包含“missing_flask_size”键。如果我设置默认值,那么密钥将在那里,但在某些情况下不应该在那里。我想检查它的类型是否存在。

我尝试将 移动field(init=False)到类型位置(冒号之后),这样我就可以更明确地说明我想要的可选内容是键而不是值。

所以我希望这个测试能够通过:

with pytest.raises(AttributeError):
    ce = CampingEquipment(**kennys_stuff)
    print(ce.missing_flask_size)
Run Code Online (Sandbox Code Playgroud)

python python-dataclasses

43
推荐指数
2
解决办法
6万
查看次数

迭代数据类键和值的更好方法是什么?

我有两个数据类,Route并且Factors. Route包含一个值和三个副本Factors

Route不知道Factors包含多少个变量。我想获取这些变量的名称,然后获取Factors.

这是我目前拥有的:

@dataclass
class Factors:
    do: bool  # does it do the route
    hub: int # how many of the locations are hubs

    def __init__(self, do_init):
        self.do = do_init
        self.hub = 0 # will add later 

    def __str__(self):
        return "%s" % self.do


@dataclass
class Route:
    route: tuple
    skyteam: Factors
    star: Factors
    oneworld: Factors

    def __init__(self, route):
        self.route = route.get('route')
        # this could probably be done with …
Run Code Online (Sandbox Code Playgroud)

python python-dataclasses

40
推荐指数
4
解决办法
5万
查看次数

从 VS Code 调用时,Mypy 不尊重 mypy.ini 中的设置以排除文件夹检查

我想从 mypy 检查中排除一个文件夹。查看文档我在 mypy.ini 配置文件中尝试了以下配置

[mypy]  
python_version = 3.8  
exclude '/venv/'
Run Code Online (Sandbox Code Playgroud)

没有运气。

我想从 mypy 检查中排除我的虚拟环境。我只有一个来检查我写的代码。

这是 mypy 的错误吗?

我正在使用 mypy 0.901 和 mypy-extensions 0.4.3。我还使用 mypy vs-code 扩展 0.2.0。

python virtualenv visual-studio-code vscode-extensions mypy

40
推荐指数
6
解决办法
5万
查看次数

“零成本抽象”是什么意思?

我在探索 Rust 时遇到了这个术语。

我看到了对此的不同解释,但仍然不太明白。

The Embedded Rust Book中,它说

类型状态也是零成本抽象的一个很好的例子

  • 将某些行为移动到编译时执行或分析的能力。

这些类型状态不包含实际数据,而是用作标记。

由于它们不包含数据,因此它们在运行时在内存中没有实际表示:

这是否意味着运行时更快,因为运行时没有内存?

如果有人能以易于理解的方式解释它,我将不胜感激。

rust

36
推荐指数
3
解决办法
2万
查看次数

如何在 macOS 12.3+ 上安装 Python 2

macOS 12.3 更新删除了 Python 2,并将其替换为版本 3:

https://developer.apple.com/documentation/macos-release-notes/macos-12_3-release-notes

Python 弃用 在此更新中,Python 2.7 已从 macOS 中删除。开发人员应该使用 Python 3 或替代语言。(39795874)

我知道我们需要迁移到版本 3,但与此同时我们仍然需要版本 2。Homebrew 似乎不再有它了:

brew install python@2.7
Warning: No available formula with the name "python@2.7". Did you mean python@3.7, python@3.9, python@3.8, python@3.10 or python-yq?

brew install python2
Warning: No available formula with the name "python2". Did you mean ipython, bpython, jython or cython?
Run Code Online (Sandbox Code Playgroud)

是什么赋予了?

python macos homebrew python-2.7 macos-monterey

35
推荐指数
3
解决办法
6万
查看次数

Client.__init__() “缺少 1 个必需的仅关键字参数:'意图'”,或“采用 1 个位置参数,但已给出 2 个”

我试图制作一个快速的不和谐机器人,我使用了以下代码:

\n
import discord\nfrom discord.ui import button, view\nfrom discord.ext import commands\n\nclient = discord.Client()\n\n@client.event\nasync def on_ready():\n    print(\'Autenticazione riuscita. {0.user} \xc3\xa8 online!\'.format(client))\n
Run Code Online (Sandbox Code Playgroud)\n

但弹出这个错误:

\n
import discord\nfrom discord.ui import button, view\nfrom discord.ext import commands\n\nclient = discord.Client()\n\n@client.event\nasync def on_ready():\n    print(\'Autenticazione riuscita. {0.user} \xc3\xa8 online!\'.format(client))\n
Run Code Online (Sandbox Code Playgroud)\n

我尝试通过在括号之间添加一些内容来提供一个论点,如下所示:

\n
import discord\nfrom discord.ui import button, view\nfrom discord.ext import commands\n\nclient = discord.Client(0)\n\n@client.event\nasync def on_ready():\n    print(\'Autenticazione riuscita. {0.user} \xc3\xa8 online!\'.format(client))\n
Run Code Online (Sandbox Code Playgroud)\n

但我得到了这个错误:

\n
Client.__init__() missing 1 required keyword-only argument: \'intents\'\n
Run Code Online (Sandbox Code Playgroud)\n

在另一台 PC 上,完全相同的代码、完全相同的模块和相同的 Python 版本运行得很好。我缺少什么?

\n

python discord.py

30
推荐指数
2
解决办法
12万
查看次数

Python 3.10 模式匹配 (PEP 634) - 字符串中的通配符

我有一个很大的 JSON 对象列表,我想根据其中一个键的开头来解析这些对象,并使用通配符来处理其余的。很多键都是相似的,例如"matchme-foo""matchme-bar"。有一个内置通配符,但它仅用于整个值,有点像else.

我可能忽略了一些东西,但我在提案中找不到解决方案:

https://docs.python.org/3/whatsnew/3.10.html#pep-634-structural-pattern-matching

PEP-636 中还有更多相关信息:

https://www.python.org/dev/peps/pep-0636/#going-to-the-cloud-mappings

我的数据如下所示:

data = [{
          "id"     : "matchme-foo",
          "message": "hallo this is a message",
      },{
          "id"     : "matchme-bar",
          "message": "goodbye",
      },{
          "id"     : "anotherid",
          "message": "completely diffrent event"
      }, ...]
Run Code Online (Sandbox Code Playgroud)

我想做一些可以匹配 id 的事情,而不必制作一长串|'s。

像这样的东西:

for event in data:
    match event:
        case {'id':'matchme-*'}: # Match all 'matchme-' no matter what comes next
            log.INFO(event['message'])
        case {'id':'anotherid'}:
            log.ERROR(event['message'])
Run Code Online (Sandbox Code Playgroud)

它是 Python 的一个相对较新的补充,因此目前还没有太多关于如何使用它的指南。

python json pattern-matching python-3.x python-3.10

28
推荐指数
1
解决办法
4677
查看次数