簡體   English   中英

如何在python中將多個循環'for'設置為函數的參數以找到將句號分成n部分的所有可能性?

[英]How to set a number of loop 'for' as a parameter of a function in python to find all the possibility to cut a period in n parts?

這是一個丑陋的代碼,用於查找將一個句點分成 5 個部分的所有可能性。 是否有可能創建一個使它看起來更好的函數,並將切割次數作為參數?

我只能編寫每個for循環:

part_list = pd.DataFrame(columns=['period_array'])
for i in range(1, period_size):
    for j in range(1, period_size - i):
        for h in range(1, period_size - (i + j)):
            for g in range(1, period_size - (i + j + h)):
                part_list = part_list.append({'period_array':
                                                  np.array([[0, i],
                                                            [i, i + j],
                                                            [i + j, i + j + h],
                                                            [i + j + h, i + j + h + g],
                                                            [i + j + h + g, period_size]])},
                                             ignore_index=True)

使用模塊 itertools中的函數combinations來生成切割點的所有組合:

from itertools import combinations, chain, pairwise

def all_cuts(seq, n):
    for comb in combinations(range(1,len(seq)), n-1):
        yield tuple(seq[i:j] for i,j in pairwise(chain((0,), comb, (len(seq),))))

print( list(all_cuts('Hello, World!', 3)) )
# [('H', 'e', 'llo, World!'), ('H', 'el', 'lo, World!'),
#  ('H', 'ell', 'o, World!'), ('H', 'ello', ', World!'),
#  ('H', 'ello,', ' World!'), ...
#                        ..., ('Hello, Wor', 'l', 'd!'),
#  ('Hello, Wor', 'ld', '!'), ('Hello, Worl', 'd', '!')]

我修改了代碼,使數據幀和應用方法的運行時間更短(“for 循環”對於長序列來說效率不高)。

對於 52 個列表中的 3 個周期,我將時間從 14.6 秒減少到 0.2 秒。

這是我的最終代碼:非常感謝@Stef :)

    COMBINATION_VECTOR = 'combination vector'
    PERIOD_ARRAY = 'period array'
    
    def get_partition_table(period_resolution: int, number_of_changes: int):
        """
        This function creates a dataframe of all the possible combination of date of change over a year
        :param period_resolution: resolution (month : 12, week: 52 or days: 365)
        :param number_of_changes
        :return: dataframe of each period table
        """
    
        scale_factor = 365 // period_resolution
    
        def from_combinations_to_period_array(comb):
            """
            This returns the period array of the specific combination : [[0, d1], [d1, d2] ... [dn, 365]]
            :param comb: combinations of dates to create the period array
            :return: period array
            """
            return np.array([[i, j] for i, j in pairwise(it.chain((0,), comb, (period_resolution,)))])
    
        part_list = pd.DataFrame(
            {COMBINATION_VECTOR: list(it.combinations(range(1, period_resolution), number_of_changes))})
    
        part_list[PERIOD_ARRAY] = part_list.apply(
            lambda x: from_combinations_to_period_array(x[COMBINATION_VECTOR]), axis=1)
        
        part_list.drop(COMBINATION_VECTOR, axis=1)
    
        return part_list * scale_factor

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM