统计由10个字母“abcdefghij”中的任意3个字母生成字母序列的总数,要求满足首字母不含“a”,尾字母不含“j”,并且没有重复字母(例如abc, bba,bbb, baj 不在统计范围内)。然后把满足要求的字母序列保存在名称为“zimu.txt”的文档中,分隔符为英文状态下的逗号。
递归实现
result = [] def listzh(a1, mylist): # 递归解法 if 2 == len(mylist): r = a1+mylist[0]+mylist[1] r1 = a1 + mylist[1] + mylist[0] result.append(r) result.append(r1) else: for i, j in enumerate(mylist): c = mylist[:] c.pop(i) listzh(a1+j, c) def filterList(n): return n[0] != 'a' and n[-1]!='f' if __name__ == '__main__': strs = 'abcdefghij' mylist = list(set(list(strs))) listzh('', mylist) str = filter(filterList, result) f = open('zimu.txt', 'w+') f.write(','.join(list(str))) f.close()
def do():
l = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
count = len(l)
f = open('fuck.txt', 'w+')
for i in range(1, count):
for j in range(count):
if i != j:
for k in range(count - 1):
if j != k and i != k:
str = l[i] + l[j] + l[k]
f.write(str)
f.write(',\n')
f.close()
if __name__ == "__main__":
do()
#在不优化算法的情况下,跟着题意走就好了
#给十个字母
words = 'abcdefghij'
#每个组合
lis = [] #用于存放
for frist_word_index in range(len(words)):
for second_word_index in range(len(words)):
#如果12是同一个回去
if frist_word_index == second_word_index:
continue
for third_word_index in range(len(words)):
# 如果13或者23是同一个回去
if frist_word_index==third_word_index or third_word_index==second_word_index:
continue
#最后3个字母组成同一个加进列表
word = words[frist_word_index]+words[second_word_index]+words[third_word_index]
lis.append(word)
#去重
words_set =set(lis)
#写入文件
with open('zimu.txt','w',encoding='utf8') as fw:
for word in words_set:
#不要A开头,不要J结尾
if word.startswith('a') or word.endswith('j'):
continue
#字母写入,隔开
fw.write(f'{word},')