编写更短,可读,更pythonic的代码

时间:2012-07-27 17:55:55

标签: python

我正在尝试制作更短,更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()

有什么建议吗?谢谢你们!

5 个答案:

答案 0 :(得分:4)

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

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))

答案 1 :(得分:4)

from operator import mul

def product(nums):
    return reduce(mul, nums)

nums = [int(c) for c in open('8.txt').read() if c.isdigit()]
result = max((product(nums[i:i+5]) for i in range(len(nums))))

答案 2 :(得分:1)

这是我的解决方案。我试着编写我知道如何编写的最“Pythonic”代码。

with open('8.txt') as f:
    numstring = f.read().replace('\n', '')

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

def sub_lists(lst, length):
    for i in range(len(lst) - (length - 1)):
        yield lst[i:i+length]

def prod(lst):
    p = 1
    for x in lst:
        p *= x
    return p

best = max(prod(lst) for lst in sub_lists(nums, 5))
print(best)

可以说,这是使用reduce的理想情况之一,因此prod()可能应该是:

# from functools import reduce   # uncomment this line for Python 3.x
from operator import mul
def prod(lst):
    return reduce(mul, lst, 1)

我不想尝试在有多条线路的情况下编写单行代码。我非常喜欢with语句,我习惯将它用于所有I / O.对于这个小问题,你可以只做一行,如果你使用PyPy或其他什么文件将在你的小程序完成执行并退出时关闭。但我喜欢使用with的双线,所以我写了。

我喜欢@Steven Rumbalski的单线:

nums = [int(c) for c in open('8.txt').read() if c.isdigit()]

以下是我可能会写的:

with open("8.txt") as f:
    nums = [int(ch) for ch in f.read() if ch.isdigit()]

同样,对于这种短程序,当程序退出时,您的文件将被关闭,因此您不必担心确保文件被关闭;但我喜欢养成使用with的习惯。

答案 3 :(得分:0)

至于解释最后一点是什么,首先要创建一个名为string的空numstring

numstring = ''

然后,您遍历string文件txt中的每一行文字(或8.txt s行):

for line in open('8.txt'):

因此,对于您找到的每一行,您都希望将line.rstrip()的结果添加到其中。 rstrip从字符串中删除空格(换行符,空格等):

    numstring += line.rstrip()

假设您有一个文件8.txt,其中包含文字:LineOne \nLyneDeux\t\nLionTree您最终会看到类似这样的结果:

>>>'LineOne' #loop first time
>>>'LineOneLyneDeux' # second time around the bush
>>>'LineOneLyneDeuxLionTree' #final answer, reggie

答案 4 :(得分:0)

这是一个完整的解决方案!首先读出数字:

with open("8.txt") as infile:
    number = infile.replace("\n", "")

然后创建一个包含5个连续数字的列表列表:

cons_numbers = [list(map(int, number[i:i+5])) for i in range(len(number) - 4)]

然后找到最大的并打印出来:

print(max(reduce(operator.mul, nums) for nums in cons_numbers))

如果您使用的是Python 3.x,则需要将reduce替换为functools.reduce