[Python] Basic Python Knowledge for Leetcode

Posted by 西维蜀黍的OJ Blog on 2023-08-26, Last Modified on 2024-01-16

For

xs = [8, 23, 45]

for x in xs:
    print("item #{} = {}".format(index, x))

Use the built-in function enumerate():

for idx, x in enumerate(xs):
    print(idx, x)

Data structure

List

l = []
# or
l = list()

# add
l.append(1)
print(l) # 1

# for loop
>>> for i, value in enumerate(['A', 'B', 'C']):
...     print(i, value)
...
0 A
1 B
2 C

Ref https://swsmile.info/post/python-collection-list/

Map/Dict

# init
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(type(thisdict))

# init 2
thisdict = dict(name = "John", age = 36, country = "Norway")
print(thisdict)

# delete
del tel['sape']

# dict -> list
>>> tel
{'jack': 4098, 'guido': 4127, 'irv': 4127}
>>> list(tel)
['jack', 'guido', 'irv']

# get
>>> 'Thomas' in d
False

# for-loop
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> for key in d:
...     print(key)
...
a
c
b

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
...     print(k, v)
...
gallahad the pure
robin the brave

Ref https://swsmile.info/post/python-collection-dict/

Set

thisset = {"apple", "banana", "cherry"}
print(thisset)

thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
print(thisset)

// add
GEEK.add('s')

Ref https://swsmile.info/post/python-collection-set/

Tuple

thistuple = ("apple", "banana", "cherry")
print(thistuple)

thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)


s=(2,5,8)
s_append = s + (8, 16, 67)
print(s_append) # (2, 5, 8, 8, 16, 67)
print(s) # (2, 5, 8)

a = ('2',)
b = 'z'
new = a + (b,)

Ref https://swsmile.info/post/python-collection-tuple/