“返回整数列表的”居中“平均值,我们将说这是值的平均值,但忽略列表中的最大值和最小值。如果最小值有多个副本,忽略一个副本,对于最大值也一样。使用整数除法生成最终平均值。您可以假设列表长度为3或更长。”
这是我在家庭作业中遇到的一个问题,我很困惑如何找到最大/最小的数字,并将它们从清单中删除。这是我到目前为止所拥有的。它适用于我必须通过的10/14方案。我认为这仅仅是因为它抓住了中位
def centered_average(nums):
x = 0
for i in range(len(nums)):
    x = i + 0
y = x + 1
if y%2 == 0:
    return (nums[y/2] + nums[(y/2)+1]) / 2
else:
    return nums[y/2]发布于 2017-03-27 08:07:28
这是一个非常不合标准的问题解决方案。这段代码是一段糟糕的代码,没有考虑到复杂性和空间。但是我认为要遵循的思想过程类似于代码中的步骤。这样就可以改进了。
def centered_average(nums):
#Find max and min value from the original list
max_value = max(nums)
min_value = min(nums)
#counters for counting the number of duplicates of max and min values.
mx = 0
mn = 0
sum = 0
#New list to hold items on which we can calculate the avg
new_nums = []
#Find duplicates of max and min values
for num in nums:
  if num == max_value:
    mx += 1
  if num == min_value:
    mn += 1
#Append max and min values only once in the new list
if mx > 1:
  new_nums.append(max_value)
if mn > 1:
  new_nums.append(min_value)
#Append all other numbers in the original to new list
for num in nums:
  if num != max_value and num != min_value:
    new_nums.append(num)
#Calculate the sum of all items in the list
for new in new_nums:
  sum += new
#Calculate the average value.
avg = sum/len(new_nums)
return avghttps://stackoverflow.com/questions/34184200
复制相似问题