Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8618775
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T06:11:20+00:00 2026-06-12T06:11:20+00:00

I am a beginning programmer. I’ve been writing codes on a mastermind solver in

  • 0

I am a beginning programmer.

I’ve been writing codes on a mastermind solver in the six-guess algorithm for an assignment.

(More info on mastermind and its algorithms:Mastermind on wiki)

And I figured it out days ago. But our prof set the fixed template, and then I don’t know how to convert my codes into it.

Below is my code. May be awkward but it works and it’s not that slow.


def product(*args, repeat=1):
    pools = [list(pool) for pool in args] * repeat
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield list(prod)

def sort_list(total_list):
    d0=list()
    d1=list()
    d2=list()
    d3=list()
    d4=list()

    for x in total_list:
        mlist=list()
        alist = x
        n = 0
        while n<4:
            m = alist.count(alist[n])
            mlist.append(m)
            n = n + 1
        if max(mlist)==1:
            d0.append(alist)
        elif max(mlist)==2 and mlist.count(2)==2:
            d1.append(alist)
        elif max(mlist)==2 and mlist.count(2)>2:
            d2.append(alist)
        elif max(mlist)==3 :
            d3.append(alist)
        elif max(mlist)==4 :
            d4.append(alist)

    total_list = d0+d1+d2+d3+d4
    possible = [''.join(p) for p in total_list]
    return total_list

def computeFeedback(code,guess):    
    b = 0
    w = 0
    inCodeCount = {'A':0,'B':0,'C':0,'D':0, 'E':0, 'F':0}
    inGuessCount = {'A':0,'B':0,'C':0,'D':0, 'E':0, 'F':0}
    for i in range(0,4):
        if code[i] == guess[i]:
            b += 1
        inCodeCount[code[i]]+=1
        inGuessCount[guess[i]]+=1
    for ch in inCodeCount:
        w+=min(inCodeCount [ch], inGuessCount [ch])
    w-=b 
    feedback = str(w)+'w'+str(b)+'b'
    return feedback

guesscount=0
code=input()
while guesscount<8:
    guesscount += 1
    if guesscount==1:
        guess='ABCD'
        print("My guess is:",guess)
        feedback=computeFeedback(code,guess)
        if feedback!='0w4b':
            combinations=sort_list([''.join(x) for x in product('ABCDEF',repeat=4)])
            overlap=list()
            for x in combinations:
                fb=computeFeedback(guess,x)
                overlap.append(x)
                if fb != feedback:
                    overlap.pop()
            common=overlap
            overlap=list()

        else:
            print("Game Over in", guesscount,"steps")
            break
    if guesscount==2:
        guess='BCDE'
        print("My guess is:",guess)
        feedback=computeFeedback(code,guess)
        if feedback!='0w4b':
            combinations=sort_list([''.join(x) for x in product('ABCDEF',repeat=4)])
            overlap=list()
            for x in combinations:
                fb=computeFeedback(guess,x)
                overlap.append(x)
                if fb != feedback:
                    overlap.pop()
            common=[token for token in overlap if token in common]
            overlap=list()

        else:
            print('Game Over in,', guesscount,'steps')
            break
    if guesscount==3:
        guess='CDEF'
        print("My guess is:",guess)
        feedback=computeFeedback(code,guess)
        if feedback!='0w4b':
            combinations=sort_list([''.join(x) for x in product('ABCDEF',repeat=4)])
            overlap=list()
            for x in combinations:
                fb=computeFeedback(guess,x)
                overlap.append(x)
                if fb != feedback:
                    overlap.pop()
            common=[token for token in overlap if token in common]

            overlap=list()
        else:
            print('Game Over in', guesscount,'steps')
            break
    if guesscount==4:
        if common[0]=="acfb".upper():
            guess="dcad".upper()
        if common[0]=="aebf".upper():
            guess="edfd".upper()
        if common[0]=='AEFB':
            guess='EACC'
        if common[0]=='AFBE':
            guess='BFCD'
        if common[0]=='BAFE':
            guess='EADC'
        if common[0]=='BEAF':
            guess='EDAE'
        if common[0]=='BEFA':
            guess='EEDA'
        if common[0]=='EABF':
            guess='FDFB'
        if common[0]=='AADB':
            guess='BABD'
        if common[0]=='ABAE':
            guess='BBCC'
        if common[0]=='AEAF':
            guess='CFFD'
        if common[0]=='CAFA':
            guess='FDFA'
        if common[0]=='AAEE':
            guess='DDDF'
        else:
            guess=common[0]
        print("My guess is:",guess)
        if len(common)>1:
            common.pop(0)

            feedback=computeFeedback(code,guess)
            if feedback!='0w4b':
                combinations=sort_list([''.join(x) for x in product('ABCDEF',repeat=4)])
                overlap=list()
                for x in combinations:
                    fb=computeFeedback(guess,x)
                    overlap.append(x)
                    if fb != feedback:
                        overlap.pop()
                common=[token for token in overlap if token in common]
                overlap=list()
            else:
                print('Game Over in', guesscount,'steps')
                break
        else:
            print('Game Over in', guesscount,'steps') 
            break
    if guesscount==5:
        guess=common[0]
        print("My guess is:",guess)
        if len(common)>1:
            common.pop(0)

            feedback=computeFeedback(code,guess)
            if feedback!='0w4b':
                combinations=sort_list([''.join(x) for x in product('ABCDEF',repeat=4)])
                overlap=list()
                for x in combinations:
                    fb=computeFeedback(guess,x)
                    overlap.append(x)
                    if fb != feedback:
                        overlap.pop()
                common=[token for token in overlap if token in common]

                overlap=list()
            else:
                print('Game Over in', guesscount,'steps')
                break
        else:
            print('Game Over in', guesscount,'steps')
            break
    if guesscount==6:
            guess=common[0]
            print("My guess is:",guess)
            if len(common)>1:
                common.pop(0)

                feedback=computeFeedback(code,guess)
                if feedback!='0w4b':
                    combinations=sort_list([''.join(x) for x in product('ABCDEF',repeat=4)])
                    overlap=list()
                    for x in combinations:
                        fb=computeFeedback(guess,x)
                        overlap.append(x)
                        if fb != feedback:
                            overlap.pop()
                    common=[token for token in overlap if token in common]

                    overlap=list()
                else:
                    print('Game Over in', guesscount,'steps')
                    break
            else:
                print('Game Over in', guesscount,'steps')
                break
    if guesscount==7:
            guess=common[0]
            print("My guess is:",guess)
            if len(common)>1:
                common.pop(0)
                feedback=computeFeedback(code,guess)
                if feedback!='0w4b':
                    combinations=sort_list([''.join(x) for x in product('ABCDEF',repeat=4)])
                    overlap=list()
                    for x in combinations:
                        fb=computeFeedback(guess,x)
                        overlap.append(x)
                        if fb != feedback:
                            overlap.pop()
                    common=[token for token in overlap if token in common]

                    overlap=list()
                else:
                    print('Game Over in', guesscount,'steps')
                    break
            else:
                print('Game Over in', guesscount,'steps')
                break
if guesscount==8:
    print('Failure')

Yeah, and here comes the template for both the code-breaker function I have to complete and a mastermind engine to run the function:


Template

class CodeBreaker:
    def __init__(self):



    def makeGuess(self):

        return guess

    def getFeedback(self, feedbackStr):

Engine

from mastermind import CodeBreaker

def computeFeedback(code,guess):
    # Given a code and guess computes the feedback string

    b = 0
    w = 0
    inCodeCount = {'A':0,'B':0,'C':0,'D':0, 'E':0, 'F':0}
    inGuessCount = {'A':0,'B':0,'C':0,'D':0, 'E':0, 'F':0}
    for i in range(0,4):
        if code[i] == guess [i]:
            b += 1
        inCodeCount[code[i]] += 1
        inGuessCount[guess[i]] += 1
    for ch in inCodeCount:
        w += min(inCodeCount [ch], inGuessCount [ch])
    w -= b 
    feedback = str(w)+'w'+str(b)+'b'
    return feedback

code = input()

while (code != None):
    guesscount = 0
    myBreaker = CodeBreaker()
    while (guesscount < 8):
        guess = myBreaker.makeGuess()
        print("My guess is:",guess)
        guesscount += 1
        feedback = computeFeedback(code, guess)
        print(feedback)
        if feedback == "0w4b":
            print("Game Over in", guesscount,"steps")
            break
        myBreaker.getFeedback(feedback)
    if guesscount == 8:
        print("Failed to find the solution in 8 steps")
    code = input()

I’m bad at Classes. I’ve even no idea on what’s the init should contain. Anyone could help?

Thanks so much!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T06:11:21+00:00Added an answer on June 12, 2026 at 6:11 am

    The simplest way to convert your code into a class is to put all your code into the getFeedback method, except that instead of computing a guess which you send off to be evaluated, remember the guess in the property self.guess, and return that next time the makeGuess function is called. You’ll also want to turn all your global variables (like common) into properties (like self.common). Here’s a sketch:

    class CodeBreaker:
        def __init__(self):
            self.guess_count = 0
            self.guess = 'ABCD'
            self.common = []
    
        def makeGuess(self):
            return self.guess
    
        def getFeedback(self, feedback):
            self.guess_count += 1
            if self.guess_count == 1:
                # ... your code here ...
                self.guess = 'BCDE'
            elif self.guess_count == 2:
                # ... your code here ...
                self.guess = 'CDEF'
            elif self.guess_count == 3:
                # ... your code here ...
            # ... and so on ...
    

    I should add that your code is very repetitive. The following changes would be worthwhile:

    1. The Python standard library already contains a function itertools.product that does the job of your function product (though it takes its arguments in a different way), so you might as well use that instead.

    2. You copy out essentially the same code for each guess (generating the set of combinations, evaluating the combinations against the most recent guess, updating common and so on). It should be straightforward to put this code into a method so that you don’t have to copy it out so many times.

    3. The code for guesses number 4 and higher is almost identical: surely there’s no need to copy out this code at all (just write if guesscount >= 4: and handle them all at the same time).

    You might want to study this class (which uses a similar method to your solution, but with all the repetition cut out) and see if you can figure out how it works:

    from itertools import product
    from random import choice
    from copy import copy
    
    class CodeBreaker(object):
        all_codes = [''.join(c) for c in product(*['ABCDEF'] * 4)]
    
        def __init__(self):
            self.codes = copy(self.all_codes)
            self.guess = 'AABB'     # Best first guess!
    
        def makeGuess(self):
            return self.guess
    
        def getFeedback(self, feedback):
            self.codes = [c for c in self.codes if computeFeedback(c, self.guess) == feedback]
            self.guess = choice(self.codes)
    

    This algorithm can take up to eight guesses in the worst case, but you have eight guesses available, so that’s OK. If you had only six guesses available, then you’d need a cleverer approach. The following alternative algorithm makes the best guess based on one move of lookahead, and needs at most six guesses. (It runs very slowly, however!) Again, you might find it interesting to study how it works (hint: it takes the minimum of a list of maxima).

        def getFeedback(self, feedback):
            self.codes = [c for c in self.codes if computeFeedback(c, self.guess) == feedback]
            def key(g): return max(Counter(computeFeedback(c, g) for c in self.codes).values())
            self.guess = min(self.codes, key = key)
    

    And here’s Knuth’s five-guess algorithm (which runs even slower):

        def getFeedback(self, feedback):
            self.codes = [c for c in self.codes if computeFeedback(c, self.guess) == feedback]
            if len(self.codes) == 1:
                self.guess = self.codes[0]
            else:
                def key(g): return max(Counter(computeFeedback(c, g) for c in self.codes).values())
                self.guess = min(self.all_codes, key = key)
    

    P.S. Your professor’s code isn’t perfect, either! Apart from not following conventional Python style (see PEP8), it also seems rather complex and long-winded. Why not take advantage of Python’s collections.Counter class to write something short and simple:

    from collections import Counter
    
    def computeFeedback(code, guess):
        """
        Return the string `{white}w{black}b` where `black` is a count of the
        characters in `guess` that appear at the same position in `code`
        and `white` is a count of the characters in `guess` that appear at
        a different position in `code`.
    
        >>> computeFeedback('ABCD', 'ACAD')
        '1w2b'
        >>> computeFeedback('ABAB', 'AABB')
        '2w2b'
        >>> computeFeedback('ABCD', 'DCBA')
        '4w0b'
        """
        w = sum((Counter(code) & Counter(guess)).values())
        b = sum(c == g for c, g in zip(code, guess))
        return '{}w{}b'.format(w - b, b)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm a beginning programmer studying computer science and I've been told many times that
As a beginning iPhone programmer, what is the best practice for writing apps to
I'm a beginning programmer and I've been having quite a bit of trouble with
So I am a beginning Perl programmer. I have been using it for about
I'm a beginning programmer in Ruby on Rails 3. I currently want to implement
I'm a beginning programmer and the I&CS program at our school starts us off
On paper, binary arithmetic is simple, but as a beginning programmer, I'm finding it
I am a beginning javascript programmer. I am trying to create something similar to
I am a beginning C programmer (though not a beginning programmer) looking to dive
So, Im a beginning C# programmer. I know basic syntax and simple things like

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.