当前位置:网站首页>Daily question 2013 Detect square
Daily question 2013 Detect square
2022-07-05 05:41:00 【A big pigeon】
topic : stay x-y The number of schemes that plane detection can form an axis aligned square .
The main points of :1. Shaft alignment, : The side of the square is parallel to the coordinate axis .2. There can be multiple points at the same position on the plane .
Explain :( Refer to the official explanation )
Use dictionary nesting to store points .{y:{x: Number }}
When calculating the square scheme, you can enumerate y2 Determine the side length of the square abs(y2-y), So as to determine the four points of the square .
class DetectSquares:
def __init__(self):
self.map = defaultdict(Counter)
# {y:{x: Number }}
def add(self, point: List[int]) -> None:
x,y = point
self.map[y][x] += 1
def count(self, point: List[int]) -> int:
# Number of axis aligned squares
res = 0
x,y = point
if not y in self.map:
return 0
yCnt = self.map[y] #y Corresponding x Dictionaries
# Enumerate another y Axis
for y2,y2Cnt in self.map.items():
if y2 != y:
d = y2 - y
res += y2Cnt[x] * y2Cnt[x+d] * yCnt[x+d]
res += y2Cnt[x] * y2Cnt[x-d] * yCnt[x-d]
return res
# Your DetectSquares object will be instantiated and called as such:
# obj = DetectSquares()
# obj.add(point)
# param_2 = obj.count(point)Add :defaultdict() and Counter
collections --- Container data type — Python 3.10.2 file
defaultdict() Returns an object similar to a dictionary . yes dict Subclasses of .
This object contains a named default_factory Properties of , When constructing , The first parameter is used to provide the initial value for the attribute , The default is None. All other parameters ( Including keyword parameters ) Are equivalent to passing on to dict Constructor for .
When the key value cannot be found ,defaultdict Would call default_factory Method provides default values . in other words , Equivalent to
Dictionary d.setdefault(k, default_factory())
defaultdict Example :
Use list As default_factory, Easily ( key - A pair of values ) The sequence is converted to ( key - A list of ) Dictionaries :
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
... d[k].append(v)
...
>>> sorted(d.items())
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
When each key first meets , It's not in the dictionary yet , So automatically create this entry , That is to call default_factory Method , Returns an empty list. list.append() Add values to this new list . When the key is accessed again , Just operate normally ,list.append() Add another value to the list . This is better than its equivalent method dict.setdefault() Be fast and simple :
>>>
>>> d = {}
>>> for k, v in s:
... d.setdefault(k, []).append(v)
...
>>> sorted(d.items())
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
Set up default_factory by int, send defaultdict Used to count ( Similar to... In other languages bag or multiset):
>>>
>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
... d[k] += 1
...
>>> sorted(d.items())
[('i', 4), ('m', 1), ('p', 2), ('s', 4)]When a letter is first encountered , It will fail the query , be default_factory Would call int() To provide an integer 0 As default . The subsequent auto increment operation establishes the count of each letter .
Counter
collections --- Container data type — Python 3.10.2 file
Counter yes dict Subclasses of , Used to count hashable objects . It's a collection , Elements are like dictionary keys (key) Same storage , Their counts are stored as values .
>>> # Tally occurrences of words in a list
>>> cnt = Counter()
>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
... cnt[word] += 1
>>> cnt
Counter({'blue': 3, 'red': 2, 'green': 1})
If the referenced key has no record , Just go back to one 0, Instead of popping up a KeyError :
>>> c = Counter(['eggs', 'ham']) >>> c['bacon'] # count of a missing element is zero 0
边栏推荐
- EOJ 2021.10 E. XOR tree
- Sword finger offer 35 Replication of complex linked list
- ALU逻辑运算单元
- Sword finger offer 09 Implementing queues with two stacks
- Sword finger offer 05 Replace spaces
- Csp-j-2020-excellent split multiple solutions
- 搭建完数据库和网站后.打开app测试时候显示服务器正在维护.
- Palindrome (csp-s-2021-palin) solution
- lxml.etree.XMLSyntaxError: Opening and ending tag mismatch: meta line 6 and head, line 8, column 8
- 剑指 Offer 35.复杂链表的复制
猜你喜欢

Introduction to tools in TF-A

Fried chicken nuggets and fifa22
![[cloud native] record of feign custom configuration of microservices](/img/39/05cf7673155954c90e75a8a2eecd96.jpg)
[cloud native] record of feign custom configuration of microservices

浅谈JVM(面试常考)

中职网络安全技能竞赛——广西区赛中间件渗透测试教程文章

CF1637E Best Pair

Remote upgrade afraid of cutting beard? Explain FOTA safety upgrade in detail

Wazuh开源主机安全解决方案的简介与使用体验

读者写者模型

Brief introduction to tcp/ip protocol stack
随机推荐
ssh免密登录设置及使用脚本进行ssh登录并执行指令
Service fusing hystrix
Warning using room database: schema export directory is not provided to the annotation processor so we cannot export
Haut OJ 2021 freshmen week II reflection summary
2017 USP Try-outs C. Coprimes
Codeforces round 712 (Div. 2) d. 3-coloring (construction)
读者写者模型
Dichotomy, discretization, etc
YOLOv5-Shufflenetv2
YOLOv5-Shufflenetv2
二十六、文件系统API(设备在应用间的共享;目录和文件API)
Common optimization methods
第六章 数据流建模—课后习题
Add level control and logger level control of Solon logging plug-in
object serialization
【实战技能】如何做好技术培训?
CCPC Weihai 2021m eight hundred and ten thousand nine hundred and seventy-five
ALU逻辑运算单元
lxml.etree.XMLSyntaxError: Opening and ending tag mismatch: meta line 6 and head, line 8, column 8
Drawing dynamic 3D circle with pure C language