Python Baseball Game

Asked 2 years ago, Updated 2 years ago, 81 views

import random

cum=random.sample(range(1,10),4)

print(cum)

def check_list(listname,input_num):

    listname=[]

    while len(listname)<=input_num-1:
        z=0
        num=int ("Enter a number")
        listname.append(num)
        for k in range(len(listname)-1):
            for j in range(k+1,len(listname)):
                if listname[k]==listname[j]:
                    print("Duplicate value exists". Please re-enter it.")
                    listname=[]

    strike=0
    ball=0

    for n in range(len(cum)):
        for r in range (len(listname)):
            if cum[n]==listname[r]and n==r:
                strike=strike+1
            elif cum[n]==listname[r]:
                ball=ball+1


    print(strike,"-strike",ball,"-ball")
    if strike==4:
        print(z"revised successfully!")
    else:
        z=z+1
        check_list(listname,input_num)




play=[]    

check_list(play,4)

I made a code for a baseball game, but how do I write the number of times? Since I reset it to a recursive function, the count of the number of times is reset to zero, so the number of times cannot be saved. Is there a solution or do I have to rewrite the code?

function

2022-09-22 13:16

1 Answers

No recursion required.

import random

cum = random.sample(range(1, 10), 4)

print(cum)

def check_list(input_num = 4):
    cnt = 1
    while True:
        num = input ("Enter a number")
        #if not num.isnumeric() or len(num) != input_num or len(set(num)) != input_num:
        if (num.isnumeric(), len(num), len(set(num))) != (True, input_num, input_num):
            print('Number only, number {} must be entered, duplicate values are not allowed'.format(input_num)))
            continue    

        solve = [v1 == v2 for v1, v2 in zip(cum, map(int, num))] # True, False to distinguish strikes and balls.

        strike, ball = solve.count(True), solve.count(False)
        print("{}-strike {}-ball".format(strike, ball))

        if strike == input_num:
            print("{}Successful conversion!"format(cnt))
            return
        else: cnt += 1

check_list()


2022-09-22 13:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.