【问题标题】:Conpressing repeated loops压缩重复循环
【发布时间】:2021-07-31 02:46:46
【问题描述】:

我为 HackerRank problem 编写了以下代码,其中涉及语法非常相似的重复 FOR 循环:

x, y = map(int, input().split())

inp = []
for _ in range(x):
    inp.append(list(map(int, input().split()))) 
#I get the rest of the input as a nested list.

while len(inp) < 7:
    inp.append([1, 0])
#Adding dummy values in the list

list = []   
for a in inp[0][1:inp[0][0]+1]:
    for b in inp[1][1:inp[1][0]+1]:
        for c in inp[2][1:inp[2][0] + 1]:
            for d in inp[3][1:inp[3][0] + 1]:
                for e in inp[4][1:inp[4][0] + 1]:
                    for f in inp[5][1:inp[5][0] + 1]:
                        for g in inp[6][1:inp[6][0] + 1]:
                            list.append((a ** 2 + b ** 2 + c ** 2 + d ** 2 + e ** 2 + f ** 2 + g ** 2) % y) 
                            #Given function

print(max(list))

我想知道有没有办法一次性做到这一点。

PS:我绝对是编程初学者。

【问题讨论】:

  • 请注意,此问题在站点的itertools 部分。也许可能有一个 itertool 方法可以帮助您找到集合的交叉product()...

标签: python-3.x loops for-loop nested-loops


【解决方案1】:

使用 itertools.product 可以稍微简化循环:

import itertools as it

K, M = map(int, input().strip().split())

# reading the K lines and appending lists to 'L'
L = []

for i in range(K):
    lst = list(map(int, input().strip().split()))
    L.append(lst[1:])
   

# Looping through Cartesian product 

MAX = -1

for i in it.product(*L):
    MAX = max(sum(map(lambda x: x**2, i))% M, MAX)
    
print(MAX)

【讨论】:

  • 您认为哪个更好:从头开始编写程序还是使用自定义库?哪个执行速度更快?
  • 这是个好问题。这取决于。如果您处于学习阶段,您可以/应该尝试“发明轮子”来学习内部工作,但在现实世界的产品开发中,时间和性能至关重要,因此您应该采取务实的态度。
猜你喜欢
  • 2018-04-11
  • 2017-03-01
  • 2022-01-12
  • 1970-01-01
  • 2014-01-04
  • 1970-01-01
  • 2019-06-26
  • 2020-11-22
  • 1970-01-01
相关资源
最近更新 更多