-3

I have a class of objects :

class Object :
def __init__(self,id,x,y):
    self.id = id
    self.x = x
    self.y = y

The id of the object is unique but for x and y they might be similar :

For example let's have 4 objects :

ob1 = Object(0, 2.7, 7.3)
ob2 =  Object(1, 2.7, 7.3)
ob3 = Object(2, 3.2, 4.6)
ob4 = Object(3, 2.7, 7.3)

I would like to keep only objects that have x and y different, for example here I would like to keep only ob1 and ob3 or ob2 and ob3 or ob4 and ob3.
How could I do it?

Thanks

Younès Raoui
  • 33
  • 1
  • 5
  • 1
    compare the objects x, and y and if theyre the same delete one of them – Craicerjack Jul 16 '20 at 13:38
  • 1
    Iterate over the objects, add the `tuple` `(x, y)` to a `set` and check if the length of the set changes, delete as necessary. – Peter Meisrimel Jul 16 '20 at 13:38
  • You can add objects to set to get unique instances. To be able to add object to set you to implement the __hash__(...) and __eq__(...) methods as [discussed here](https://stackoverflow.com/questions/10547343/add-object-into-pythons-set-collection-and-determine-by-objects-attribute) – DarrylG Jul 16 '20 at 13:41

2 Answers2

1

Allow objects to be added to a set using technique from here

To placed objects in set, object class needs to implement:

  1. eq(...)
  2. hash(...)

Code

class Object :
  def __init__(self,id,x,y):
    self.id = id
    self.x = x
    self.y = y

  def __eq__(self, other):
    return self.x == other.x and self.y == other.y

  def __hash__(self):
    return hash((self.x, self.y)) # hash of x, y tuple

  def __str__(self):
    return str(vars(self))       # vars converts attributes to dictionary
                                 # str converts dictionary to string 

Usage

ob1 = Object(0, 2.7, 7.3)
ob2 =  Object(1, 2.7, 7.3)
ob3 = Object(2, 3.2, 4.6)
ob4 = Object(3, 2.7, 7.3)

set_ = {ob1, ob2, ob3, ob4}  # Place objects in set

# Show unique elements i.e. set
for obj in set_:
  print(obj)

Output

{'id': 2, 'x': 3.2, 'y': 4.6}   # ob2
{'id': 0, 'x': 2.7, 'y': 7.3}   # ob0
DarrylG
  • 16,732
  • 2
  • 17
  • 23
0

If you don't want to, or for some reason can't, add the methods needed to use your objects in a set, you can find the objects with a unique set of attributes by using a temporary dictionary:

ob1 = Object(0, 2.7, 7.3)
ob2 = Object(1, 2.7, 7.3)
ob3 = Object(2, 3.2, 4.6)
ob4 = Object(3, 2.7, 7.3)

uniq = {(o.x, o.y): o for o in [ob1, ob2, ob3, ob4]}.values()

# test - print the object ids
print([o.id for o in uniq]

Results in:

[3, 2]
SpoonMeiser
  • 19,918
  • 8
  • 50
  • 68