Question

0. Introduction. In this laboratory assignment, you will write a Python class called Zillion. The class...

0. Introduction.

In this laboratory assignment, you will write a Python class called Zillion. The class Zillion implements a decimal counter that allows numbers with an effectively infinite number of digits. Of course the number of digits isn’t really infinite, since it is bounded by the amount of memory in your computer, but it can be very large.

1. Examples.

Here are some examples of how your class Zillion must work. I’ll first create an instance of Zillion. The string gives the initial value of the counter. Blanks and commas in the string are ignored.

z = Zillion('999 999 999 998')

This instance of Zillion contains the number nine hundred ninety nine billion, nine hundred ninety nine million, nine hundred and ninety nine thousand, nine hundred and ninety eight. This is much larger than the maximum number that can be represented in a Java int variable, which is only 2 147 483 647, or around two billion.
      I’ll add 1 to the counter, by calling the method increment, and I’ll print the counter by calling the method toString. I should see 999999999999 (twelve nines) printed.

z.increment()
print(z.toString())

I’ll add 1 to the counter again, and print its digits as before. I should see 1000000000000 (one with twelve zeroes) printed.

z.increment()
print(z.toString())

Finally, I’ll test if the counter contains zero by calling the method isZero. Of course z.isZero() will return False. But Zillion('0').isZero() will return True.

2. Theory.

Your class Zillion must represent a number internally as a list of one or more digits. Each digit d in the list is an integer 0 ≤ d ≤ 9. For example, the number 1234 must be represented as the list [1, 2, 3, 4]. Although Python provides long integers that can have arbitrarily many digits, the class Zillion must not use these long integers. You will receive zero points for this assignment if you use Python’s long integers in any way!
      The method increment must work like this. Starting at the right end of the list, and moving toward the left end, it must change 9’s into 0’s, until it finds a digit that is not 9, or until there are no more digits left to be visited. If it stops because it has found a digit that is not 9, then it must add 1 to that digit. If it stops because there are no more digits left, then it must add 1 to the front of the list. For example, if the list is [1, 2, 9], then increment will first change the 9 at the end of the list to a 0, then add 1 to the digit 2, resulting in [1, 3, 0]. Similarly, if the list is [9, 9], then increment will change both 9’s to 0’s, then add 1 to the front of the list, resulting in [1, 0, 0].
      Hint: unlike the previous lab, you are using lists, which are mutable objects whose elements can be changed. In fact, you must change list elements, or your program will not work correctly.

3. Implementation.

The class Zillion must define the following methods. To simplify grading, your methods must use the same names as the ones shown here. However, they need not use the same parameter names, except for self, which must be unchanged. To demonstrate your understanding of Python, some methods must be implemented in specific ways, as described below.

__init__(self, digits)

The string digits must be a string containing nothing but digits (0 through 9), blanks, and commas. It must contain at least one digit. If digits contains no digits, or if it contains a character that is not a digit, a blank, or a comma, then raise a RuntimeError exception. Convert digits to a list of integer digits as described in section 2, and save it within the instance of Zillion. The list represents the number that is stored in the counter.
      Hints: it is not enough to test if digits is the empty string. For example, a string consisting of nothing but blanks and commas, like ' , ,,' must raise an exception. Also, you may wish to call the built-in function int, which converts a string to an integer. For example, int('0') returns the integer 0.

increment(self)

Increment the counter, using the algorithm described in part 2. Hint: one way to do this is by using a while loop, and another way is to use recursion. There may be still other ways.

isZero(self)

Test if the counter contains zero. That is, test if your list of digits contains nothing but 0’s.

toString(self)

Convert the list of digits to a string, and return the string. Hint: you may wish to call the built-in function str, which converts an integer to a string. For example, str(0) returns the string '0'.

4. Tests.

The file tests2.py on Moodle contains a series of tests. The tests create instances of the class Zillion, call their methods, and print what they return. Some of the tests raise exceptions instead of printing values. They show whether Zillion’s methods raise exceptions correctly.
      To grade your work, the TA’s will run the tests using your functions. If a test behaves exactly as it should, then you will receive all the points for that test. If a test does anything else, then you will receive no points for that test. Your score for this assignment is the sum of the points you receive for all the tests.

# Every test is followed by a comment which shows what must be printed if your

# code works correctly. It also shows how many points the test is worth.

#

try:

z = Zillion('')

except RuntimeError:

print('Empty string')

# It must print 'Empty string' without apostrophes. 2 points.

try:

z = Zillion(' , ')

except RuntimeError:

print('No digits in the string')

# It must print 'No digits in the string' without apostrophes. 2 points.

try:

z = Zillion('1+0')

except RuntimeError:

print('Non-digit in the string')

# It must print 'Non-digit in the string' without apostrophes. 2 points.

try:

z = Zillion('0')

except RuntimeError:

print('This must not be printed')

# It must print nothing. 2 points.

print(z.isZero())    # It must print True. 2 points.

try:

z = Zillion('000000000')

except RuntimeError:

print('This must not be printed')

# It must print nothing. 2 points.

print(z.isZero())    # It must print True. 2 points.

try:

z = Zillion('000 000 000')

except RuntimeError:

print('This must not be printed')

# It must print nothing. 2 points.

print(z.isZero())    # It must print True. 2 points.

try:

z = Zillion('997')

except RuntimeError:

print('This must not be printed')

# It must print nothing. 2 points.

print(z.isZero())    # It must print False. 2 points.

print(z.toString()) # It must print 997. 2 points.

z.increment()

print(z.toString()) # It must print 998. 2 points.

z.increment()

print(z.toString()) # It must print 999. 2 points.

z.increment()

print(z.toString()) # It must print 1000. 2 points.

try:

z = Zillion('0 9,9 9')

except:

print('This must not be printed')

# It must print nothing. 3 points.

z.increment()

print(z.toString()) # It must print 1000. 2 points.

Homework Answers

Answer #1

class Zillion:

        def __init__(self, digits):
                digits = digits.replace(',', '')
                digits = digits.replace(' ', '')

                if not all([d.isdigit() for d in digits]):
                        raise RuntimeError('Invalid digits')
                
                self.digits = [int(d) for d in digits]

        def increment(self):
                
                for i in range(len(self.digits) - 1, -1, -1):
                        self.digits[i] += 1
                        if self.digits[i] == 10:
                                self.digits[i] = 0
                        else:
                                return
                self.digits = [1] + self.digits
        
        def isZero(self):
                return all([x == 0 for x in self.digits])
        
        def toString(self):
                return ''.join(map(str, self.digits))

        def __str__(self):
                return self.toString()
                
x = Zillion('999 999 999 998')
print(x)
x.increment()
print(x)
x.increment()
print(x)
**************************************************

Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.

Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.

Know the answer?
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
Similar Questions
write a code in python Write the following functions below based on their comments. Note Pass...
write a code in python Write the following functions below based on their comments. Note Pass is a key word you can use to have a function the does not do anything. You are only allowed to use what was discussed in the lectures, labs and assignments, and there is no need to import any libraries. #!/usr/bin/python3 #(1 Mark) This function will take in a string of digits and check to see if all the digits in the string are...
This laboratory assignment involves implementing a data structure called a map. A map associates objects called...
This laboratory assignment involves implementing a data structure called a map. A map associates objects called keys with other objects called values. It is implemented as a Java class that uses arrays internally. 1. Theory. A map is a set of key-value pairs. Each key is said to be associated with its corresponding value, so there is at most one pair in the set with a given key. You can perform the following operations on maps. You can test if...
Homework Assignment 5 Instructions: Class name must be: HW5_yourName For example: Michael will name the python...
Homework Assignment 5 Instructions: Class name must be: HW5_yourName For example: Michael will name the python file of homework assignment 5 as HW5_Michael.py Grading Rubric: Code running and as per the required conditions and giving expected output = 10 points File named as per instructions = 1 point Comments in code = 4 points Problem: Average calculation of test scores using a Dictionary Write a program that reads a text file named Asg5_data.txt and stores the name of the student...
Complete this in C++ and explain what is being done. 1      Introduction The functions in the...
Complete this in C++ and explain what is being done. 1      Introduction The functions in the following subsections can all go in one big file called pointerpractice.cpp. 1.1     Basics Write a function, int square 1(int∗ p), that takes a pointer to an int and returns the square of the int that it points to. Write a function, void square 2(int∗ p), that takes a pointer to an int and replaces that int (the one pointed to by p) with its...
import java.io.PrintStream; import java.util.Arrays; public class joker { public static int smallest(int[] v1, int[] v2) {...
import java.io.PrintStream; import java.util.Arrays; public class joker { public static int smallest(int[] v1, int[] v2) { return 0; } public static int[] convert1(String str) { return new int[1]; } public static String convert2(int[] v) { return ""; } public static void main(String[] args) { testSmallest(); testConvert(); } public static void testSmallest() { System.out.println("Testing your method smallest(...)"); int[][] testVectors1 = new int[][]{{1, 2, 3}, {1, 2, 3, 4}, {1, 2, 3}, {1, 2, 3}, {2, 3, 4}}; int[][] testVectors2 = new...
For this part, you will write a PostfixCalculator class that has methods for processing each possible...
For this part, you will write a PostfixCalculator class that has methods for processing each possible input. You will write a Tester class that reads a line of input from the user, with each symbol separated by a space, and prints out the numeric value of the top of the stack. If the user specifies an incomplete expression, print out the top of the stack and print out a message saying that the stack contains more than one item. If...
c++ Program Description You are going to write a computer program/prototype to process mail packages that...
c++ Program Description You are going to write a computer program/prototype to process mail packages that are sent to different cities. For each destination city, a destination object is set up with the name of the city, the count of packages to the city and the total weight of all the packages. The destination object is updated periodically when new packages are collected. You will maintain a list of destination objects and use commands to process data in the list....
ALL CODE MUST BE IN C++ Before you begin, you must write yourself a LinkedList class...
ALL CODE MUST BE IN C++ Before you begin, you must write yourself a LinkedList class and a Node class (please name your classes exactly ​as I did here). Please follow the below specifications for the two classes. Node.cpp ● This must be a generic class. ● Should contain a generic member variable that holds the nodes value. ● Should contain a next and prev Node* as denoted here. ● All member variables should be private. ● Use public and...
Python Blackjack Game Here are some special cases to consider. If the Dealer goes over 21,...
Python Blackjack Game Here are some special cases to consider. If the Dealer goes over 21, all players who are still standing win. But the players that are not standing have already lost. If the Dealer does not go over 21 but stands on say 19 points then all players having points greater than 19 win. All players having points less than 19 lose. All players having points equal to 19 tie. The program should stop asking to hit if...
You can complete this assignment individually or as a group of two people. In this assignment...
You can complete this assignment individually or as a group of two people. In this assignment you will create a ​​Sorted Singly-Linked List​ that performs basic list operations using C++. This linked list should not allow duplicate elements. Elements of the list should be of type ‘ItemType’. ‘ItemType’ class should have a private integer variable with the name ‘value’. Elements in the linked list should be sorted in the ascending order according to this ‘value’ variable. You should create a...