20190129-‘abcdefgh’里面挑出3个字母进行组合,一共有多少组合

时间:2023-01-29 01:47:30

一. 百度面试题‘abcdefgh’里面挑出3个字母进行组合,一共有多少组合,要求3个字母中不能有重复的组合,三个字母同时出现的次数只能出现一次,如出现了abc就不能出现cab,bca等

思路:

1. abcdefgh里面挑选3个字母进行组合,考虑使用3层for循环,然后使用if条件过滤不符合要求的组合

2. 3个字母中不能有重复的组合,考虑使用i!=j,i!=k,k!=i

3. 三个字母同时出现的次数只能出现一次,首先使用result来存储符合条件的组合,通过遍历result里面的item,使用条件if i in item and j in item and k in item,如果符合条件break,退出该层循环,如果遍历完result后都没有符合条件的,则表明符合组合要求,count+1,并将组合插入result中


e = 'abcdefghi'

for i in e:

#第一个字符
for j in e:
#第二个字符
for k in e:
#第三个字符
if i!=j and j!=k and k!=i:
for item in result:
if i in item and j in item and k in item:
break
else:
#与for item in result对应,当for主体中没有执行break语句的时候,else语句执行
item= i+j+k
result.append(item)
count+=1
print("共计%s个"%count)
print('分别为:',result)

三个字母同时出现的次数只能出现一次,可以考虑使用sort来实现,如sorted(item) not in list(map(lambda x:sorted(x),for x in result_two))来实现,具体写法如下:

e = 'abcdefghi'
#方法2:
#三个字母同时出现的次数只能出现一次,可以考虑使用sort来实现,如sorted(item) not in list(map(lambda x:sorted(x),for x in result_two))来实现,具体写法
count_two=0
result_two=[]
for i in e:
#第一个字符
for j in e:
#第二个字符
for k in e:
#第三个字符
item = i+j+k
if item.count(i)>1 or item.count(j)>1 or item.count(k)>1:
continue
if sorted(list(item)) not in list(map(lambda x:sorted(x),result_two)):
result_two.append(item)
count_two+=1
print("共计%s个"%count_two)
print('分别为:',result_two)

以上两种方法皆可实现题目的需求,核心考虑点为三个字母同时出现的次数只能出现一次,如出现了abc,就不能再出现cab,cba,bca等等

第三种方法,使用python内置函数itertools,写法如下:

import itertools
count_three= 0
result_three=[]
for i in itertools.combinations(e,3):
count_three+=1
result_three.append(''.join(i))
print("共计%s个"%count_three)
print('分别为:',result_three)