不使用itertools的 Python 組合

在許多情況下,我們必須從單個字符串或不同的數字集合中找到不同的組合。

為了在 Python 中找到這樣的組合,我們有 itertools 模塊,這是尋找不同組合和排列的最常見模塊。

這個模塊是一個非常有效的工具,可以快速找到所有可能的組合。但是 itertools 模塊函數並不是我們可以用來找到組合的唯一可能的方法。

在本教程中,我們將了解在 Python 中不使用 itertools 就可以從字符串中找到不同組合的不同方法。

不使用 itertools 的 Python 組合

在本節中,我們將編寫 Python 程序,通過在其中實現幾個方法來查找組合。我們將在 Python 程序中使用以下方法:

  • 使用迭代法
  • 使用遞歸方法

在這兩種方法中,首先,我們將查看程序並了解它的工作原理,然後我們將轉到解釋部分來了解其中使用的實現。

使用迭代法的 Python 組合:

為了在程序中實現迭代方法,我們必須導入 numpy 庫來使用它的函數。讓我們理解下面的例子。

示例:


# Import numpy module in program
import numpy as np
# Default function to use iterative approach
def RecurCombo(iterArray, num):
 char = tuple(iterArray) # converting input string into a tuple
 m = len(char) # length of string or tuple
 if num > m: # checking if length of combinations is more than length of string
   return
 index = np.arange(num) # using numpy arrange() function
 # Yielding the first sequence
 yield tuple(char[i] for i in index)
 # Using while loop with true condition
 while True:
  # iterating over the tuple we made using reversed for loop
  for a in reversed(range(num)):
     if index[a] != a + m - num:
         break
     else:
              return
  index[a] += 1
  # another for loop iteration
  for b in range(a + 1, num):
   index[b] = index[b - 1] + 1
  yield tuple(char[a] for a in index) # yielding possible combinations from given string
# Taking an input string from user
inputArray = input("Enter an input string to find combinations: ")
# Printing different combinations as result in output
print("All possible combinations of three letter sets from the string given by you is: ")
print([x for x in RecurCombo(inputArray, 3)])

輸出:

Enter an input string to find combinations: JavaTpoint
All possible combinations of three letter sets from the string given by you is: 
[('J', 'a', 'v'), ('J', 'a', 'a'), ('J', 'a', 'T'), ('J', 'a', 'p'), ('J', 'a', 'o'), ('J', 'a', 'i'), ('J', 'a', 'n'), ('J', 'a', 't')]

說明:

我們在上面的程序中使用了迭代方法來從輸入字符串中找到組合。

首先,我們使用了一個默認的 Python 函數,輸入字符串和組合集的長度作為參數。然後,我們將輸入字符串轉換成元組。我們還檢查了組合所需的長度是否不超過字符串的長度。

之後,我們使用 numpy 的 arrange()函數來設置元組的索引。我們將使用索引變量迭代元組。

然後,我們在 While循環中使用反向 for循環和另一個 for循環迭代元組。在循環迭代之後,我們得到了所需長度的可能組合。

然後,我們從用戶那裡獲取了一個輸入字符串。最後,我們從輸入字符串中返回三個集合的組合。

使用遞歸方法的 Python 組合:

在遞歸方法方法中,我們將遍歷由字符串列表組成的列表。讓我們理解下面的例子。

示例:


# Default Python function to use recursive approach
def RecurCombo(array, num): 
    if num == 0: 
        return [[]] # if length for combination is 0
    l =[] # list to printed in result
    # Using for loop to implement recursive approach
    for j in range(0, len(array)): 
        emptyArray = array[j] # define an empty array to print list of sets
        recurList = array[j + 1:]
        # Recursion method on list defined in function
        for x in RecurCombo(recurList, num-1): 
            l.append([emptyArray]+x) # appending list
    return l # list as result of recursion
if __name__=="__main__":
    # Taking an input string from user
    inputArray = input("Enter an input string to find combinations: ")
    # Printing different combinations as result in output
    print("All possible combinations of three letter sets from the string given by you is: ")
    print(RecurCombo([a for a in inputArray], 3))

輸出:

Enter an input string to find combinations: Python
All possible combinations of three letter sets from the string given by you is: 
[['P', 'y', 't'], ['P', 'y', 'h'], ['P', 'y', 'o'], ['P', 'y', 'n'], ['P', 't', 'h'], ['P', 't', 'o'], ['P', 't', 'n'], ['P', 'h', 'o'], ['P', 'h', 'n'], ['P', 'o', 'n'], ['y', 't', 'h'], ['y', 't', 'o'], ['y', 't', 'n'], ['y', 'h', 'o'], ['y', 'h', 'n'], ['y', 'o', 'n'], ['t', 'h', 'o'], ['t', 'h', 'n'], ['t', 'o', 'n'], ['h', 'o', 'n']]

說明:

在上面的程序中,在實現遞歸方法時,我們沒有使用 Python 的任何特定模塊。像迭代方法一樣,我們使用默認函數在代碼中實現遞歸方法。

在這個程序中,我們使用一個條件來檢查組合的所需長度。然後,我們在帶有 for循環的函數中使用遞歸方法。使用遞歸方法後,我們從輸入字符串中返回所需長度的組合。最後,我們將字符串作為用戶的輸入,並在輸出中返回三個集合的組合。


原創文章,作者:簡單一點,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/130081.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
簡單一點的頭像簡單一點
上一篇 2024-10-03 23:27
下一篇 2024-10-03 23:27

相關推薦

  • 如何查看Anaconda中Python路徑

    對Anaconda中Python路徑即conda環境的查看進行詳細的闡述。 一、使用命令行查看 1、在Windows系統中,可以使用命令提示符(cmd)或者Anaconda Pro…

    編程 2025-04-29
  • Python列表中負數的個數

    Python列表是一個有序的集合,可以存儲多個不同類型的元素。而負數是指小於0的整數。在Python列表中,我們想要找到負數的個數,可以通過以下幾個方面進行實現。 一、使用循環遍歷…

    編程 2025-04-29
  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • Python計算陽曆日期對應周幾

    本文介紹如何通過Python計算任意陽曆日期對應周幾。 一、獲取日期 獲取日期可以通過Python內置的模塊datetime實現,示例代碼如下: from datetime imp…

    編程 2025-04-29
  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • 蝴蝶優化算法Python版

    蝴蝶優化算法是一種基於仿生學的優化算法,模仿自然界中的蝴蝶進行搜索。它可以應用於多個領域的優化問題,包括數學優化、工程問題、機器學習等。本文將從多個方面對蝴蝶優化算法Python版…

    編程 2025-04-29
  • Python字典去重複工具

    使用Python語言編寫字典去重複工具,可幫助用戶快速去重複。 一、字典去重複工具的需求 在使用Python編寫程序時,我們經常需要處理數據文件,其中包含了大量的重複數據。為了方便…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29
  • Python程序需要編譯才能執行

    Python 被廣泛應用於數據分析、人工智能、科學計算等領域,它的靈活性和簡單易學的性質使得越來越多的人喜歡使用 Python 進行編程。然而,在 Python 中程序執行的方式不…

    編程 2025-04-29
  • Python清華鏡像下載

    Python清華鏡像是一個高質量的Python開發資源鏡像站,提供了Python及其相關的開發工具、框架和文檔的下載服務。本文將從以下幾個方面對Python清華鏡像下載進行詳細的闡…

    編程 2025-04-29

發表回復

登錄後才能評論