假设我有一个单词“ apple”,一组字母['a','l','e']和重复次数3。 由此,我想创建以下集合: ['aaapple','aaappllle','aaappllleee','appllle','appllleee','appleee']。
这是我已经尝试过的:
l = ['a', 'l', 'e']
word = "apple"
for i in range(0, len(l)):
print wordWithDuplicatedLetters = "".join(3*c if c == l[i] else c for c in word)
但这与所有组合都不匹配,itertools似乎没有提供我正在寻找的可能性。
答案 0 :(得分:3)
我不认为您的示例输出具有所有可能的组合,下面的我认为具有所有可能的组合。这里的技巧是遍历下面函数 "Hello World!"
所具有的任何大小的所有组合。
all_combinations
输出
import itertools
repeat = ['a', 'l', 'e']
word = 'apple'
def all_combinations(itr):
lst = list(itr)
for r in range(1, len(lst) + 1): # set start to 0 if want to include []
for perm in itertools.combinations(lst, r=r):
yield perm # or use yield from in py3
def all_repeats():
for rep in all_combinations(repeat):
yield ''.join(char * 3 if char in rep else char for char in word)
print(list(all_repeats()))
答案 1 :(得分:2)
尝试使用此循环:
s = ''
for i in word:
if i in l:
s += (3 * i)
else:
s += i
可以是列表理解:
s = ''.join([3 * i if i in l else i for i in word])
现在两种情况下:
print(s)
是:
aaappllleee
完全回答您的问题
您将必须使用:
import itertools
l = ['a', 'l', 'e']
word = 'apple'
l2 = []
for i in range(len(l)):
for x in itertools.combinations(l, r=i+1):
l2.append(x)
l3 = []
for lst in l2:
l3.append(''.join(char * 3 if char in lst else char for char in word))
print(l3)
输出:
['aaapple', 'appllle', 'appleee', 'aaappllle', 'aaappleee', 'appllleee', 'aaappllleee']
答案 2 :(得分:2)
您可以将此问题分为两个步骤。首先,找出所有可能重复的位置子集。从本质上讲,这是一个幂集taken from here,其中除去了空白的情况。基于索引构建它可以使该解决方案对于包含重复字母以进行重复的单词具有鲁棒性。
第二,针对Powerset中的每种情况,构建一个有效的字符串并显示它。
from itertools import chain, combinations
def powerset_non_empty(iterable):
"""
powerset with empty set skipped
powerset([1,2,3]) --> (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)
"""
xs = list(iterable)
# note we return a list, but could choose to return an iterator too
return list(chain.from_iterable(combinations(xs,n) for n in range(1, len(xs)+1)))
l = ['a', 'l', 'e']
word = "apple"
indices = [i for i,c in enumerate(word) if c in l]
number_of_repetition = 3
powerset = powerset_non_empty(indices)
result = []
for index_tuple in powerset:
s = ''
for i, c in enumerate(word):
if i in index_tuple:
s += (number_of_repetition * c)
else:
s += c
print(s)
result.append(s)
#Output:
['aaapple',
'appllle',
'appleee',
'aaappllle',
'aaappleee',
'appllleee',
'aaappllleee']
答案 3 :(得分:1)
您可以使用一个简单的递归生成器函数:
first_rent = first_rent.text
输出:
import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
public class KeyPairToString {
private static final String ALGORITHM = "RSA";
private static byte[] encrypt(byte[] publicKey, byte[] inputData) throws Exception {
PublicKey key = KeyFactory.getInstance(ALGORITHM) /* ExceptionL Invalid DER encoding */
.generatePublic(new X509EncodedKeySpec(publicKey));
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(inputData);
}
private static byte[] decrypt(byte[] privateKey, byte[] inputData) throws Exception {
PrivateKey key = KeyFactory.getInstance(ALGORITHM)
.generatePrivate(new PKCS8EncodedKeySpec(privateKey));
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(inputData);
}
private static KeyPair generateKeyPair()
throws NoSuchAlgorithmException, NoSuchProviderException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
keyGen.initialize(512, random);
return keyGen.generateKeyPair();
}
private static String bytesToString(byte[] bytes) {
return new String(bytes);
}
private static byte[] stringToBytes(String astring) {
return astring.getBytes();
}
private static String bytesToEncodedString(byte[] bytes) {
return Base64.getEncoder().encodeToString(bytes);
}
private static byte[] encodedStringToBytes(String encodedString) {
return Base64.getDecoder().decode(encodedString);
}
public static void main(String[] args) throws Exception {
KeyPair generateKeyPair = generateKeyPair();
byte[] publicKey = generateKeyPair.getPublic().getEncoded();
byte[] privateKey = generateKeyPair.getPrivate().getEncoded();
// Byte array
String secretText = "hi this is secret johan here";
byte[] encryptedData = encrypt(publicKey, secretText.getBytes());
byte[] decryptedData = decrypt(privateKey, encryptedData);
System.out.println(new String(decryptedData));
// Now with Strings
String encodedPublicKeyString = bytesToEncodedString(publicKey);
String encodedPrivateKeyString = bytesToEncodedString(privateKey);
String encryptedDataString = bytesToEncodedString(
encrypt(encodedStringToBytes(encodedPublicKeyString), stringToBytes(secretText)));
String decryptedDataString = bytesToString(
decrypt(
encodedStringToBytes(encodedPrivateKeyString),
encodedStringToBytes(encryptedDataString)));
System.out.println(new String(decryptedDataString));
}
}