在不使用列表的情况下计算 10 个整数之间的最大增量

Computing largest increase between 10 integers without using a list

我有一个问题集需要解决,但无法想象如何使用我目前知道的工具来解决这个问题。有人可以就我应该如何解决这个问题提供一些指导吗?

问题集:

Design a program to compute the largest increase that occurred in a list of 10 numbers. Note: Your design cannot assign a separate variable per number nor can you use a list.

The program should read any 10 integers and print a result: 

Numbers : 48 54 49 47 62 64 79 80 82 84

Largest increase of 15
from 64 to 79
occurred between day 6 and day 7

在我看来 - 我会通过将数字转换为列表并遍历列表来比较天数之间的差异来解决这个问题。如果下一组天数的差异大于前一组天数,它将替换该值。

从那里我将在 Largest increase of ____ 中输入迭代的最终值。

但是..因为我不能使用列表,所以我不完全确定如何解决这个问题。

您可以使用迭代器代替列表,例如:

from itertools import tee


numbers = [48, 54, 49, 47, 62, 64, 79, 80, 82, 84]
a, b = tee(numbers)
next(b, None)

maxnum, argmax = max(map(lambda x: (x[1][1] - x[1][0], x[0]), enumerate(zip(a, b))))
print(maxnum, (numbers[argmax], numbers[argmax + 1]))

输出:

15 (64, 79)

为了解决这个问题,使用了以下方法:

  • python 内置函数
    • enumerate 用于遍历计数和值
    • zip 用于聚合多个迭代器的值
    • map 用于将函数应用于迭代器的每个项目
  • 模块 itertools 和带有 tee 函数的“Itertools Recipe”用于遍历对,参见 https://docs.python.org/3/library/itertools.html#itertools-recipes
  • max 函数中的元组比较。比较元组(increas, increase position)用于获取最后最大的增加。