簡體   English   中英

編寫更短,可讀,更pythonic的代碼

[英]Writing shorter, readable, pythonic code

我正在嘗試制作更短,更pythonic,可讀的python。 我為Project Euler的問題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))
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))))

這是我的解決方案。 我試着編寫我知道如何編寫的最“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

至於解釋最后一點是什么,首先要創建一個名為numstring的空string

numstring = ''

然后循環遍歷txt文件8.txt中的每一行文本(或string s行):

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

因此,對於您找到的每一行,您都希望將line.rstrip()的結果添加到其中。 rstrip '剝離'字符串中的空格(換行符,空格等):

    numstring += line.rstrip()

假設你有一個包含文本的文件, 8.txtLineOne \\nLyneDeux\\t\\nLionTree你得到的結果看起來像這樣:

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

這是一個完整的解決方案! 首先讀出這個數字:

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,則需要使用functools.reduce替換reduce

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM