I started learning python and I'm wondering if there's a way to put a limit of values that can fit into a set and how would I tell the user that said set is full? For example 4 players can only be in one team(set).
Asked
Active
Viewed 36 times
0
-
1Does this answer your question? [How to force a list to a fixed size?](https://stackoverflow.com/questions/5944708/how-to-force-a-list-to-a-fixed-size) (I realize you specifically asked about `set()` but `collections.deque()` might help. – JonSG May 05 '21 at 21:45
1 Answers
0
You can either create a new set class that checks for the size before adding.
class fixed_set(set):
def __init__(self,n):
self.max_size = n
def add(self,player):
if len(self)>=self.max_size:
print("Max size reached")
else:
super().add(player)
This class will behave exactly as a normal set except when you try to add more than n
items it will print "Max size reached"
for example:
x = fixed_set(2)
x.add(1)
x.add(2)
x.add(3)
print(x)
will print
Max size reached
fixed_set({1,2})
meaning the new element wasn't added

kinshukdua
- 1,944
- 1
- 5
- 15
-
I'm still confused. I'm relativeley new to python and I don't what do you mean by class. – Paul Atreidis May 07 '21 at 20:07
-
You know how to use sets, right? Just copy paste the first code with `class fixed_set` and instead of `set` use fixed_set everything else should work exactly the same. Except when you try to add more than `n` players it will print a message instead. – kinshukdua May 08 '21 at 11:16