Python计算序列中数字最大差值(美团2016校招笔试题)

题目要求:给定一个包含若干数字的序列A(本文以列表为例),求满足0≤a≤b<n(其中n为序列长度)的A[b] - A[a]的最大值。

编程要点:循环结构用法,切片,内置函数enumerate(),列表推导式。

参考代码:

from random import randrange

def maxDifference(lst): # 负无穷大 diff = -float('inf') for index, value in enumerate(lst[:-1]): for v in lst[index+1:]: t = v-value if t > diff: result = (value,v) diff = t return result

for _ in range(10): print('='*20) lst = [randrange(1,100) for _ in range(20)] print(lst) print(maxDifference(lst))

运行结果:

==================== [51, 41, 43, 38, 38, 38, 30, 5, 96, 84, 6, 60, 81, 77, 6, 98, 42, 33, 97, 99] (5, 99) ==================== [41, 88, 4, 15, 99, 82, 54, 96, 66, 74, 32, 28, 21, 96, 89, 44, 42, 25, 57, 84] (4, 99) ==================== [88, 61, 1, 87, 18, 38, 50, 71, 95, 80, 64, 21, 12, 87, 10, 86, 45, 77, 10, 1] (1, 95) ==================== [91, 10, 84, 17, 74, 21, 95, 41, 68, 40, 31, 61, 80, 45, 91, 6, 83, 22, 76, 25] (10, 95) ==================== [56, 92, 83, 92, 52, 75, 87, 11, 6, 87, 60, 77, 85, 24, 82, 2, 84, 44, 9, 27] (2, 84) ==================== [36, 49, 27, 33, 57, 19, 74, 81, 46, 28, 4, 92, 7, 40, 52, 60, 14, 58, 21, 59] (4, 92) ==================== [73, 21, 47, 44, 74, 23, 75, 11, 95, 89, 4, 26, 22, 62, 55, 36, 17, 37, 73, 57] (11, 95) ==================== [94, 77, 42, 90, 60, 23, 57, 34, 61, 70, 80, 6, 47, 60, 12, 15, 65, 9, 36, 30] (6, 65) ==================== [39, 25, 97, 21, 91, 54, 69, 11, 68, 54, 72, 36, 16, 52, 29, 31, 95, 74, 99, 28] (11, 99) ==================== [53, 77, 51, 15, 87, 29, 16, 94, 79, 72, 51, 64, 2, 92, 29, 80, 32, 87, 78, 79] (2, 92)

原文发布于微信公众号 - Python小屋(Python_xiaowu)

原文发表时间:2017-05-03

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券