这是google里面的python入门教程,basic练习的list2.py。第一道题是查找一个list里面有没有相邻的重复元素,有的话就删掉。
我的程序
def remove_adjacent(nums):
# +++your code here+++
i=0
numsSlim=[]
while i<len(nums):
if i+1<len(nums):
if nums[i]!=nums[i+1]:
numsSlim.append(nums[i])
else:
numsSlim.append(nums[i])
i+=1
return numsSlim
别人家的程序
def remove_adjacent(nums):
result = []
for num in nums:
if len(result) == 0 or num != result[-1]:
result.append(num)
return result
第二道题是给两个已经从小到大排好序的list,让你把两个list融合起来,同时保证仍旧是从小到大排序。最好是对于两个list都只读取一次
我的程序
def linear_merge(list1, list2):
result=list1+list2
return sorted(result)
别人家的程序
def linear_merge(list1, list2):
result = []
# Look at the two lists so long as both are non-empty.
# Take whichever element [0] is smaller.
while len(list1) and len(list2):
if list1[0] < list2[0]:
result.append(list1.pop(0))
else:
result.append(list2.pop(0))
# Now tack on what's left
result.extend(list1)
result.extend(list2)
return result
嗯,我觉得自己的智商被碾压了