Here's a tiny compilation of all the libraries and tools that can be used on Leetcode to make life simpler. This README
covers the following:
requests
collections
itertools
This library helps you pull and push data to remote or local servers via URLs. In this interaction between your Python code and the server, your code is called the "Client". When sending a request to a server, it sends back a "response" that contains information like the status (whether it's successful or not) and other trivial metadata.
There are some basic method and functions within requests
that helps you craft and facilitate these "client-server" interactions.
Suppose we have a URL url
that's in the form of a link to a page (suppose it's to discount ModReg's JSON directory used for module search). To download the contents from a file like this (called modules.json
), you can use the get
method like so:
import requests
url = 'https://raw.githubusercontent.com/rish-16/discount-modreg/main/modules.json'
response = requests.get(url)
print (response)
'''
<Response [200]>
'''
We get back a response status code of 200
which means OK
. This means your request was successful. There are many other status codes you should be aware of. It's summarised well in this image:
Ever encountered an Error 404 page before? This is because your request was unsuccessful. Not your fault, though.
To view the contents of the response, you can use the different methods of the response
variable like so:
# since we are requesting JSON information, let's access it in that format:
print (requests.json())
'''
{'BT1101': {'detailed-name': 'Introduction to Business Analytics',
'lecture-id': 'L-L1-1226',
'name': 'BT1101',
'occupancy': 153,
'units': '4.00',
'vacancy': '600'},
'BT2101': {'detailed-name': 'Econometrics Modeling for Business Analytics '
'And/Or',
'lecture-id': 'L-L1-1226',
'name': 'BT2101',
'occupancy': 153,
'units': '4.00',
'vacancy': '600'},
...
'''
There are other attributes and methods you can use for response
:
response.content
: Gets the raw string representation of the content in Bytes formatresponse.headers
: Gets the Header metadata that describes the request received by the serverresponse.elapsed
: Gets the time taken for the request to be received and answered by the server
This method allows you to update or add information to the server. This is usually done when dealing with remote databases where data is updated and added continually. Suppose we have a database that tracks a userID
and userEmail
. Let's say the user, with ID user1234
wants to change their email, originally [email protected]
:
import requests
url = 'https://www.database_server_url.com/'
data_to_be_sent = {
"userEmail": "[email protected]",
"userID": "user1234"
}
response = requests.push(url, data)
print (response)
'''
This request will send back a 200 if the database has been updated properly. If not, another code not in the 200s range.
'''
All data to be pushed to a server are typically in JSON format as seen by data_to_be_sent
. The server (assume it accepts new data like this) will then take this data and update the database appropriately using the specific userID
you have provided.
This library contains useful data structures to collect and store information in various forms.
A Counter
is literally a counter that keep track of element counts. This is a fast-query dictionary that lets you count the occurrences of data in a string or array. Suppose you encounter a question that asks you to count the number of occurrences of certain characters (like a
), you can do so like:
from collections import Counter
string = "aabcceijaaoceleciefeaha"
ctr = Counter(string)
print (ctr)
'''
Counter({'a': 6,
'e': 5,
'c': 4,
'i': 2,
'b': 1,
'j': 1,
'o': 1,
'l': 1,
'f': 1,
'h': 1})
'''
Now, we know the character a
shows up 6 times! To access this, you can use your usual dictionary querying to retrieve information:
print (ctr['a']) # returns 6
print (ctr['j']) # returns 1
print (ctr['c']) # returns 4
The ctr
variable comes with some funky, useful attributes:
# returns an array with the occurrences in sorted order
print (ctr.most_common())
'''
[('a', 6), ('e', 5), ('c', 4), ('i', 2), ('b', 1), ('j', 1), ('o', 1), ('l', 1), ('f', 1), ('h', 1)]
'''
You can even tell collections
how many of the top most-occurring unique characters you want:
print (ctr.most_common(4))
'''
[('a', 6), ('e', 5), ('c', 4), ('i', 2)]
'''
You can even run Counter
on an array and perform all the above-mentioned operations:
from collections import Counter
arr = [3, 5, 1, 9, 58, 2, 2, 0]
ctr = Counter(arr)
print (ctr)
'''
Counter({
2: 2, 3: 1, 5: 1, 1: 1, 9: 1, 58: 1, 0: 1
})
'''
### `deque`
This is an efficient double-ended queue data structure implementation. You do not need to waste time writing your own implementation during interviews.
```python
from collections import deque
deque = deque([1, 2, 3]) # initial elements [1, 2, 3] – can start empty as well
# adding
deque.append(4) # becomes [1, 2, 3, 4]
deque.appendleft(5) # becomes [5, 1, 2, 3, 4]
# removing
deque.pop() # becomes [5, 1, 2, 3]
deque.popleft() # becomes [1, 2, 3]
# reverse order (left becomes right, right becomes left)
deque.reverse() # becomes [3, 2, 1] until you re-reverse
This is a very important library for combinatorics (permutations and combinations). It allows you to take elements in an array or string and permute them, combine them, and arrange them exhaustively.
This lets you come up with all the possible permutations of a given array.
from itertools import permutations
print (list(permutations(['1', '2', '3']))) # be sure to cast it to a list
'''
[('1', '2', '3'),
('1', '3', '2'),
('2', '1', '3'),
('2', '3', '1'),
('3', '1', '2'),
('3', '2', '1')]
'''
This allows you to generate all possible combinations nCr
of an array:
from itertools import combinations
comb = combinations(['1', '2', '3', '4'], r=2) # all pairwise combinations of the array
print (list(combinations))
'''
[('1', '2'), ('1', '3'), ('1', '4'), ('2', '3'), ('2', '4'), ('3', '4')]
'''
This document contains some of the basic information on libraries you'll need when using Python on Leetcode. The environment comes with all of these baked in and needs no special installations or downloads.
Happy learning!