Python – 所有位置字符组合
给定一个字符K,追加到每个索引和所有长度组合。
Input : test_str = ‘gfg’, K = ‘$’
Output : [‘gfg’, ‘gf$’, ‘g$g’, ‘g$$’, ‘$fg’, ‘$f$’, ‘$$g’, ‘$$$’]
Explanation : All possible pairs with replacement occurrences.
Input : test_str = ‘gfg’, K = ‘*’
Output : [‘gfg’, ‘gf*’, ‘g*g’, ‘g**’, ‘*fg’, ‘*f*’, ‘**g’, ‘***’]
Explanation : All possible pairs with replacement occurrences.
方法 #1:使用循环 + zip() + join() + product()
在这里,形成组合的任务是使用 product() 完成的,loop 用于元素的迭代,join() 用于获得所需的结果,而 zip() 用于将每个提取的产品与原始 String 组合。
Python3
# Python3 code to demonstrate working of
# All Position Character Combination
# Using loop + zip() + join() + product()
import itertools
# initializing strings
test_str = 'gfg'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = "$"
res = []
# True and false represent Character from String and K respectively.
for sub in itertools.product((True, False), repeat = len(test_str)):
res.append("".join(chr if ele else K for chr, ele in zip(test_str, sub)))
# printing result
print("The required Combinations : " + str(res))
Python3
# Python3 code to demonstrate working of
# All Position Character Combination
# Using list comprehension
import itertools
# initializing strings
test_str = 'abc'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = "$"
# one liner to perform this task
res = ["".join(chr if ele else K for chr, ele in zip(test_str, sub)) \
for sub in itertools.product((True, False), repeat = len(test_str))]
# printing result
print("The required Combinations : " + str(res))
输出:
The original string is : gfg
The required Combinations : ['gfg', 'gf$', 'g$g', 'g$$', '$fg', '$f$', '$$g', '$$$']
方法#2:使用列表推导
这类似于上述方法,唯一的区别是它是在一行中的所有功能的简写。
Python3
# Python3 code to demonstrate working of
# All Position Character Combination
# Using list comprehension
import itertools
# initializing strings
test_str = 'abc'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = "$"
# one liner to perform this task
res = ["".join(chr if ele else K for chr, ele in zip(test_str, sub)) \
for sub in itertools.product((True, False), repeat = len(test_str))]
# printing result
print("The required Combinations : " + str(res))
输出:
The original string is : abc
The required Combinations : ['abc', 'ab$', 'a$c', 'a$$', '$bc', '$b$', '$$c', '$$$']