Question

In this lab you will convert lab5.py to use object oriented programming techniques. The createList and checkList functions in lab5.py become methods of the MagicList class, and the main function of lab6.py calls methods of the MagicList class to let the user play the guessing game.

                            

A. (4pts) Use IDLE to create a lab6.py. Change the 2 comment lines at the top of lab6.py file:

  • First line: your full name
  • Second line: a short description of what the program does

B. (243 pts total) Write a Python program that plays a guess-the-number game with magic lists.

The program will play as many games as the user wants. In each game, the program asks the user to think of a number between 1 and 31, inclusive. Then the program presents the user with 5 lists of numbers and asks the user if their number is in the list. Based on the user's answers of 'y' or 'n', the program guesses the user's number.

  • The program works with 5 files, each file contains 16 integers, one number per line.

The filenames are: magicList1.txt, magicList2.txt, magicList3.txt, magicList4.txt, and magicList5.txt
This is the same as lab5.py.

  • The program is divided into a NumberGuesser class and a main function. (3pts)
    It might be helpful to open lab5.py since you'll be using some of the same code in lab5.py for lab6.py.

  • The NumberGuesser class

         Create a class named NumberGuesser. (5pts)
       The class has 3 methods: (5pts)

  • Convert lab5's createList function into the constructor of the NumberGuesser class. (15pts)
    The constructor does the following tasks:
    • Loop 5 times to:      (5pts)
      • Open one magcListN.txt file each time through the loop.    (10pts)
      • Read the 16 numbers from the file into a list. This is the same as in lab5.py.   (15pts)
      • Store the list into an instance attribute named magicLists, which is also a list.   (15pts)

By the time the constructor is finished, there should be a magicLists instance attribute which contains 5 magic lists.

  • Write a new printAList method that does the following tasks: (5pts)
    • Receive a magic list as input argument   (10pts)
    • Have a nested loop to print the numbers in the list as 4 rows by 4 columns. This is the same as in lab5.py.     (15pts)

  • Convert the lab5's checkList function into a checkList method. (5 pts)

The method does the following tasks:

  • Loop 5 times to:     (5pts)
    • Call the printAList method to print one magic list at a time    (10pts)
    • Loop to keep asking the user whether their number is in the list, until you get a 'y' or 'n' answer        (15pts)
    • If the answer is 'y', add the value corresponding to the current magic list to the total. (30pts)
      You'll need to figure out how to tell the computer what the corresponding value is.
      Example: 16 is the corresponding value for magic list 1, 8 is the corresponding value for magic list 2, etc.
      5 pts extra credit: if you can figure out how to add the corresponding value without using an if statement.
    • The checkList method returns the total.    (5pts)

  • The main function
           Write the main function, which is not part of the NumberGuesser class. (5 pts)
           The main function will:
  • Create an instance (an object) of the NumberGuesser class.    (15pts)
  • Loop as long as the user wants to play. You decide how the user indicates that they want to play again, such as answer 'y' or 'n', or any 2 choices that make sense.(15pts).
    Inside the loop:
    • Call the checkList method to get the total.    (15 pts)
    • If the total is non-zero, then print the user's number
      If the total is 0, then print an error message       (10pts)
  • Don't forget to call the main function so that the program will run.       (10pts)

C. (10 pts) Test your output by running several games, one after another.
The sample output will be the same as with lab5.py

Text files:

magicList1.txt

16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

magicList2.txt

8
9
10
11
12
13
14
15
24
25
26
27
28
29
30
31

magicList3.txt

4
5
6
7
12
13
14
15
20
21
22
23
28
29
30
31

magicList4.txt

2
3
6
7
10
11
14
15
18
19
22
23
26
27
30
31

magicList5.txt

1
3
5
7
9
11
13
15
17
19
21
23
25
27
29
31

lab5.py

def createList(n):

    filename = 'magicList'+str(n)+'.txt'
   
magic_numbers=[]
    with open(filename,'r') as infile:
        for number in infile.readlines():
            if number.strip() is not '':
                magic_numbers.append(int(number.strip()))
    return magic_numbers

def is_number_exist(magic_list):

    for i in range(len(magic_list)):
        print('{0:>3}'.format(magic_list[i]),end='')
        if (i+1)%4==0:
            print()

    present=input('Is your number in the list above? y/n: ')
    return present


def main():

    while True:
        secret_number=0
        for i in range(5):
            magic_numbers = createList(i+1)
            present=is_number_exist(magic_numbers)
            if present=='y' or present=='Y':
                secret_number+=2**i
        print('Your number is {}'.format(secret_number))
      play_again=input('Do you want to play again y/n: ')
        if play_again=='n' or play_again=='N':break
   
print('Thanks. Good Bye!')

main()

Sample Output:

16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Is your number in the list above? y/n: n 8 9 10 11 12 13 14 15 24 25 26 27 28

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Note: Please save the 5 input text files and source code python file in the same folder. Otherwise it raises errors.

Program Screenshots:

#Name: XXXXXX #Number Guessing game beween computer to #person. #create class NumberGuesser class NumberGuesser(): def init__

#define the main method def main(): #create object for the class game=NumberGuesser() #repeat the loop while True: #call the

Sample Input text files:

magicList1 - Notepad File Edit Format View Help 16 17 20 magicList2 - Notepad File Edit Format View Help magicList3 - Notepad

Sample Output:

16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Is your number in the list above? y/n: n 8 9 10 11 12 13 14 15 24 25 26 27 28

Do you want to play again y/n: y 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Is your number in the list above? y/n: y 8 9

Code to be Copied:

#Name: XXXXXX
#Number Guessing game beween computer to
#person.
#create class NumberGuesser
class NumberGuesser():
    def __init__(self):
        #create list
        self.magicLists=[]
        #use for loop to to repeat 5times
        for i in range(5):
            #get the filename
            filename = 'magicList'+str((i+1))+'.txt'
            #create list
            magic_numbers=[]
            #open the file
            with open(filename,'r') as infile:
                #get the numbers from the file
                #and append into list
                for number in infile.readlines():
                    if number.strip() is not '':
                        magic_numbers.append(int(number.strip()))
            self.magicLists.append(magic_numbers)
    #implement printAList
    def printAList(self,magic_list):
        #use for-loop to get the list
        for i in range(len(magic_list)):
            #print the list in the console
            #in a format
            print('{0:>3}'.format(magic_list[i]),end='')
            if (i+1)%4==0:
                print()
    #implement checkList method
    def checkList(self):
        #intialize the number
        secret_number=0
        #declare and initialize number
        multiply=4
        #use for-loop
        #to compute secret number
        for i in range(5):
            self.printAList(self.magicLists[i])
            #repeat the prompting
            present=input('Is your number in the list above? y/n: ')
            if present=='y' or present=='Y':
                secret_number+=2**multiply
            multiply-=1
        #return the number
        return secret_number

#define the main method
def main():
    #create object for the class
    game=NumberGuesser()
    #repeat the loop
    while True:
        #call the method through the object
        total=game.checkList()
        #if the total value is 0
        if(total==0):
            #print the message
            print("Error! You guesed the number wrong.")
        #Otherwise print the guessing number
        else:
            #print the number
            print('Your number is {}'.format(total))
            #again prompt for the number
            play_again=input('Do you want to play again y/n: ')
            #if the user input is n or N
            if play_again=='n' or play_again=='N':
                #break
                break
    #print the message
    print('Thanks. Good Bye!')
#call the main method
main()

Add a comment
Know the answer?
Add Answer to:
In this lab you will convert lab5.py to use object oriented programming techniques. The createList and...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Create a new Python program in IDLE, and save it as lab8.py.(Again, I recommend saving lab...

    Create a new Python program in IDLE, and save it as lab8.py.(Again, I recommend saving lab progranms Your Python program will do the following: Create an empty list . Use a for loop to ask the user for 10 numbers. Add each number to your list using the append metha . Use another for loop to print the list in reverse order, one per line . Use a while loop to count how many positive numbers are in the list...

  • LAB5 #1. Method and loop Write a method integerPower(base, exponent) that returns the value of baseexponent...

    LAB5 #1. Method and loop Write a method integerPower(base, exponent) that returns the value of baseexponent (2 pts). For example, integerPower(3, 4) returns 81. Assume thatexponent is a positive nonzero integer, and base is an integer. Method integer should use for or while loop to control the calculation. Do not use any Math library methods. Incorporate this method into a program class and invoke this method with different combinations of input values at least 4 times. Please use printf() method...

  • PYTHON 3 Object Oriented Programming ***a9q3.py file below*** class GradeItem(object): # A Grade Item is anything...

    PYTHON 3 Object Oriented Programming ***a9q3.py file below*** class GradeItem(object): # A Grade Item is anything a course uses in a grading scheme, # like a test or an assignment. It has a score, which is assessed by # an instructor, and a maximum value, set by the instructor, and a weight, # which defines how much the item counts towards a final grade. def __init__(self, weight, scored=None, out_of=None): """ Purpose: Initialize the GradeItem object. Preconditions: :param weight: the weight...

  • C++ Lab 11 – Is This Box a Magic Box? Objectives: Define a two dimensional array Understand h...

    C++ Lab 11 – Is This Box a Magic Box? Objectives: Define a two dimensional array Understand how to traverse a two dimensional array Code and run a program that processes a two dimensional array Instructions: A magic square is a matrix (two dimensional arrays) in which the sum of each row, sum of each column, sum of the main diagonal, and sum of the reverse diagonal are all the same value. You are to code a program to determine...

  • Your mission in this programming assignment is to create a Python program that will take an...

    Your mission in this programming assignment is to create a Python program that will take an input file, determine if the contents of the file contain email addresses and/or phone numbers, create an output file with any found email addresses and phone numbers, and then create an archive with the output file as its contents.   Tasks Your program is to accomplish the following: ‐ Welcome the user to the program ‐ Prompt for and get an input filename, a .txt...

  • C# Goals: Practice building a class Use object oriented programming to solve a problem Problem Description:...

    C# Goals: Practice building a class Use object oriented programming to solve a problem Problem Description: Create a Windows Console Application using the .NET Framework For this application you will be designing a program that allows users to keep track of robot inventory. First, you will design a Robot class, and then build an application that creates Robot objects. Important formulas / relationships: Before we begin designing robots, we should understand a few key electrical terms and relationships. Terms: Voltage...

  • A Prime Number is an integer which is greater than one, and whose only factors are...

    A Prime Number is an integer which is greater than one, and whose only factors are 1 and itself. Numbers that have more than two factors are composite numbers. The first few prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23 and 29. The number 1 is not a prime number. Write a well-documented, Python program - the main program, that accepts both a lower and upper integer from user entries. Construct a function, isPrime(n), that takes...

  • JAVA PROGRAMMING PLEASE This lab has three parts: Create an ArrayList class. Create a LinkedList class....

    JAVA PROGRAMMING PLEASE This lab has three parts: Create an ArrayList class. Create a LinkedList class. Print out the results after testing each of the methods in both of the classes and solving a simple problem with them. Task 1 – ArrayList Class Create an ArrayList class. This is a class that uses an internal array, but manipulates the array so that the array can be dynamically changed. This class should contain a default and overloaded constructor, where the default...

  • Propose: In this lab, you will complete a Python program with one partner. This lab will...

    Propose: In this lab, you will complete a Python program with one partner. This lab will help you with the practice modularizing a Python program. Instructions (Ask for guidance if necessary): To speed up the process, follow these steps. Download the ###_###lastnamelab4.py onto your desktop (use your class codes for ### and your last name) Launch Pyscripter and open the .py file from within Pyscripter. The code is already included in a form without any functions. Look it over carefully....

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT