Python求balance_list【三】

本文为博主原创,未经授权,严禁转载及使用。
本文链接:https://blog.csdn.net/zyooooxie/article/details/130159648

很早之前,我写了2篇 如何求balance_list 的博客: https://blog.csdn.net/zyooooxie/article/details/107159798 、 https://blog.csdn.net/zyooooxie/article/details/108179627;

最近又在学习,翻看这2篇博客,感觉写的不太好,我重新整理下;

【实际这篇博客推迟发布N个月】

个人博客:https://blog.csdn.net/zyooooxie

【以下所有内容仅为个人项目经历,如有不同,纯属正常】

需求

有一个情景:某商店,今天进货、卖东西,总共发生5笔交易【-10,+20,-15,+150,-100】,最初手上是50块钱,想知道 每笔交易发生后,手上有多少钱?

过程:
50-10 为第一笔交易后 手上的钱【期初 + 第一笔】;
50-10+20 为第二笔交易后 手上的钱【第一笔交易后的钱 + 第二笔】;
50-10+20-15 为第三笔交易后 手上的钱【第二笔交易后的钱 + 第三笔】;

依此类推;若生意极其火爆,当天共100w笔交易,那该咋做呢?

求balance_list【一】

https://blog.csdn.net/zyooooxie/article/details/107159798

"""
@blog: https://blog.csdn.net/zyooooxie
@qq: 153132336
@email: [email protected]
"""

import random
from user_log import Log
from csdn.p_balance_list_2 import test_recursion2, test_sum, test_recursion2__, test_recursion_2_1

from XXX_use.common_functions import spend_time_deco

nums = 9876540
# amount_list = random.sample(range(-9999, 9999), nums)
amount_list = random.choices(range(-9999, 9999), k=nums)
opening_balance = 1234
Log.info(opening_balance)
Log.info(amount_list[-50:])
Log.info(len(amount_list))


def sum_(x, y):
    return x + y


def reduce_func(func, seq, init_num=None):
    if init_num is not None:
        res = init_num

    else:
        res = seq.pop(0)

    # Log.info(f'初始值:{res}')
    balance_list = list()

    for i in seq:
        res = func(res, i)
        balance_list.append(res)
    else:
        Log.debug(f'最后余额是 {res}')

    return res, balance_list


@spend_time_deco
def test_reduce_3(reduce_amount_list, reduce_opening_balance):
    last_ele = reduce_func(sum_, reduce_amount_list, reduce_opening_balance)
    Log.info(len(last_ele[1]))
    Log.info(last_ele[1][-50:])


@spend_time_deco
def test_while(while_amount_list, while_opening_balance):
    balance_list = list()
    i = 0
    b = while_opening_balance
    len_ = len(while_amount_list)

    while i < len_:
        b = sum([b, while_amount_list[i]])
        balance_list.append(b)

        i = i + 1
    Log.info(len(balance_list))
    Log.info(balance_list[-50:])


@spend_time_deco
def test_for(for_amount_list, for_opening_balance):
    balance_list = list()
    res = for_opening_balance

    for i in for_amount_list:
        res = i + res
        balance_list.append(res)

    Log.info(len(balance_list))
    Log.info(balance_list[-50:])


@spend_time_deco
def test_accumulate(accumulate_amount_list, accumulate_opening_balance):
    from itertools import accumulate

    res = accumulate(accumulate_amount_list, initial=accumulate_opening_balance)
    list_ = list(res)

    Log.info(len(list_))    # accumulate 传的initial,会作为 iterable 的第一个元素
    Log.info(list_[-50:])


if __name__ == '__main__':
    pass

    # test_reduce()
    # test_reduce_2()

    test_reduce_3(amount_list, opening_balance)

    test_while(amount_list, opening_balance)

    test_for(amount_list, opening_balance)

    test_accumulate(amount_list, opening_balance)

    # test_recursion2(amount_list, opening_balance)
    test_recursion_2_1(amount_list, opening_balance, 'test_recursion')

    test_sum(amount_list, opening_balance)

    # test_recursion2__(amount_list, opening_balance)
    test_recursion_2_1(amount_list, opening_balance, 'test_recursion__')


求balance_list【二】

https://blog.csdn.net/zyooooxie/article/details/108179627

"""
@blog: https://blog.csdn.net/zyooooxie
@qq: 153132336
@email: [email protected]
"""

import sys
import math

from XXX_use.common_functions import spend_time_deco
from user_log import Log

gl_sys_limit = 2000
sys.setrecursionlimit(gl_sys_limit)


def test_recursion(result_list: list, recursion_index: int, recursion_amount_list, recursion_opening_balance):
    """

    :param result_list:
    :param recursion_index: 传的 必须是 len(recursion_amount_list)-1
    :param recursion_amount_list:
    :param recursion_opening_balance:
    :return:
    """

    # Log.info(f'{len(result_list)}, {len(recursion_amount_list)}')
    if recursion_index == 0:
        res_0 = recursion_opening_balance + recursion_amount_list[0]
        # Log.info(res_0)
        result_list.append(res_0)
        # Log.info(f'{len(result_list)}, {len(recursion_amount_list)}')
        return res_0

    res_before = test_recursion(result_list, recursion_index - 1, recursion_amount_list, recursion_opening_balance)
    res = res_before + recursion_amount_list[recursion_index]
    # Log.info(res)
    result_list.append(res)

    # Log.info(f'{len(result_list)}, {len(recursion_amount_list)}')

    if len(result_list) == len(recursion_amount_list):
        # Log.info(result_list)
        return result_list

    return res


@spend_time_deco
def test_sum(sum_amount_list, sum_opening_balance):
    res_list = list()
    for index_, ele_ in enumerate(sum_amount_list):
        if index_ == 0:
            ob = sum_opening_balance
            res = 0
        else:
            ob = 0

        res = sum([ele_, res], ob)
        # Log.info(res)

        res_list.append(res)

    Log.info(len(res_list))
    Log.info(res_list[-50:])


def test_recursion__(recursion_index: int, recursion_amount_list, recursion_opening_balance, recursion_dict):
    # Log.info(f'{recursion_index}, {recursion_dict}')

    if recursion_index == 0:
        value_0 = recursion_opening_balance + recursion_amount_list[0]
        recursion_dict[0] = value_0
        # Log.info(recursion_dict)

    if recursion_index not in recursion_dict:
        value = test_recursion__(recursion_index - 1, recursion_amount_list, recursion_opening_balance,
                                 recursion_dict) + recursion_amount_list[recursion_index]
        recursion_dict[recursion_index] = value
        # Log.info(recursion_dict)
        # Log.info(f'{len(recursion_dict)}, {len(recursion_amount_list)}')

    if len(recursion_dict) == len(recursion_amount_list):
        # Log.info(recursion_dict)
        # Log.info(len(recursion_dict))
        return list(recursion_dict.values())

    return recursion_dict[recursion_index]


@spend_time_deco
def test_recursion_2_1(recursion_amount_list, recursion_opening_balance, func_name):
    # 实际分组用的时候 比 设置的最大递归深度 要小一点
    sys_limit = int(gl_sys_limit * 0.9)

    times_ = math.ceil(len(recursion_amount_list) / sys_limit)
    Log.info(f'{sys_limit}, {times_}')

    al = recursion_amount_list[:sys_limit]
    # Log.info(len(al))

    if func_name == 'test_recursion__':
        res = test_recursion__(len(al) - 1, al, recursion_opening_balance, dict())

    elif func_name == 'test_recursion':
        res = test_recursion([], len(al) - 1, al, recursion_opening_balance)

    else:
        return

    # Log.info(res)

    for i in range(1, times_):
        start, end = sys_limit * i, sys_limit * (i + 1)
        al = recursion_amount_list[start:end]

        if func_name == 'test_recursion__':

            new = test_recursion__(len(al) - 1, al, res[-1], dict())

        elif func_name == 'test_recursion':
            new = test_recursion([], len(al) - 1, al, res[-1])

        else:
            return

        # Log.info(new)

        res.extend(new)

    Log.info(len(res))
    Log.info(res[-50:])


if __name__ == '__main__':
    pass

    from csdn.p_balance_list_1 import amount_list, opening_balance

    # abc = test_recursion([], len(amount_list) - 1, amount_list, opening_balance)
    # Log.info(abc)

    test_recursion_2_1(amount_list, opening_balance, 'test_recursion')

    # test_sum(amount_list, opening_balance)

    # test_recursion__(0, amount_list, opening_balance, dict())
    # test_recursion__(len(amount_list) - 1, amount_list, opening_balance, dict())

    test_recursion_2_1(amount_list, opening_balance, 'test_recursion__')


执行时间、balance_list的对比


def spend_time_deco(func):
    def inner(*args, **kwargs):
        Log.info('')

        before = datetime.datetime.now()
        Log.info(before)

        res = func(*args, **kwargs)

        after = datetime.datetime.now()
        Log.info(after)

        spend = after - before
        Log.info(f'{func.__name__} 实际花费:{spend.total_seconds()}')

        Log.info('')

        return res

    return inner

执行 p_balance_list_1.py的结果:

Python求balance_list【三】_第1张图片

Python求balance_list【三】_第2张图片

按着我的写法,9876540笔交易 计算balance_list,使用 accumulate()、for循环 的效率最高。

本文链接:https://blog.csdn.net/zyooooxie/article/details/130159648

个人博客 https://blog.csdn.net/zyooooxie

你可能感兴趣的:(Python学习,python)