Last active
August 1, 2016 13:02
-
-
Save nisxiya/8fbcdae8bd281bcd6a9671b07e3eb4df to your computer and use it in GitHub Desktop.
remove all the duplicated items from a list. These items should contain primitive elements (int, str, float, etc) and all other kinds of objects.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
#coding=utf-8 | |
class Ice: | |
def __init__(self, name): | |
self.prop = 'water' | |
self.hardness = 9 | |
self.name = name | |
class RmDup: | |
def rm(self, target_arr): | |
if type(target_arr) != type([]): | |
print 'exception: not list type' | |
sys.exit(1) | |
if len(target_arr) == 0: | |
return target_arr | |
# So dt will look like. Key is a Type object and value is an array | |
# <type 'int'>: [1, 2, 3] | |
# <type 'str'>: ['arr', 'arr2'] | |
dt = {} | |
for each_item in target_arr: | |
item_type = type(each_item) | |
if not dt.has_key(item_type): | |
dt[item_type] = [] | |
dt[item_type].append(each_item) | |
# remove duplications | |
for k, v in dt.items(): | |
# list(set(target)) should work for all kinds of object besides the primitive types like int, str | |
dt[k] = list(set((dt[k]))) | |
res = [] | |
# merge all the results | |
for k, v in dt.items(): | |
res.extend(v) | |
return res | |
if __name__ == '__main__': | |
target_arr = [] | |
target_arr.append(1); | |
target_arr.append(3); | |
target_arr.append(2); | |
target_arr.append(2); | |
target_arr.append('arr') | |
target_arr.append('arr2') | |
target_arr.append('arr') | |
ice1 = Ice('ice1') | |
ice2 = Ice('ice2') | |
ice3 = ice1 | |
target_arr.append(ice1) | |
target_arr.append(ice2) | |
target_arr.append(ice3) | |
rd = RmDup() | |
print 'Before rming duplicated items', target_arr | |
target_arr = rd.rm(target_arr) | |
print 'After rming duplicated items', target_arr | |
print 'The overall time complexity is O(n)' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment