python - 在不使用列表的情况下计算 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 ____
。
但是..因为我不能使用列表,所以我不完全确定如何解决这个问题。
解决方案
您可以使用迭代器而不是列表,例如:
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)
用于获得最后最大的增加。
推荐阅读
- android - Ionic android 构建失败,找不到插件“proposal-numeric-separator”
- node.js - 使用通配符路径的 Cloud Functions 不起作用
- java - javax.swing.UIManager.getIcon(Object key) 从 ArrayList 流式传输字符串键时返回 null
- javascript - avascript:history.go(-window.history.length) 不起作用
- sql - 选择类别请求期间的sql动态列
- php - 如何启用opencart Seo Url
- ios - 如何从标签栏打开侧边菜单
- python - 为什么我的文本在屏幕上运行而不是在 Python 终端中运行?
- c# - 如何在 C# 中减去两种不同类型的两个数量 - 十进制和双精度?
- docker - docker可以从环境变量中读取凭据吗?