TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Python Multiple Assignment Is a Puzzle

62 点作者 jw2013将近 11 年前

7 条评论

todd8将近 11 年前
I think it&#x27;s easier to see what is going on without the nested subscripting:<p><pre><code> &gt;&gt;&gt; i = 0 &gt;&gt;&gt; a = [0, 0] &gt;&gt;&gt; i, a[i] = 1, 10 &gt;&gt;&gt; a [0, 10] </code></pre> versus<p><pre><code> &gt;&gt;&gt; i = 0 &gt;&gt;&gt; a = [0, 0] &gt;&gt;&gt; a[i], i = 10, 1 &gt;&gt;&gt; a [10, 0]</code></pre>
评论 #8093061 未加载
评论 #8092537 未加载
ghshephard将近 11 年前
While it may require an extra set, the following is a lot more pythonic, and also finds the first missing positive in the same two passes that your code did (which is actually O(2n), and honestly made my eyes bleed trying to follow.)<p><pre><code> def missPos(a): b={x for x in a} for x in range(1,len(b)+2): if not x in b: return x</code></pre>
评论 #8092517 未加载
评论 #8092400 未加载
评论 #8093678 未加载
评论 #8092403 未加载
评论 #8092362 未加载
yoo-interested将近 11 年前
This reminded me of gotchas one can fall to when defining some Lisp macro from scratch. So I decided to test whether rotatef works exactly like Python&#x27;s multiple assignment:<p><pre><code> (let ((A (vector 2 1))) (rotatef (elt A 0) (elt A (1- (elt A 0)))) A) </code></pre> It returns a changed vector as if indexes were saved.<p>I am not sure which should be considered the right behavior.
评论 #8093963 未加载
tom1024将近 11 年前
Please note, that the solution from the post has O(n) space complexity (you modify the input and this counts as using the extra memory).
kghose将近 11 年前
<p><pre><code> A = [1, 2, 4, 5, 7] A_s = sorted(A) b = A_s[0] for a in A_s[1:]: if a - b &gt; 1: print b + 1 break else: b = a else: print &#x27;No missing element&#x27; </code></pre> Trying to be more Pythonic:<p><pre><code> def test(l): l_s = sorted(l) print [l0 + 1 for l1, l0 in zip(l_s[1:], l_s[:-1]) if l1 - l0 &gt; 1]</code></pre>
评论 #8096786 未加载
评论 #8094501 未加载
podlipensky将近 11 年前
Interesting post regarding python, but the algo is incorrect, consider test case firstMissingPositive([100,101,103,104]) will return 1 instead of 102
zebulanmcranahn将近 11 年前
def findMissingPositive(A): A.sort() return min([x for x in range(A[0], A[-1]+1) if x not in A])
评论 #8092135 未加载