【问题标题】:What does this line of the code do?这行代码有什么作用?
【发布时间】:2018-03-06 01:22:53
【问题描述】:

我是 python 的新手。我正在解决 Hackerrank https://www.hackerrank.com/challenges/maximize-it/problem 上的一个问题。

我无法解决问题,所以我开始讨论。我在那里找到了一个代码 -

from itertools import product

K,M = map(int,input().split())
N = (list(map(int, input().split()))[1:] for _ in range(K))
results = map(lambda x: sum(i**2 for i in x)%M, product(*N))
print(max(results))

我有两个疑问:

  1. 首先,如果我尝试打印N,它会抛出“生成器对象不可下标”错误,但该值已经转换为列表,所以我无法理解错误原因。
  2. 我无法理解results=map(lambda x: sum(i**2 for i in x)%M, product(*N)) 会存储什么。

我了解product(*N) 的作用。但是sum(i**2 for i in x)%M 的输出是什么?它是添加列表值的平方然后执行取模运算吗?还是别的什么?

【问题讨论】:

  • "但该值已转换为列表" 不,不是。 N 是一个生成器。
  • 我可以从错误中理解这一点。但为什么会这样呢?
  • 使用() 括号代替[] 括号。 [] 表示list 存储在内存中。 () 表示动态生成每个值的生成器。

标签: python python-3.x list


【解决方案1】:

对于您的第一个疑问:

为什么 N 是生成器?

list 函数被应用于map(int, input().split()) 语句,确实是一个返回的列表,但是,最外面的一对括号和for _ in range(K) 表示生成器对象正在返回到N 和不是列表。如果你想在调试的时候看到N的内容,把最外面的括号改成方括号[],然后在后面加上print(N)这样的语句:

# Debug & view contents of N like this:
N = [ list(map(int, input().split()))[1:] for _ in range(K) ]
print(N)


第二个疑问:

变量results的值是怎么来的?

为了让阅读此答案的每个人都清楚,在下面的示例中,我会让:

N = [[1, 2], [3, 4], [5, 6]]

product(*N) 将为包含 N 的每个子列表的笛卡尔积的元组列表返回一个迭代器,例如product(*N) 返回元组 (1, 3, 5), (1, 3, 6), (1, 4, 5), (1, 4, 6), ..., (2, 4, 6)

您可以通过 print([x for x in product(*N)]) 来验证这一点,或者如果您在 for 循环中遍历 N 并打印出每个值:

N = [[1, 2], [3, 4], [5, 6]]

# You can verify the contents of a generator like this:
print([item for item in product(*N)])

# Or like this:
for item in product(*N):
    print(item)


分解results = map(lambda x: sum(i**2 for i in x)%M, product(*N))

(i**2 for i in x) 中,x 指的是元组之一,例如(1, 3, 5)product(*N) 中,并返回一个包含值(1, 9, 25) 的生成器。所以它基本上是对元组(1, 3, 5) 中的每个整数求平方并返回它们平方的元组。

sum(i**2 for i in x) 对元组 x 中的每个整数求和,得到 1 + 9 + 25 = 35。

之后,将得到的总和 35 应用于模运算% M

最后,results 将包含生成器,其中包含每个元组的所有合成模数和。同样,您可以通过执行print([x for x in results]) 来验证results 的内容,或者如果您在for 循环中迭代results 并打印出每个值,就像在上面的代码sn-p 中所做的那样。

print(max(results)) 会给你results 中的最大值。


我假设使用的是 Python-3.x。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-03
    • 2010-11-07
    • 2011-04-13
    • 2015-07-19
    • 2011-05-09
    • 1970-01-01
    相关资源
    最近更新 更多