Skip to content

Instantly share code, notes, and snippets.

@ZhouYang1993
ZhouYang1993 / example5.py
Created April 22, 2020 12:23
Differences between Class Attribute and Instance Attribute of Python
class MyClass(object):
data = 0
def __init__(self, value):
self.instance_data = value
MyClass.data
# 0
my_instance = MyClass(3)
my_instance.data
@ZhouYang1993
ZhouYang1993 / example6.py
Created April 22, 2020 12:32
Differences between Class Attribute and Instance Attribute of Python
class MyClass(object):
data = []
def __init__(self, value):
self.instance_data = value
my_instance = MyClass(3)
my_instance.data
# []
try:
f = open('test_file.txt', 'r')
# do some operations
finally:
if f:
f.close()
@ZhouYang1993
ZhouYang1993 / example1.py
Created April 24, 2020 19:49
File Handling in Python
try:
f = open('test_file.txt', 'r')
print(f.read())
finally:
if f:
f.close()
@ZhouYang1993
ZhouYang1993 / example2.py
Created April 24, 2020 19:54
File Handling in Python
with open('test_file.txt', 'r') as f:
print(f.read())
@ZhouYang1993
ZhouYang1993 / solution.py
Created April 24, 2020 20:27
File Handling in Python
import bisect
with open('ip1.txt', 'r') as f1:
list1 = [line.rstrip('\n') for line in f1.readlines()]
with open('ip2.txt', 'r') as f2:
list2 = [line.rstrip('\n') for line in f2.readlines()]
list2.sort()
same_ip = []
for i in list1:
@ZhouYang1993
ZhouYang1993 / example3.py
Created April 24, 2020 20:48
File Handling in Python
with open('test.txt', 'w') as f:
f.write('Hello, world!')
@ZhouYang1993
ZhouYang1993 / example4.py
Created April 24, 2020 21:02
File Handling in Python
# Example 1
with open('test1.txt', 'w') as f:
f.writelines(["1", "2", "3"])
# The contents of test1.txt is:
# 123
# Example 2
with open('test2.txt', 'w') as f:
f.writelines(["1\n", "2\n", "3\n"])
# The contents of test2.txt is:
@ZhouYang1993
ZhouYang1993 / example5.py
Created April 24, 2020 21:22
File Handling in Python
# The contents in test.txt are:
# Hello,Yang!
with open('test.txt', 'r+') as f:
print(f.read())
f.seek(6, 0)
print(f.read())
# Hello,Yang!
# Yang!
@ZhouYang1993
ZhouYang1993 / LeetCode 20 Valid Parentheses.py
Created May 8, 2020 00:46
Algorithms for Interview 1: Stack
class Solution:
def isValid(self, s: str) -> bool:
mapping = {')': '(', ']': '[', '}': '{'}
stack = []
for char in s:
if mapping.get(char):
if not stack:
return False
else:
if stack[-1] == mapping[char]: