import random
import os
if os.path.exists("D:\new.txt")==False: #检测文件是否存在
file = open('D:\' + 'new' + '.txt','w') #若不存在则立即创建
file.close()
temp = 1 #控制是否继续
answer = ''.join([str(i) for i in random.sample(range(0, 9), 4)])
for i in range(0, 4) :
a = answer
if any([a[0] == a[1], a[0] == a[2], a[0] == a[3], a[1] == a[2], a[1] == a[3], a[2] == a[3]]):
pass
else:
break
print('答案是:', answer)
a = answer
# 随机生成一个四位数(首位可以是0,每位的数字不相同 )
while temp == 1 :
file = open('D:\new.txt', 'w')
guess = (input('请输入您猜测的数:'))
g = str(guess)
if any([g[0] == g[1], g[0] == g[2], g[0] == g[3], g[1] == g[2], g[1] == g[3], g[2] == g[3]]):
break
else:
g = str(guess)
(i, j) = (0, 0)
for y in range(0, 4):
if a[y] == g[y]:
i += 1
elif any([a[y] == g[0], a[y] == g[1], a[y] == g[2], a[y] == g[3]]):
j += 1
print("%dA%dB" % (i, j))
file.write("'%s'的结果是 '%dA%dB'"%(g, i, j))
string = input("继续请输入yes,退出循环请输入exit:")
file.close()
if string == 'yes':
temp = 1
elif string == 'exit':
temp = 0
continue
os即operating system(操作系统),Python 的 os 模块封装了常见的文件和目录操作。
os.path.exists()就是判断括号里的文件是否存在的意思,括号内的可以是文件路径。
temp判断是否执行
''.join()
概述:
将序列中的元素以指定的字符连接生成一个新的字符串。
语法: ‘delimiter’.join(seq)
delimiter:分隔符。可以为空
delimiter:要连接的元素序列、字符串、元组、字典
返回通过指定字符连接序列中元素后生成的新字符串。
random.sample(population, k)
返回从总体序列或集合(potution)中选择的唯一元素的 k 长度列表(list)。用于随机抽样,无需更换
由于生成的四位数首位可以为零,
因此将答案设为str类型
判断answer是否有相同数,guess同理
将字符串每一位都放入数组a,g
通过for循环,判断AB的数量
将结果保存至new.txt
最后询问是否继续
看了有写了同样题目的,但是发现并没有根据要求实现功能,当然我也没有:)
等我学的更深入了再改吧



