def minTransfers(self, transactions: List[List[int]]) -> int: # calculate final balance counter = defaultdict(int) for t in transactions: counter[t[0]] -= t[2] counter[t[1]] += t[2] # only get outstanding balances balance = [x for x in list(counter.values()) if x != 0] ans = 0 # find smallest sub groups, min with 2 elements, max with all elements for r in range(2, len(balance)+1): group = set() # find all possible combinations, if a sub group has sum of 0, pick them as candidate group.update(g for g in itertools.combinations(balance, r) if sum(g) == 0) # remove sub group from balance, only remove a sub group when all elements in the sub gourp are still in balance for g in group: if all([c in balance for c in g]): for c in g: balance.remove(c) ans += len(g) - 1 return ans
def __init__(self, maxNumbers): """ Initialize your data structure here @param maxNumbers - The maximum numbers that can be stored in the phone directory. :type maxNumbers: int """ self.queue=deque() self.s=set() for i in range(maxNumbers): self.queue.append(i)
def numSubstrNoRepeats(self, S, K): res, i = 0, 0 cur = set() for j in xrange(len(S)): while S[j] in cur: cur.remove(S[i]) i += 1 cur.add(S[j]) res += j - i + 1 return res
def containsNearbyDuplicate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: bool """ myset = set() for i in range(len(nums)): if i > k: myset.remove(nums[i-k-1]) if not myset.add(nums[i]): return True return False
add() Adds an element to the set clear() Removes all the elements from the set copy() Returns a copy of the set difference() Returns a set containing the difference between two or more sets difference_update() Removes the items in this set that are also included in another, specified set discard() Remove the specified item intersection() Returns a set, that is the intersection of two other sets intersection_update() Removes the items in this set that are not present in other, specified set(s) isdisjoint() Returns whether two sets have a intersection or not issubset() Returns whether another set contains this set or not issuperset() Returns whether this set contains another set or not pop() Removes an element from the set remove() Removes the specified element symmetric_difference() Returns a set with the symmetric differences of two sets symmetric_difference_update() inserts the symmetric differences from this set and another union() Return a set containing the union of sets update() Update the set with the union of this set and others
This operation removes element from the set. If element does not exist, it raises a KeyError. The .remove(x) operation returns None. Example >>> s = set([1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> s.remove(5) >>> print s set([1, 2, 3, 4, 6, 7, 8, 9]) >>> print s.remove(4) None >>> print s set([1, 2, 3, 6, 7, 8, 9]) >>> s.remove(0) KeyError: 0 .discard(x) This operation also removes element from the set. If element does not exist, it does not raise a KeyError. The .discard(x) operation returns None. Example >>> s = set([1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> s.discard(5) >>> print s set([1, 2, 3, 4, 6, 7, 8, 9]) >>> print s.discard(4) None >>> print s set([1, 2, 3, 6, 7, 8, 9])
#sets ================================ #Sets in Python #A Set is an unordered collection data type that is iterable, mutable, and #has no duplicate elements. Python’s set class represents the mathematical #notion of a set. The major advantage of using a set, as opposed to a list, #is that it has a highly optimized method for checking whether a specific #element is contained in the set. This is based on a data structure known as a hash table. =================================== #Frozen Sets Frozen sets are immutable objects that only support #methods and operators that produce a result without a?ecting the #frozen set or sets to which they are applied. =================================== # Same as {"a", "b","c"} normal_set = set(["a", "b","c"]) # Adding an element to normal set is fine normal_set.add("d") print("Normal Set") print(normal_set) # A frozen set frozen_set = frozenset(["e", "f", "g"]) print("Frozen Set") print(frozen_set) # Uncommenting below line would cause error as # we are trying to add element to a frozen set
In this lecture we will learn about the various methods for sets that you may not have seen yet. We'll go over the basic ones you already know and then dive a little deeper. In [2]: s = set() add add elements to a set. Remember a set won't take duplicate elements and only present them once (thats why its called a set!) In [3]: s.add(1) In [4]: s.add(2) In [5]: s Out[5]: {1, 2} clear removes all elements from the set In [6]: s.clear() In [7]: s Out[7]: set() copy returns a copy of the set. Note it is a copy, so changes to the original don't effect the copy. In [10]: s = {1,2,3}
tests=int(input()) for _ in range(tests): n=int(input()) a=input() aa=[] b=input() d={} a1=set(a) b1=set(b) x=0 if (a1 | b1) != a1: print(-1) continue dd={} for i in range(n): if b[i] != a[i]: if ord(b[i])>ord(a[i]): x=1 break if b[i] in d: d[b[i]].append(i) else: d[b[i]]=[i]
.remove(x) This operation removes element from the set. If element does not exist, it raises a KeyError. The .remove(x) operation returns None. Example >>> s = set([1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> s.remove(5) >>> print s set([1, 2, 3, 4, 6, 7, 8, 9]) >>> print s.remove(4) None >>> print s set([1, 2, 3, 6, 7, 8, 9]) >>> s.remove(0) KeyError: 0 .discard(x) This operation also removes element from the set. If element does not exist, it does not raise a KeyError. The .discard(x) operation returns None. Example >>> s = set([1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> s.discard(5) >>> print s set([1, 2, 3, 4, 6, 7, 8, 9]) >>> print s.discard(4) None >>> print s
.difference() The tool .difference() returns a set with all the elements from the set that are not in an iterable. Sometimes the - operator is used in place of the .difference() tool, but it only operates on the set of elements in set. Set is immutable to the .difference() operation (or the - operation). >>> s = set("Hacker") >>> print s.difference("Rank") set(['c', 'r', 'e', 'H']) >>> print s.difference(set(['R', 'a', 'n', 'k'])) set(['c', 'r', 'e', 'H']) >>> print s.difference(['R', 'a', 'n', 'k']) set(['c', 'r', 'e', 'H']) >>> print s.difference(enumerate(['R', 'a', 'n', 'k'])) set(['a', 'c', 'r', 'e', 'H', 'k']) >>> print s.difference({"Rank":1}) set(['a', 'c', 'e', 'H', 'k', 'r']) >>> s - set("Rank") set(['H', 'c', 'r', 'e']) Task Students of District College have a subscription to English and French newspapers. Some students have subscribed to only the English newspaper, some have subscribed to only the French newspaper, and some have subscribed to both newspapers. You are given two sets of student roll numbers. One set has subscribed to the English newspaper, and one set has subscribed to the French newspaper. Your task is to find the total number of students who have subscribed to only English newspapers. Input Format The first line contains the number of students who have subscribed to the English newspaper.
>>> text_lists Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> text_lists NameError: name 'text_lists' is not defined >>> texts_list >>> comments=zip(users_list,texts_list) >>> comments <zip object at 0x000002A8F8F3A108> >>> comments[users_list[0]] Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> comments[users_list[0]] TypeError: 'zip' object is not subscriptable >>> comments=set(comments) >>> comments >>> comments[0] Traceback (most recent call last): File "<pyshell#10>", line 1, in <module> comments[0] TypeError: 'set' object is not subscriptable >>> print(comments) >>> print(comments['aashita_jhamb']) Traceback (most recent call last): File "<pyshell#12>", line 1, in <module> print(comments['aashita_jhamb']) TypeError: 'set' object is not subscriptable >>> len(comments)
#============================================# # SET # #============================================# #Set contains Unordered and Unindexed elements #Set are written within Curly Braces. #Creating Set #Empty Set example = set() print((dir(example)) print() #Adding items in the empty set example.add(42) example.add("Abhishek") example.add(56.12) example.add(False) #All of the above item will be added in the set. #It is possible that the order might be different than the way we added it. {False, 42, 56.12, 'Abhishek'} #In a set if you add a duplicate value, you won't get any error but there will be only a single copy of that item. example.add(42) print(example) #Even though we added 42 again, there will only be a single 42 value in it.
#Sets in Python #A Set is an unordered collection data type that is iterable, mutable, and #has no duplicate elements. Python’s set class represents the mathematical #notion of a set. The major advantage of using a set, as opposed to a list, #is that it has a highly optimized method for checking whether a specific #element is contained in the set. This is based on a data structure known as a hash table. =================================== #Frozen Sets Frozen sets are immutable objects that only support #methods and operators that produce a result without a?ecting the #frozen set or sets to which they are applied. =================================== 1. set --> mutable 2. frozenset --> Immutable =================================== # Same as {"a", "b","c"} normal_set = set(["a", "b","c"]) # Adding an element to normal set is fine normal_set.add("d") print("Normal Set") print(normal_set) # A frozen set frozen_set = frozenset(["e", "f", "g"]) print("Frozen Set") print(frozen_set) # Uncommenting below line would cause error as # we are trying to add element to a frozen set # frozen_set.add("h") Output: #Normal Set #set(['a', 'c', 'b', 'd']) #Frozen Set
def numKLenSubstrNoRepeats(self, S, K): return 0 if K > 26 else sum(len(set(S[i:i + K])) == K for i in xrange(n - K + 1))
piles = [2.83, 8.23, 9.38, 10.23, 25.58, 0.42, 5.37, 28.10, 32.14, 7.31] def hash_functions(x): return int(x*100 % 31) [hash_functions(pile) for pile in piles] ouput [4, 17, 8, 0, 16, 11, 10, 20, 21, 18] print(int(5.37 * 100 % 31)) 10 print(set([23, 609, 348, 10, 5, 23, 340, 82])) print(set(('a', 'b', 'q', 'c', 'c', 'd', 'r', 'a'))) output {609, 5, 10, 82, 340, 23, 348} {'b', 'a', 'd', 'c', 'q', 'r'} student_a_courses = {'history', 'english', 'biology', 'theatre'} student_b_courses = {'biology', 'english', 'mathematics', 'computer science'} print(student_a_courses.intersection(student_b_courses)) output: english print(student_a_courses.union(student_b_courses)) output:
A-B.png .difference() The tool .difference() returns a set with all the elements from the set that are not in an iterable. Sometimes the - operator is used in place of the .difference() tool, but it only operates on the set of elements in set. Set is immutable to the .difference() operation (or the - operation). >>> s = set("Hacker") >>> print s.difference("Rank") set(['c', 'r', 'e', 'H']) >>> print s.difference(set(['R', 'a', 'n', 'k'])) set(['c', 'r', 'e', 'H']) >>> print s.difference(['R', 'a', 'n', 'k']) set(['c', 'r', 'e', 'H']) >>> print s.difference(enumerate(['R', 'a', 'n', 'k'])) set(['a', 'c', 'r', 'e', 'H', 'k']) >>> print s.difference({"Rank":1}) set(['a', 'c', 'e', 'H', 'k', 'r']) >>> s - set("Rank") set(['H', 'c', 'r', 'e']) Task Students of District College have a subscription to English and French newspapers. Some students have subscribed to only the English newspaper, some have subscribed to only the French newspaper, and some have subscribed to both newspapers. You are given two sets of student roll numbers. One set has subscribed to the English newspaper, and one set has subscribed to the French newspaper. Your task is to find the total number of students who have subscribed to only English newspapers. Input Format The first line contains the number of students who have subscribed to the English newspaper.