gpt4 book ai didi

python - 编写更短、可读的 pythonic 代码

转载 作者:太空狗 更新时间:2023-10-30 00:46:07 26 4
gpt4 key购买 nike

我正在尝试生成更短、更 pythonic 和可读的 python。我有这个适用于 Project Euler's problem 8 的解决方案(找出 1000 位数字中 5 个连续数字的最大乘积)。

关于编写此脚本的更 pythonic 版本的建议?

numstring = ''
for line in open('8.txt'):
numstring += line.rstrip()

nums = [int(x) for x in numstring]

best=0
for i in range(len(nums)-4):
subset = nums[i:i+5]
product=1
for x in subset:
product *= x
if product>best:
best=product
bestsubset=subset

print best
print bestsubset

例如:下面的代码段必须是一行代码。我确定这里有一个过去的主题,但我不确定如何在下面描述我正在做的事情。

numstring = ''
for line in open('8.txt'):
numstring += line.rstrip()

有什么建议吗?谢谢大家!

最佳答案

我正在研究一个完整的答案,但现在这是一个类轮

numstring = ''.join(x.rstrip() for x in open('8.txt'))

编辑:给你!一个用于搜索的类轮。列表理解很棒。

from operator import mul
def prod(list):
return reduce(mul, list)

numstring = ''.join(x.rstrip() for x in open('8.txt'))
nums = [int(x) for x in numstring]
print max(prod(nums[i:i+5]) for i in range(len(nums)-4))

关于python - 编写更短、可读的 pythonic 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11693115/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com