当前位置:网站首页>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
边栏推荐
- Animation scoring data analysis and visualization and it industry recruitment data analysis and visualization
- 动漫评分数据分析与可视化 与 IT行业招聘数据分析与可视化
- CF1634E Fair Share
- Light a light with stm32
- Sword finger offer 35 Replication of complex linked list
- Reader writer model
- 游戏商城毕业设计
- A preliminary study of sdei - see the essence through transactions
- 26、 File system API (device sharing between applications; directory and file API)
- Configuration and startup of kubedm series-02-kubelet
猜你喜欢
剑指 Offer 58 - II. 左旋转字符串
【Jailhouse 文章】Look Mum, no VM Exits
Introduction and experience of wazuh open source host security solution
sync.Mutex源码解读
全国中职网络安全B模块之国赛题远程代码执行渗透测试 //PHPstudy的后门漏洞分析
Acwing 4300. Two operations
Personal developed penetration testing tool Satania v1.2 update
AtCoder Grand Contest 013 E - Placing Squares
剑指 Offer 06.从头到尾打印链表
Sword finger offer 04 Search in two-dimensional array
随机推荐
[jailhouse article] performance measurements for hypervisors on embedded ARM processors
Bit mask of bit operation
每日一题-搜索二维矩阵ps二维数组的查找
中职网络安全技能竞赛——广西区赛中间件渗透测试教程文章
[cloud native] record of feign custom configuration of microservices
Sword finger offer 58 - ii Rotate string left
Haut OJ 1401: praise energy
Use of room database
Fried chicken nuggets and fifa22
Sword finger offer 04 Search in two-dimensional array
浅谈JVM(面试常考)
Configuration and startup of kubedm series-02-kubelet
Software test -- 0 sequence
2020ccpc Qinhuangdao J - Kingdom's power
Add level control and logger level control of Solon logging plug-in
A new micro ORM open source framework
Detailed explanation of expression (csp-j 2021 expr) topic
Introduction et expérience de wazuh open source host Security Solution
26、 File system API (device sharing between applications; directory and file API)
Codeforces Round #715 (Div. 2) D. Binary Literature