python面试题:python计算股票收益最大化

股票收益最大化

思路:
计算差值: 后一天的价格 - 前一天的价格
如果是正数,说明股票上涨,连续为正则为持续上涨,仍然是赚的
如果是负数,股票下跌,不持有该股,不管我们的事

代码:

import random

listOne = []
for i in range(10):
    temp = random.randint(10,100)
    listOne.append(temp)

# 测试数据 股票价格
print("股票价格", listOne)

print("-"*20)


def maxProfit(tempList):
# 计算股票最大收益

    newList = []
    for i in range(len(tempList)):
        if i < len(listOne) - 1:
            # 后一天-前一天
            chazhi = tempList[i + 1] - tempList[i]
            newList.append(chazhi)

    # 股票价格差值
    print("股票价格差值", newList)

    # 股票增值数
    newList2 = []
    for i in newList:
        # 将增值保存到列表
        if i > 0:
            newList2.append(i)

    print("股票增值数", newList2)
    return sum(newList2)

if __name__ == '__main__':
    result = maxProfit(listOne)
    print("股票最大收益", result)

最后打印结果:

股票价格 [77, 84, 59, 56, 69, 38, 53, 77, 35, 89]
--------------------
股票价格差值 [7, -25, -3, 13, -31, 15, 24, -42, 54]
股票增值数 [7, 13, 15, 24, 54]
股票最大收益 113
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容