如何使用.combinations()替换字符串中的多个字符?

2024-05-04 11:01:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我在这里问的第一个问题。所以我学会了如何使用我的代码从一个范围内生成和计算所有可能的组合:

import random
from random import shuffle
import itertools
import math
from math import factorial

# to calculate total number of combinations from a select range of elements:
# max!/(select_num_of_elems! * (max - select_num_of_elems)!

ranger = range(0,30+1) 

enlist_range=list(ranger)
print(f"well this what happens when you print the enlist_range...cuz its an array " + 
                                                                   "{enlist_range}")
max_val_of_range = len(enlist_range)
print(f"the length of enlist_range is {max_val_of_range}")

select_num_of_elems= int( input(f"enter in the range of select elements that will " + 
                                 "recombinate \n by the way it can't be more than the " +
                                 "range max of {max_val_of_range} \n") )


# max!/(select_num_of_elems! * (max - select_num_of_elems)!
total_combos = factorial(max_val_of_range)/( factorial(select_num_of_elems) * 
                                factorial( max_val_of_range - select_num_of_elems ) )
print()
print(f"the total number of combos from a range of {max_val_of_range} with "  + 
                                  "{select_num_of_elems} selected number of " +
                                  "elements is {total_combos}")
print()
for suby in itertools.combinations(enlist_range,select_num_of_elems):    
  print(suby) 

如何使用生成的所有组合值来同时替换字符串中的多个字符?你知道吗

如果我有一个字符串: some_string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 例如,给定一个组合对[(0,12)],我想得到一个输出:

_BCDEFGHIJKL_NOPQRSTUVWXYZ

使用len(some_string)这将使我的n value26,并说我为这个组合选择了r value2

我会生成组合,如[(0, 12)][(2,14)]

我想让每一个组合都用'_'替换一个字母。我尝试过用list(some_string)将字符串分开,然后用for循环与list(some_string).insert((combo_index), "_")结合使用,然后[i+1] = ""删除一个字符。然后使用''.join(list(some_string))将新字符串合并在一起

但这样做会产生令人失望的结果:

A____________BCDEFGHIJKLMNOPQRSTUVWXYZ

Tags: ofthefromimportstringrangevalsome