首页 > 解决方案 > 在不使用列表的情况下计算 10 个整数之间的最大增量

问题描述

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

问题集:

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 ____

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

标签: pythonlistiteration

解决方案


您可以使用迭代器而不是列表,例如:

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和“Itertools 配方”,tee具有用于迭代对的功能,请参阅https://docs.python.org/3/library/itertools.html#itertools-recipes
  • 函数中的元组比较max。元组的比较(increas, increase position)用于获得最后最大的增加。

推荐阅读