我必须生成字符串的串联:
我的功能具有n
和stuff
,作为输入,它必须生成以下任意序列
这里 N
是要考虑的输入字符串的否。
样本输入:
n = 3,quatp = ['x','y','z']
样本OUPUTS:
xy xz yz
输出的说明:
xy-> 1和2
的组合xz-> 1和3
的组合yz-> 2和3的组合
n的范围不是特定于3。即n< = 1000的范围。
我的代码:
for _ in range(int(input())):
n = int(input())
stuff = []
for i in range(0,n):
stuff.append(input())
for L in stuff[0:]:
for J in stuff[1:-1]:
k = L+J
print(k)
我的输出:
xy 是的 zy
我知道我未能正确地在列表中实现索引。但是我也无法修复此错误。
问题1:谁能帮助我修复列表中的列表?
问题2:时间复杂性是o(n^2)我可以优化o(n)?
也许不是您想要的。但是,为初学者尝试这个:
stuff = []
N = int(input("Enter the size of N: "))
for n in range(N):
s = input("Enter stuff %i : " %(n+1))
stuff.append(str(s))
for ss in range(len(stuff)):
st = stuff[ss]
for x in range(ss+1, len(stuff)):
comb = st + stuff[x]
print (comb)
,也可以使用itertools.combination
:
from itertools import combinations
stuff = []
N = int(input("Enter the size of N: "))
for n in range(N):
s = input("Enter stuff %i : " %(n+1))
stuff.append(str(s))
result = [''.join(i) for i in combinations(stuff, 2)]
print (result)
您可以使用列表综合和itertools.combinations实现这一目标:
from itertools import combinations
res = [''.join(item) for item in combinations(stuff, 2)]
# ['xy', 'xz', 'yz']
2是您所需组合的长度