本文整理汇总了Python中sortedcontainers.SortedSet.add方法的典型用法代码示例。如果您正苦于以下问题:Python SortedSet.add方法的具体用法?Python SortedSet.add怎么用?Python SortedSet.add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sortedcontainers.SortedSet
的用法示例。
在下文中一共展示了SortedSet.add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_ne
# 需要导入模块: from sortedcontainers import SortedSet [as 别名]
# 或者: from sortedcontainers.SortedSet import add [as 别名]
def test_ne():
alpha = SortedSet(range(100), load=7)
beta = SortedSet(range(99), load=17)
assert alpha != beta
beta.add(100)
assert alpha != beta
assert alpha != beta._set
示例2: get_links
# 需要导入模块: from sortedcontainers import SortedSet [as 别名]
# 或者: from sortedcontainers.SortedSet import add [as 别名]
def get_links(names, html):
"""
Return a SortedSet of computer scientist names that are linked from this
html page. The return set is restricted to those people in the provided
set of names. The returned list should contain no duplicates.
Params:
names....A SortedSet of computer scientist names, one per filename.
html.....A string representing one html page.
Returns:
A SortedSet of names of linked computer scientists on this html page, restricted to
elements of the set of provided names.
>>> get_links({'Gerald_Jay_Sussman'},
... '''<a href="/wiki/Gerald_Jay_Sussman">xx</a> and <a href="/wiki/Not_Me">xx</a>''')
SortedSet(['Gerald_Jay_Sussman'], key=None, load=1000)
"""
pagenames = SortedSet()
for link in BeautifulSoup(html, "html.parser", parse_only=SoupStrainer('a')):
if link.has_attr('href'):
name = link['href'].split('/')[-1]
if name in names:
pagenames.add(name)
return pagenames
示例3: test_eq
# 需要导入模块: from sortedcontainers import SortedSet [as 别名]
# 或者: from sortedcontainers.SortedSet import add [as 别名]
def test_eq():
alpha = SortedSet(range(100), load=7)
beta = SortedSet(range(100), load=17)
assert alpha == beta
assert alpha == beta._set
beta.add(101)
assert not (alpha == beta)
示例4: get_links
# 需要导入模块: from sortedcontainers import SortedSet [as 别名]
# 或者: from sortedcontainers.SortedSet import add [as 别名]
def get_links(names, html):
"""
Return a SortedSet of computer scientist names that are linked from this
html page. The return set is restricted to those people in the provided
set of names. The returned list should contain no duplicates.
Params:
names....A SortedSet of computer scientist names, one per filename.
html.....A string representing one html page.
Returns:
A SortedSet of names of linked computer scientists on this html page, restricted to
elements of the set of provided names.
>>> get_links({'Gerald_Jay_Sussman'},
... '''<a href="/wiki/Gerald_Jay_Sussman">xx</a> and <a href="/wiki/Not_Me">xx</a>''')
SortedSet(['Gerald_Jay_Sussman'], key=None, load=1000)
"""
soup = BeautifulSoup(html,"html.parser")
list = [l['href'] for l in soup.find_all('a') if l.get('href')]
res = SortedSet()
for l in list:
if l.startswith('/wiki/'):
tokens = l.split('/')
if tokens[2] in names:
res.add(tokens[2])
return res
示例5: test_add
# 需要导入模块: from sortedcontainers import SortedSet [as 别名]
# 或者: from sortedcontainers.SortedSet import add [as 别名]
def test_add():
temp = SortedSet(range(100))
temp._reset(7)
temp.add(100)
temp.add(90)
temp._check()
assert all(val == temp[val] for val in range(101))
示例6: test_count
# 需要导入模块: from sortedcontainers import SortedSet [as 别名]
# 或者: from sortedcontainers.SortedSet import add [as 别名]
def test_count():
temp = SortedSet(range(100), load=7)
assert all(temp.count(val) == 1 for val in range(100))
assert temp.count(100) == 0
assert temp.count(0) == 1
temp.add(0)
assert temp.count(0) == 1
temp._check()
示例7: test_eq
# 需要导入模块: from sortedcontainers import SortedSet [as 别名]
# 或者: from sortedcontainers.SortedSet import add [as 别名]
def test_eq():
alpha = SortedSet(range(100))
alpha._reset(7)
beta = SortedSet(range(100))
beta._reset(17)
assert alpha == beta
assert alpha == beta._set
beta.add(101)
assert not (alpha == beta)
示例8: DictGraph
# 需要导入模块: from sortedcontainers import SortedSet [as 别名]
# 或者: from sortedcontainers.SortedSet import add [as 别名]
class DictGraph(Graph):
"""Graph that supports nonconsecutive vertex ids."""
def __init__(self, nodes: Set[int]=None, r: int=1) -> None:
"""Make a new graph."""
if nodes is None:
self.nodes = SortedSet() # type: Set[int]
else:
self.nodes = nodes
self.radius = r
self.inarcs_by_weight = [defaultdict(SortedSet) for _ in range(self.radius)]
def __len__(self):
"""len() support."""
return len(self.nodes)
def __iter__(self):
"""Iteration support."""
return iter(self.nodes)
def __contains__(self, v):
"""Support for `if v in graph`."""
return v in self.nodes
def add_node(self, u: int):
"""Add a new node."""
self.nodes.add(u)
def arcs(self, weight: int=None):
"""
Return all the arcs in the graph.
restrict to a given weight when provided
"""
if weight:
return [(x, y) for x in self.nodes
for y in self.inarcs_by_weight[weight-1][x]]
else:
return [(x, y, w+1) for w, arc_list in
enumerate(self.inarcs_by_weight)
for x in self.nodes
for y in arc_list[x]]
def remove_isolates(self) -> List[int]:
"""
Remove all isolated vertices and return a list of vertices removed.
Precondition: the graph is bidirectional
"""
isolates = [v for v in self if self.in_degree(v, 1) == 0]
for v in isolates:
self.nodes.remove(v)
for N in self.inarcs_by_weight:
if v in N:
del N[v]
return isolates
示例9: test_ne
# 需要导入模块: from sortedcontainers import SortedSet [as 别名]
# 或者: from sortedcontainers.SortedSet import add [as 别名]
def test_ne():
alpha = SortedSet(range(100))
alpha._reset(7)
beta = SortedSet(range(99))
beta._reset(17)
assert alpha != beta
beta.add(100)
assert alpha != beta
assert alpha != beta._set
assert alpha != list(range(101))
示例10: get_links
# 需要导入模块: from sortedcontainers import SortedSet [as 别名]
# 或者: from sortedcontainers.SortedSet import add [as 别名]
def get_links(names, html):
"""
Return a SortedSet of computer scientist names that are linked from this
html page. The return set is restricted to those people in the provided
set of names. The returned list should contain no duplicates.
Params:
names....A SortedSet of computer scientist names, one per filename.
html.....A string representing one html page.
Returns:
A SortedSet of names of linked computer scientists on this html page, restricted to
elements of the set of provided names.
>>> get_links({'Gerald_Jay_Sussman'},
... '''<a href="/wiki/Gerald_Jay_Sussman">xx</a> and <a href="/wiki/Not_Me">xx</a>''')
SortedSet(['Gerald_Jay_Sussman'], key=None, load=1000)
"""
###TODO
#remove BeautifulSoap - later
listofHrefs = []
listofHrefTexts = []
FinalSortedSet = SortedSet()
splice_char = '/'
#getting all the tags using the BeautifulSoup
#soup = BeautifulSoup(html, "html.parser")
#fectching all the links in anchor tags
#for link in soup.find_all('a'):
#listofHrefs.append(link.get('href'))
for i in range(0,len(listofHrefs)):
value = listofHrefs[i][6:]
listofHrefTexts.append(value)
listofHrefTexts = re.findall(r'href="([^"]*)', html)
#print(listofHrefTexts)
for i in listofHrefTexts:
#print(i)
value = i[6:]
listofHrefs.append(value)
#print(listofHrefs)
listofHrefs = list(set(listofHrefs))
#print(len(listofHrefs))
for href in listofHrefs:
for name in names:
#windows OS handling
if(name == "Guy_L._Steele,_Jr"):
names.remove(name)
names.add("Guy_L._Steele,_Jr.")
if(href == name):
FinalSortedSet.add(name)
return FinalSortedSet
pass
示例11: compute_domset
# 需要导入模块: from sortedcontainers import SortedSet [as 别名]
# 或者: from sortedcontainers.SortedSet import add [as 别名]
def compute_domset(graph: Graph, radius: int):
"""
Compute a d-dominating set using Dvorak's approximation algorithm
for dtf-graphs (see `Structural Sparseness and Complex Networks').
Graph needs a distance-d dtf augmentation (see rdomset() for usage).
"""
domset = SortedSet()
infinity = float('inf')
# minimum distance to a dominating vertex, obviously infinite at start
domdistance = defaultdict(lambda: infinity) # type: Dict[int, float]
# counter that keeps track of how many neighbors have made it into the
# domset
domcounter = defaultdict(int) # type: Dict[int, int]
# cutoff for how many times a vertex needs to have its neighbors added to
# the domset before it does. We choose radius^2 as a convenient "large"
# number
c = (2*radius)**2
# Sort the vertices by indegree so we take fewer vertices
order = sorted([v for v in graph], key=lambda x: graph.in_degree(x),
reverse=True)
# vprops = [(v,graph.in_degree(v)) for v in nodes]
# vprops.sort(key=itemgetter(1),reverse=False)
# order = map(itemgetter(0),vprops)
for v in order:
# look at the in neighbors to update the distance
for r in range(1, radius + 1):
for u in graph.in_neighbors(v, r):
domdistance[v] = min(domdistance[v], r+domdistance[u])
# if v is already dominated at radius, no need to work
if domdistance[v] <= radius:
continue
# if v is not dominated at radius, put v in the dominating set
domset.add(v)
domdistance[v] = 0
# update distances of neighbors of v if v is closer if u has had too
# many of its neighbors taken into the domset, include it too.
for r in range(1, graph.radius + 1):
for u in graph.in_neighbors(v, r):
domcounter[u] += 1
domdistance[u] = min(domdistance[u], r)
if domcounter[u] > c and u not in domset:
# add u to domset
domset.add(u)
domdistance[u] = 0
for x, rx in graph.in_neighbors(u):
domdistance[x] = min(domdistance[x], rx)
# only need to update domdistance if u didn't get added
return domset
示例12: __init__
# 需要导入模块: from sortedcontainers import SortedSet [as 别名]
# 或者: from sortedcontainers.SortedSet import add [as 别名]
class Server:
_ids = 0
def __init__(self):
self.queue = SortedSet(key = lambda job: job.arrivalTime)
self.numServers = 1
Server._ids +=1
self.busyServers = 0
self.serviceTimeDistribution = None
self.name = "Server {}".format(Server._ids)
self.In = None
self.Out = None
self.scheduler = None
def receive(self, m):
if m.event == "end": # end of service
self.send(m.job)
if len(self.queue) > 0:
assert self.busyServers == self.numServers
job = self.queue.pop(0)
self.startService(job)
else:
assert self.busyServers > 0
self.busyServers -= 1
#self.departureStats()
else: # receive new job
assert "job" in m.event
job = m.job
job.setArrivalTime(self.scheduler.now())
serviceTime = self.serviceTimeDistribution.rvs()
job.setServiceTime(serviceTime)
job.log(self.scheduler.now(), "a", self.busyServers + len(self.queue))
if self.busyServers < self.numServers:
self.busyServers += 1
self.startService(job)
else:
self.queue.add(job)
def startService(self, job):
job.log(self.scheduler.now(), "s", len(self.queue))
t = self.scheduler.now() + job.serviceTime
m = Event(self, self, t, job = job, event = "end")
self.scheduler.add(m)
def send(self, job): # job departure
job.log(self.scheduler.now(), "d", len(self.queue))
m = Event(self, self.Out, self.scheduler.now(), job = job, event = "job")
self.scheduler.add(m)
def setServiceTimeDistribution(self, distribution):
self.serviceTimeDistribution = distribution
示例13: euler
# 需要导入模块: from sortedcontainers import SortedSet [as 别名]
# 或者: from sortedcontainers.SortedSet import add [as 别名]
def euler():
fracs = SortedSet()
limit = 10**6
for d in range(5, limit+1):
target = d*3/7
for n in range(int(floor(target)), int(ceil(target))+1):
if gcd(n, d) == 1:
fracs.add(Fraction(n, d))
result = 0
compare = Fraction(3, 7)
for i, f in enumerate(fracs):
if f == compare:
result = i-1
break
print(fracs[result])
示例14: __init__
# 需要导入模块: from sortedcontainers import SortedSet [as 别名]
# 或者: from sortedcontainers.SortedSet import add [as 别名]
class FileReference:
"""A class that manages n-triple files.
This class stores inforamtation about the location of a n-triple file and is
able to add and delete triples to that file.
"""
def __init__(self, path, content):
"""Initialize a new FileReference instance.
Args:
filelocation: A string of the filepath.
filecontentinmem: Boolean to decide if local filesystem should be used to
or if file content should be kept in memory too . (Defaults false)
Raises:
ValueError: If no file at the filelocation, or in the given directory + filelocation.
"""
if isinstance(content, str):
new = []
for line in content.splitlines():
new.append(' '.join(line.split()))
content = new
self._path = path
self._content = SortedSet(content)
self._modified = False
@property
def path(self):
return self._path
@property
def content(self):
return "\n".join(self._content) + "\n"
def add(self, data):
"""Add a triple to the file content."""
self._content.add(data)
def extend(self, data):
"""Add triples to the file content."""
self._content.extend(data)
def remove(self, data):
"""Remove trple from the file content."""
try:
self._content.remove(data)
except KeyError:
pass
示例15: euler50
# 需要导入模块: from sortedcontainers import SortedSet [as 别名]
# 或者: from sortedcontainers.SortedSet import add [as 别名]
def euler50():
limit = 100
primes = SortedSet(sieve.primerange(1, limit))
prime_sums = SortedSet()
prime_sums.add(0)
consecutive = 0
for p in primes:
prime_sums.add(prime_sums[-1] + p)
for i in range(consecutive, len(prime_sums)):
for j in range(i - consecutive - 1, -1, -1):
if prime_sums[i] - prime_sums[j] > limit:
break
if isprime(prime_sums[i] - prime_sums[j]):
consecutive = i - j
result = prime_sums[i] - prime_sums[j]
print(result)