Logo
3

Write a class to represent an NSet. An NSet is a kind of set that allows a maximum of N instances of every value. A traditional set is an NSet where N = 1.

class should support the following operations.

Description Method
Create an NSet. Let N = 1, if N is not provided to the constructor. NSet(N)
Add a value to the NSet add(value)
Remove one occurrence of a given value from the NSet remove(value)
How many occurrences of a value are in the NSet? count(value)
Does the NSet contain a given value? contains(value)
How many values are in the NSet? total()
How many different values are in the NSet? countUnique()
Return a string representation of the NSet __str()__
Set the value of N setN()
x = NSet(3)

for i in range(3):
    x.add("X")
print(1, x)

x.add("X")
print(2, x)

x.add("y")
print(3, x)

x.remove('X')
print(4, x)

print("5 Count of y:", x.count('y'))
print("6 Contains z:", x.contains('z'))

x.add('a')
x.add('a')
x.add('a')
print(7, x)

print("8 Total Count:", x.total())
print("9 Total Unique:", x.countUnique())
x.setN(1)
print(10, x)

Expected Output
1 ['X', 'X', 'X']
2 ['X', 'X', 'X']
3 ['X', 'X', 'X', 'y']
4 ['X', 'X', 'y']
5 Count of y: 1
6 Contains z: False
7 ['X', 'X', 'y', 'a', 'a', 'a']
8 Total Count: 6
9 Total Unique: 3
10 ['X', 'y', 'a']

guideOfSATguideOfSAT asked a year ago

·

Answers

2

Here is the answer:

class NSet:
    def __init__(self, N = 1):
        self.N = N
        self.nSetArray = []
    
    def add(self, value):
        if self.count(value) < self.N:
            self.nSetArray.append(value)
    
    def remove(self, value):
        for idx,val in enumerate(self.nSetArray):
            if val == value:
                self.nSetArray.pop(idx)
                break
    
    def count(self, value):
        totalCount = 0
        for val in self.nSetArray:
            if val == value:
                totalCount += 1
        
        return totalCount
    
    def contains(self, value):
        return value in self.nSetArray
    
    def total(self):
        return len(self.nSetArray)
        
    def countUnique(self):
        return len(set(self.nSetArray))
    
    def setN(self, N):
        self.N = N
        oldArray = self.nSetArray
        self.nSetArray = []
        for str in oldArray:
            self.add(str)
    
    def __str__(self):
        return str(self.nSetArray)
  

x = NSet(3)

for i in range(3):
    x.add("X")
print(1, x)

x.add("X")
print(2, x)

x.add("y")
print(3, x)

x.remove('X')
print(4, x)

print("5 Count of y:", x.count('y'))
print("6 Contains z:", x.contains('z'))

x.add('a')
x.add('a')
x.add('a')
print(7, x)

print("8 Total Count:", x.total())
print("9 Total Unique:", x.countUnique())
x.setN(1)
print(10, x) 

davidmacagodavidmacago answered a year ago

Post your answer

Recommended Books

Reading books is a great way to learn. Here are some of the books we recommend.