本帖最后由 0HB 于 2021-9-3 02:53 编辑
检察 原先错误程序 运行# 建立投票程序,用户输入候选人:
p = ['张三']
m = "请输入候选人: "
m += "请输入'p'结束程序: "
active = True
while active:
mess = input(m)
if mess == 'p':
active = False
else:
p.append(mess)
# 判断是否有两个候选人都超过总数的1/3:
moj_1 = moj_2 = p[0] # 初始化两个候选人变量
count_1 = count_2 = 0 # 初始化两个候选人的票数
# 对抗阶段:
# 遍历候选人列表,每个元素需要分别与当前候选人变量比对,相同则当前候选人票数+1,都不同则弃之,票数-1:
num = 0 # 用来记录循环次数
for each in p:
if moj_1 == each:
count_1 += 1
num += 1
print('第{0}次循环,执行的是: if moj_1 == each:'.format(num))
print('1:{0}{1}票,2:{2}{3}票'.format(moj_1, count_1, moj_2, count_2))
continue
if moj_2 == each:
count_2 += 1
num += 1
print('第{0}次循环,执行的是:if moj_2 == each:'.format(num))
print('1:{0}{1}票,2:{2}{3}票'.format(moj_1, count_1, moj_2, count_2))
continue
if count_1 == 0:
moj_1 = each
count_1 = 1
num += 1
print('第{0}次循环,执行的是:if count_1 == 0:'.format(num))
print('1:{0}{1}票,2:{2}{3}票'.format(moj_1, count_1, moj_2, count_2))
continue
if count_2 == 0:
num += 1
moj_2 == each
count_2 = 1
print('第{0}次循环,执行的是:count_2 == 0'.format(num))
print('1:{0}{1}票,2:{2}{3}票'.format(moj_1, count_1, moj_2, count_2))
continue
count_1 -= 1
count_2 -= 1
num += 1
print('第{0}次循环,执行的是:减票操作'.format(num))
print('1:{0}{1}票,2:{2}{3}票'.format(moj_1, count_1, moj_2, count_2))
# 统计阶段:
# 对抗阶段结束后,如果moj_1,moj_2两个变量都有剩余,则统计各自的票数,否则不存在同时过1/3的两个候选人:
if p.count(moj_1) > len(p) / 3:
print("候选人", moj_1, "的选票超过1/3!")
if p.count(moj_2) > len(p) / 3:
print("候选人", moj_2, "的选票超过1/3!")
"""
注意:第一次循环的对象是p列表中提前写好的张三
"""
结果:(按照「张三、张三、李四、李四、李四、p」依次输入) |