jackfrued / jackfrued/Python-100-Days
提个疑问,Day07 练习4
Nobody has claimed this yet.
- Dominant language
- Jupyter Notebook
- Stars
- 187k
- Forks
- 55.8k
- PR merge metrics
- No merged PRs in 30d
Description
练习4:设计一个函数返回传入的列表中最大和第二大的元素的值。
参考答案:
def max2(x):
m1, m2 = (x[0], x[1]) if x[0] > x[1] else (x[1], x[0])
for index in range(2, len(x)):
if x[index] > m1:
m2 = m1
m1 = x[index]
elif x[index] > m2:
m2 = x[index]
return m1, m2
请问上面为什么要在赋值变量时先判断一次0和1,然后在for里跳过0和1从2开始?
下面这段代码不是更简便一点吗?我想请问下这里面的区别,请解答!
def max3(x):
m1, m2 = (x[0], x[1])
for index in range(len(x)):
if x[index] > m1:
m2 = m1
m1 = x[index]
elif x[index] > m2:
m2 = x[index]
return m1, m2
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the Day07 Exercise 4 reference answer and the alternative code shown in the issue. Compare their initialization and loop ranges; done means adding a clear explanation of why the reference answer treats the first two elements separately, or confirming the alternative's behavior in the exercise documentation.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 1/5
- Estimated time
- Under an hour
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 35/100