Initial commit
This commit is contained in:
24
python/Algorithms/8 queen problem with recursion.py
Normal file
24
python/Algorithms/8 queen problem with recursion.py
Normal file
@@ -0,0 +1,24 @@
|
||||
BOARD_SIZE = 8
|
||||
|
||||
def under_attack(col, queens):
|
||||
left = right = col
|
||||
|
||||
for r, c in reversed(queens):
|
||||
left, right = left - 1, right + 1
|
||||
|
||||
if c in (left, col, right):
|
||||
return True
|
||||
return False
|
||||
|
||||
def solve(n):
|
||||
if n == 0:
|
||||
return [[]]
|
||||
|
||||
smaller_solutions = solve(n - 1)
|
||||
|
||||
return [solution+[(n,i+1)]
|
||||
for i in xrange(BOARD_SIZE)
|
||||
for solution in smaller_solutions
|
||||
if not under_attack(i+1, solution)]
|
||||
for answer in solve(BOARD_SIZE):
|
||||
print answer
|
||||
28
python/Algorithms/Guess the number game.py
Normal file
28
python/Algorithms/Guess the number game.py
Normal file
@@ -0,0 +1,28 @@
|
||||
import random
|
||||
|
||||
guesses_made = 0
|
||||
|
||||
name = raw_input('Hello! What is your name?\n')
|
||||
|
||||
number = random.randint(1, 20)
|
||||
print 'Well, {0}, I am thinking of a number between 1 and 20.'.format(name)
|
||||
|
||||
while guesses_made < 6:
|
||||
|
||||
guess = int(raw_input('Take a guess: '))
|
||||
|
||||
guesses_made += 1
|
||||
|
||||
if guess < number:
|
||||
print 'Your guess is too low.'
|
||||
|
||||
if guess > number:
|
||||
print 'Your guess is too high.'
|
||||
|
||||
if guess == number:
|
||||
break
|
||||
|
||||
if guess == number:
|
||||
print 'Good job, {0}! You guessed my number in {1} guesses!'.format(name, guesses_made)
|
||||
else:
|
||||
print 'Nope. The number I was thinking of was {0}'.format(number)
|
||||
@@ -0,0 +1,20 @@
|
||||
import itertools
|
||||
|
||||
def iter_primes():
|
||||
# an iterator of all numbers between 2 and +infinity
|
||||
numbers = itertools.count(2)
|
||||
|
||||
# generate primes forever
|
||||
while True:
|
||||
# get the first number from the iterator (always a prime)
|
||||
prime = numbers.next()
|
||||
yield prime
|
||||
|
||||
# this code iteratively builds up a chain of
|
||||
# filters...slightly tricky, but ponder it a bit
|
||||
numbers = itertools.ifilter(prime.__rmod__, numbers)
|
||||
|
||||
for p in iter_primes():
|
||||
if p > 1000:
|
||||
break
|
||||
print p
|
||||
@@ -0,0 +1,15 @@
|
||||
def counting_sort(array1, max_val):
|
||||
m = max_val + 1
|
||||
count = [0] * m
|
||||
|
||||
for a in array1:
|
||||
# count occurences
|
||||
count[a] += 1
|
||||
i = 0
|
||||
for a in range(m):
|
||||
for c in range(count[a]):
|
||||
array1[i] = a
|
||||
i += 1
|
||||
return array1
|
||||
|
||||
print(counting_sort( [1, 2, 7, 3, 2, 1, 4, 2, 3, 2, 1], 7 ))
|
||||
@@ -0,0 +1,34 @@
|
||||
def Ordered_binary_Search(olist, item):
|
||||
|
||||
if len(olist) == 0:
|
||||
return False
|
||||
else:
|
||||
midpoint = len(olist) // 2
|
||||
if olist[midpoint] == item:
|
||||
return True
|
||||
else:
|
||||
if item < olist[midpoint]:
|
||||
return binarySearch(olist[:midpoint], item)
|
||||
else:
|
||||
return binarySearch(olist[midpoint+1:], item)
|
||||
|
||||
def binarySearch(alist, item):
|
||||
|
||||
first = 0
|
||||
last = len(alist) - 1
|
||||
found = False
|
||||
|
||||
while first <= last and not found:
|
||||
midpoint = (first + last) // 2
|
||||
if alist[midpoint] == item:
|
||||
found = True
|
||||
else:
|
||||
if item < alist[midpoint]:
|
||||
last = midpoint - 1
|
||||
else:
|
||||
first = midpoint + 1
|
||||
|
||||
return found
|
||||
|
||||
print(Ordered_binary_Search([0, 1, 3, 8, 14, 18, 19, 34, 52], 3))
|
||||
print(Ordered_binary_Search([0, 1, 3, 8, 14, 18, 19, 34, 52], 17))
|
||||
17
python/Algorithms/Python program for binary search.py
Normal file
17
python/Algorithms/Python program for binary search.py
Normal file
@@ -0,0 +1,17 @@
|
||||
def binary_search(item_list,item):
|
||||
first = 0
|
||||
last = len(item_list)-1
|
||||
found = False
|
||||
while( first<=last and not found):
|
||||
mid = (first + last)//2
|
||||
if item_list[mid] == item :
|
||||
found = True
|
||||
else:
|
||||
if item < item_list[mid]:
|
||||
last = mid - 1
|
||||
else:
|
||||
first = mid + 1
|
||||
return found
|
||||
|
||||
print(binary_search([1,2,3,5,8], 6))
|
||||
print(binary_search([1,2,3,5,8], 5))
|
||||
14
python/Algorithms/Python program for sequential search.py
Normal file
14
python/Algorithms/Python program for sequential search.py
Normal file
@@ -0,0 +1,14 @@
|
||||
def Sequential_Search(dlist, item):
|
||||
|
||||
pos = 0
|
||||
found = False
|
||||
|
||||
while pos < len(dlist) and not found:
|
||||
if dlist[pos] == item:
|
||||
found = True
|
||||
else:
|
||||
pos = pos + 1
|
||||
|
||||
return found, pos
|
||||
|
||||
print(Sequential_Search([11,23,58,31,56,77,43,12,65,19],31))
|
||||
@@ -0,0 +1,26 @@
|
||||
def shellSort(alist):
|
||||
sublistcount = len(alist)//2
|
||||
while sublistcount > 0:
|
||||
for start_position in range(sublistcount):
|
||||
gap_InsertionSort(alist, start_position, sublistcount)
|
||||
|
||||
print("After increments of size",sublistcount, "The list is",nlist)
|
||||
|
||||
sublistcount = sublistcount // 2
|
||||
|
||||
def gap_InsertionSort(nlist,start,gap):
|
||||
for i in range(start+gap,len(nlist),gap):
|
||||
|
||||
current_value = nlist[i]
|
||||
position = i
|
||||
|
||||
while position>=gap and nlist[position-gap]>current_value:
|
||||
nlist[position]=nlist[position-gap]
|
||||
position = position-gap
|
||||
|
||||
nlist[position]=current_value
|
||||
|
||||
|
||||
nlist = [14,46,43,27,57,41,45,21,70]
|
||||
shellSort(nlist)
|
||||
print(nlist)
|
||||
@@ -0,0 +1,11 @@
|
||||
def bubbleSort(nlist):
|
||||
for passnum in range(len(nlist)-1,0,-1):
|
||||
for i in range(passnum):
|
||||
if nlist[i]>nlist[i+1]:
|
||||
temp = nlist[i]
|
||||
nlist[i] = nlist[i+1]
|
||||
nlist[i+1] = temp
|
||||
|
||||
nlist = [14,46,43,27,57,41,45,21,70]
|
||||
bubbleSort(nlist)
|
||||
print(nlist)
|
||||
@@ -0,0 +1,44 @@
|
||||
def quickSort(data_list):
|
||||
quickSortHlp(data_list,0,len(data_list)-1)
|
||||
|
||||
def quickSortHlp(data_list,first,last):
|
||||
if first < last:
|
||||
|
||||
splitpoint = partition(data_list,first,last)
|
||||
|
||||
quickSortHlp(data_list,first,splitpoint-1)
|
||||
quickSortHlp(data_list,splitpoint+1,last)
|
||||
|
||||
|
||||
def partition(data_list,first,last):
|
||||
pivotvalue = data_list[first]
|
||||
|
||||
leftmark = first+1
|
||||
rightmark = last
|
||||
|
||||
done = False
|
||||
while not done:
|
||||
|
||||
while leftmark <= rightmark and data_list[leftmark] <= pivotvalue:
|
||||
leftmark = leftmark + 1
|
||||
|
||||
while data_list[rightmark] >= pivotvalue and rightmark >= leftmark:
|
||||
rightmark = rightmark -1
|
||||
|
||||
if rightmark < leftmark:
|
||||
done = True
|
||||
else:
|
||||
temp = data_list[leftmark]
|
||||
data_list[leftmark] = data_list[rightmark]
|
||||
data_list[rightmark] = temp
|
||||
|
||||
temp = data_list[first]
|
||||
data_list[first] = data_list[rightmark]
|
||||
data_list[rightmark] = temp
|
||||
|
||||
|
||||
return rightmark
|
||||
|
||||
data_list = [54,26,93,17,77,31,44,55,20]
|
||||
quickSort(data_list)
|
||||
print(data_list)
|
||||
@@ -0,0 +1,14 @@
|
||||
def selectionSort(nlist):
|
||||
for fillslot in range(len(nlist)-1,0,-1):
|
||||
maxpos=0
|
||||
for location in range(1,fillslot+1):
|
||||
if nlist[location]>nlist[maxpos]:
|
||||
maxpos = location
|
||||
|
||||
temp = nlist[fillslot]
|
||||
nlist[fillslot] = nlist[maxpos]
|
||||
nlist[maxpos] = temp
|
||||
|
||||
nlist = [14,46,43,27,57,41,45,21,70]
|
||||
selectionSort(nlist)
|
||||
print(nlist)
|
||||
@@ -0,0 +1,20 @@
|
||||
class Point:
|
||||
def __init__(self, x, y):
|
||||
self.x = x
|
||||
self.y = y
|
||||
|
||||
def __lt__(self, other):
|
||||
return self.x < other.x
|
||||
|
||||
def __str__(self):
|
||||
return "(" + str(self.x) + "," + str(self.y) + ")"
|
||||
|
||||
|
||||
def test():
|
||||
points = [Point(2, 1), Point(1, 1)]
|
||||
points.sort()
|
||||
for p in points:
|
||||
print(p)
|
||||
|
||||
|
||||
test()
|
||||
3
python/Algorithms/bigint.py
Normal file
3
python/Algorithms/bigint.py
Normal file
@@ -0,0 +1,3 @@
|
||||
a = 123456789
|
||||
b = a * a * a * a // 3
|
||||
print(b)
|
||||
16
python/Algorithms/binary_exponentiation.py
Normal file
16
python/Algorithms/binary_exponentiation.py
Normal file
@@ -0,0 +1,16 @@
|
||||
# https://en.wikipedia.org/wiki/Exponentiation_by_squaring
|
||||
def pow(a, b, mod):
|
||||
res = 1
|
||||
while b > 0:
|
||||
if b & 1 != 0:
|
||||
res = res * a % mod
|
||||
a = a * a % mod
|
||||
b >>= 1
|
||||
return res
|
||||
|
||||
|
||||
def test():
|
||||
print(1024 == pow(2, 10, 1000000007))
|
||||
|
||||
|
||||
test()
|
||||
49
python/Algorithms/binary_heap.py
Normal file
49
python/Algorithms/binary_heap.py
Normal file
@@ -0,0 +1,49 @@
|
||||
class BinaryHeap:
|
||||
def __init__(self, n):
|
||||
self.heap = [0] * n
|
||||
self.size = 0
|
||||
|
||||
def remove_min(self):
|
||||
removed = self.heap[0]
|
||||
self.size -= 1
|
||||
self.heap[0] = self.heap[self.size]
|
||||
self._down(0)
|
||||
return removed
|
||||
|
||||
def add(self, value):
|
||||
self.heap[self.size] = value
|
||||
self._up(self.size)
|
||||
self.size += 1
|
||||
|
||||
def _up(self, pos):
|
||||
while pos > 0:
|
||||
parent = (pos - 1) // 2
|
||||
if self.heap[pos] >= self.heap[parent]:
|
||||
break
|
||||
self.heap[pos], self.heap[parent] = self.heap[parent], self.heap[pos]
|
||||
pos = parent
|
||||
|
||||
def _down(self, pos):
|
||||
while True:
|
||||
child = 2 * pos + 1
|
||||
if child >= self.size:
|
||||
break
|
||||
if child + 1 < self.size and self.heap[child + 1] < self.heap[child]:
|
||||
child += 1
|
||||
if self.heap[pos] <= self.heap[child]:
|
||||
break
|
||||
self.heap[pos], self.heap[child] = self.heap[child], self.heap[pos]
|
||||
pos = child
|
||||
|
||||
|
||||
def test():
|
||||
h = BinaryHeap(10)
|
||||
h.add(3)
|
||||
h.add(1)
|
||||
h.add(2)
|
||||
print(h.remove_min())
|
||||
print(h.remove_min())
|
||||
print(h.remove_min())
|
||||
|
||||
|
||||
test()
|
||||
17
python/Algorithms/binary_search.py
Normal file
17
python/Algorithms/binary_search.py
Normal file
@@ -0,0 +1,17 @@
|
||||
def binary_search_first_true(predicate, from_inclusive, to_inclusive):
|
||||
lo = from_inclusive - 1
|
||||
hi = to_inclusive + 1
|
||||
while hi - lo > 1:
|
||||
mid = (lo + hi) // 2
|
||||
if not predicate(mid):
|
||||
lo = mid
|
||||
else:
|
||||
hi = mid
|
||||
return hi
|
||||
|
||||
|
||||
def test():
|
||||
assert 4 == binary_search_first_true(lambda x: x * x >= 10, 0, 10)
|
||||
|
||||
|
||||
test()
|
||||
29
python/Algorithms/convex_hull.py
Normal file
29
python/Algorithms/convex_hull.py
Normal file
@@ -0,0 +1,29 @@
|
||||
def convex_hull(points):
|
||||
points = sorted(set(points))
|
||||
|
||||
if len(points) <= 1:
|
||||
return points
|
||||
|
||||
def hull(points):
|
||||
def cross(a, b, c):
|
||||
return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
|
||||
|
||||
res = []
|
||||
for p in points:
|
||||
while len(res) >= 2 and cross(res[-2], res[-1], p) >= 0:
|
||||
res.pop()
|
||||
res.append(p)
|
||||
return res
|
||||
|
||||
return hull(points)[:-1] + hull(reversed(points))[:-1]
|
||||
|
||||
|
||||
def test():
|
||||
import random
|
||||
|
||||
assert convex_hull([(0, 0), (0, 0)]) == [(0, 0)]
|
||||
assert convex_hull([(i // 10, i % 10) for i in range(100)]) == [(0, 0), (0, 9), (9, 9), (9, 0)]
|
||||
print(len(convex_hull([(random.randint(0, 10000), random.randint(0, 10000)) for i in range(10000)])))
|
||||
|
||||
|
||||
test()
|
||||
15
python/Algorithms/count_solutions.py
Normal file
15
python/Algorithms/count_solutions.py
Normal file
@@ -0,0 +1,15 @@
|
||||
def count_solutions(a, b):
|
||||
dp = [0] * (b + 1)
|
||||
dp[0] = 1
|
||||
|
||||
for i in range(len(a)):
|
||||
for j in range(a[i], b + 1):
|
||||
dp[j] += dp[j - a[i]]
|
||||
return dp[b]
|
||||
|
||||
|
||||
def test():
|
||||
print(5 == count_solutions([1, 2, 3], 5))
|
||||
|
||||
|
||||
test()
|
||||
46
python/Algorithms/dijkstra.py
Normal file
46
python/Algorithms/dijkstra.py
Normal file
@@ -0,0 +1,46 @@
|
||||
# https://en.wikipedia.org/wiki/Dijkstra's_algorithm in O(V^2)
|
||||
class Edge:
|
||||
def __init__(self, t, cost):
|
||||
self.t = t
|
||||
self.cost = cost
|
||||
|
||||
|
||||
def dijkstra(graph, s):
|
||||
n = len(graph)
|
||||
pred = [-1] * n
|
||||
prio = [float('inf')] * n
|
||||
prio[s] = 0
|
||||
visited = [False] * n
|
||||
for i in range(n):
|
||||
u = -1
|
||||
for j in range(n):
|
||||
if not visited[j] and (u == -1 or prio[u] > prio[j]):
|
||||
u = j
|
||||
|
||||
if prio[u] == float('inf'):
|
||||
break
|
||||
|
||||
visited[u] = True
|
||||
|
||||
for e in graph[u]:
|
||||
v = e.t
|
||||
nprio = prio[u] + e.cost
|
||||
if prio[v] > nprio:
|
||||
prio[v] = nprio
|
||||
pred[v] = u
|
||||
|
||||
return prio, pred
|
||||
|
||||
|
||||
def test():
|
||||
g = [[] for _ in range(3)]
|
||||
g[0].append(Edge(1, 3))
|
||||
g[0].append(Edge(2, 2))
|
||||
g[1].append(Edge(2, -2))
|
||||
|
||||
dist, pred = dijkstra(g, 0)
|
||||
assert dist == [0, 3, 1]
|
||||
assert pred == [-1, 0, 1]
|
||||
|
||||
|
||||
test()
|
||||
42
python/Algorithms/dijkstra_heap.py
Normal file
42
python/Algorithms/dijkstra_heap.py
Normal file
@@ -0,0 +1,42 @@
|
||||
# https://en.wikipedia.org/wiki/Dijkstra's_algorithm in O(E*log(V))
|
||||
from heapq import *
|
||||
|
||||
|
||||
class Edge:
|
||||
def __init__(self, t, cost):
|
||||
self.t = t
|
||||
self.cost = cost
|
||||
|
||||
|
||||
def dijkstra(graph, s):
|
||||
n = len(graph)
|
||||
pred = [-1] * n
|
||||
prio = [float('inf')] * n
|
||||
prio[s] = 0
|
||||
q = [(0, s)]
|
||||
while q:
|
||||
(prio_u, u) = heappop(q)
|
||||
if prio_u != prio[u]:
|
||||
continue
|
||||
for e in graph[u]:
|
||||
v = e.t
|
||||
nprio = prio[u] + e.cost
|
||||
if prio[v] > nprio:
|
||||
prio[v] = nprio
|
||||
pred[v] = u
|
||||
heappush(q, (nprio, v))
|
||||
return prio, pred
|
||||
|
||||
|
||||
def test():
|
||||
g = [[] for _ in range(3)]
|
||||
g[0].append(Edge(1, 3))
|
||||
g[0].append(Edge(2, 2))
|
||||
g[1].append(Edge(2, -2))
|
||||
|
||||
dist, pred = dijkstra(g, 0)
|
||||
assert dist == [0, 3, 1]
|
||||
assert pred == [-1, 0, 1]
|
||||
|
||||
|
||||
test()
|
||||
34
python/Algorithms/factorize.py
Normal file
34
python/Algorithms/factorize.py
Normal file
@@ -0,0 +1,34 @@
|
||||
def factorize(n):
|
||||
factors = {}
|
||||
d = 2
|
||||
while n > 1:
|
||||
power = 0
|
||||
while n % d == 0:
|
||||
power += 1
|
||||
n //= d
|
||||
if power > 0:
|
||||
factors[d] = power
|
||||
d += 1
|
||||
if d * d > n:
|
||||
d = n
|
||||
return factors
|
||||
|
||||
|
||||
def get_all_divisors(n):
|
||||
divisors = []
|
||||
d = 1
|
||||
while d * d <= n:
|
||||
if n % d == 0:
|
||||
divisors.append(d)
|
||||
if d * d != n:
|
||||
divisors.append(n // d)
|
||||
d += 1
|
||||
return sorted(divisors)
|
||||
|
||||
|
||||
def test():
|
||||
assert factorize(24) == {2: 3, 3: 1}
|
||||
assert get_all_divisors(16) == [1, 2, 4, 8, 16]
|
||||
|
||||
|
||||
test()
|
||||
30
python/Algorithms/fenwick_tree.py
Normal file
30
python/Algorithms/fenwick_tree.py
Normal file
@@ -0,0 +1,30 @@
|
||||
import time
|
||||
|
||||
|
||||
# T[i] += value
|
||||
def add(t, i, value):
|
||||
while i < len(t):
|
||||
t[i] += value
|
||||
i |= i + 1
|
||||
|
||||
|
||||
# sum[0..i]
|
||||
def sum(t, i):
|
||||
res = 0
|
||||
while i >= 0:
|
||||
res += t[i]
|
||||
i = (i & (i + 1)) - 1
|
||||
return res
|
||||
|
||||
|
||||
def test():
|
||||
start = time.time()
|
||||
n = 100000
|
||||
t = [0] * n
|
||||
for i in range(n):
|
||||
add(t, i, 1)
|
||||
assert n == sum(t, n - 1)
|
||||
print(time.time() - start)
|
||||
|
||||
|
||||
test()
|
||||
30
python/Algorithms/max_matching.py
Normal file
30
python/Algorithms/max_matching.py
Normal file
@@ -0,0 +1,30 @@
|
||||
def max_matching(graph):
|
||||
n1 = len(graph)
|
||||
n2 = 0 if n1 == 0 else len(graph[0])
|
||||
matching = [-1] * n2
|
||||
matches = 0
|
||||
for u in range(n1):
|
||||
if find_path(graph, u, matching, [False] * n1):
|
||||
matches += 1
|
||||
return matches
|
||||
|
||||
|
||||
def find_path(graph, u1, matching, vis):
|
||||
vis[u1] = True
|
||||
for v in range(len(matching)):
|
||||
u2 = matching[v]
|
||||
if graph[u1][v] and (u2 == -1 or not vis[u2] and find_path(graph, u2, matching, vis)):
|
||||
matching[v] = u1
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def test():
|
||||
graph = [[False] * 2 for _ in range(2)]
|
||||
graph[0][1] = True
|
||||
graph[1][0] = True
|
||||
graph[1][1] = True
|
||||
assert 2 == max_matching(graph)
|
||||
|
||||
|
||||
test()
|
||||
71
python/Algorithms/maxflow_dinic.py
Normal file
71
python/Algorithms/maxflow_dinic.py
Normal file
@@ -0,0 +1,71 @@
|
||||
# https://en.wikipedia.org/wiki/Dinic%27s_algorithm in O(V^2 * E)
|
||||
|
||||
class Edge:
|
||||
def __init__(self, t, rev, cap):
|
||||
self.t = t
|
||||
self.rev = rev
|
||||
self.cap = cap
|
||||
self.f = 0
|
||||
|
||||
|
||||
def add_edge(graph, s, t, cap):
|
||||
graph[s].append(Edge(t, len(graph[t]), cap))
|
||||
graph[t].append(Edge(s, len(graph[s]) - 1, 0))
|
||||
|
||||
|
||||
def dinic_bfs(graph, src, dest, dist):
|
||||
dist[:] = [-1] * len(dist)
|
||||
dist[src] = 0
|
||||
Q = [0] * len(graph)
|
||||
size_q = 0
|
||||
Q[size_q] = src
|
||||
size_q += 1
|
||||
i = 0
|
||||
while i < size_q:
|
||||
u = Q[i]
|
||||
for e in graph[u]:
|
||||
if dist[e.t] < 0 and e.f < e.cap:
|
||||
dist[e.t] = dist[u] + 1
|
||||
Q[size_q] = e.t
|
||||
size_q += 1
|
||||
i += 1
|
||||
return dist[dest] >= 0
|
||||
|
||||
|
||||
def dinic_dfs(graph, ptr, dist, dest, u, f):
|
||||
if u == dest:
|
||||
return f
|
||||
while ptr[u] < len(graph[u]):
|
||||
e = graph[u][ptr[u]]
|
||||
if dist[e.t] == dist[u] + 1 and e.f < e.cap:
|
||||
df = dinic_dfs(graph, ptr, dist, dest, e.t, min(f, e.cap - e.f))
|
||||
if df > 0:
|
||||
e.f += df
|
||||
graph[e.t][e.rev].f -= df
|
||||
return df
|
||||
ptr[u] += 1
|
||||
return 0
|
||||
|
||||
|
||||
def max_flow(graph, src, dest):
|
||||
flow = 0
|
||||
dist = [0] * len(graph)
|
||||
while dinic_bfs(graph, src, dest, dist):
|
||||
ptr = [0] * len(graph)
|
||||
while True:
|
||||
df = dinic_dfs(graph, ptr, dist, dest, src, float('inf'))
|
||||
if df == 0:
|
||||
break
|
||||
flow += df
|
||||
return flow
|
||||
|
||||
|
||||
def test():
|
||||
graph = [[] for _ in range(3)]
|
||||
add_edge(graph, 0, 1, 3)
|
||||
add_edge(graph, 0, 2, 2)
|
||||
add_edge(graph, 1, 2, 2)
|
||||
assert 4 == max_flow(graph, 0, 2)
|
||||
|
||||
|
||||
test()
|
||||
28
python/Algorithms/maxflow_fordfulkerson_simple.py
Normal file
28
python/Algorithms/maxflow_fordfulkerson_simple.py
Normal file
@@ -0,0 +1,28 @@
|
||||
# https://en.wikipedia.org/wiki/Ford–Fulkerson_algorithm in O(V^2 * flow)
|
||||
|
||||
|
||||
def max_flow(cap, s, t):
|
||||
def augment_path(cap, visited, i, t):
|
||||
if i == t:
|
||||
return True
|
||||
visited[i] = True
|
||||
for j in range(len(cap)):
|
||||
if not visited[j] and cap[i][j] > 0 and augment_path(cap, visited, j, t):
|
||||
cap[i][j] -= 1
|
||||
cap[j][i] += 1
|
||||
return True
|
||||
return False
|
||||
|
||||
flow = 0
|
||||
while True:
|
||||
if not augment_path(cap, [False] * len(cap), s, t):
|
||||
return flow
|
||||
flow += 1
|
||||
|
||||
|
||||
def test():
|
||||
capacity = [[0, 1, 1, 0], [1, 0, 1, 1], [1, 1, 0, 1], [0, 1, 1, 0]]
|
||||
assert max_flow(capacity, 0, 3) == 2
|
||||
|
||||
|
||||
test()
|
||||
107
python/Algorithms/min_cost_flow.py
Normal file
107
python/Algorithms/min_cost_flow.py
Normal file
@@ -0,0 +1,107 @@
|
||||
# https://en.wikipedia.org/wiki/Minimum-cost_flow_problem in O(V^2 * E)
|
||||
from heapq import *
|
||||
|
||||
|
||||
class Edge:
|
||||
def __init__(self, to, cap, cost, rev):
|
||||
self.to = to
|
||||
self.cap = cap
|
||||
self.cost = cost
|
||||
self.rev = rev
|
||||
self.f = 0
|
||||
|
||||
|
||||
def add_edge(graph, s, t, cap, cost):
|
||||
graph[s].append(Edge(t, cap, cost, len(graph[t])))
|
||||
graph[t].append(Edge(s, 0, -cost, len(graph[s]) - 1))
|
||||
|
||||
|
||||
def bellman_ford(graph, s, dist):
|
||||
n = len(graph)
|
||||
dist[:] = [float('inf')] * n
|
||||
dist[s] = 0
|
||||
inqueue = [False] * n
|
||||
q = [0] * n
|
||||
qt = 0
|
||||
q[qt] = s
|
||||
qt += 1
|
||||
qh = 0
|
||||
while (qh - qt) % n != 0:
|
||||
u = q[qh % n]
|
||||
inqueue[u] = False
|
||||
for i in range(len(graph[u])):
|
||||
e = graph[u][i]
|
||||
if e.cap <= e.f:
|
||||
continue
|
||||
v = e.to
|
||||
ndist = dist[u] + e.cost
|
||||
if dist[v] > ndist:
|
||||
dist[v] = ndist
|
||||
if not inqueue[v]:
|
||||
inqueue[v] = True
|
||||
q[qt % n] = v
|
||||
qt += 1
|
||||
qh += 1
|
||||
|
||||
|
||||
def min_cost_flow(graph, s, t, maxf):
|
||||
n = len(graph)
|
||||
prio = [0] * n
|
||||
curflow = [0] * n
|
||||
prevedge = [0] * n
|
||||
prevnode = [0] * n
|
||||
pot = [0] * n
|
||||
|
||||
bellman_ford(graph, s, pot) # bellmanFord invocation can be skipped if edges costs are non-negative
|
||||
flow = 0
|
||||
flow_cost = 0
|
||||
while flow < maxf:
|
||||
q = [(0, s)]
|
||||
prio[:] = [float('inf')] * n
|
||||
prio[s] = 0
|
||||
finished = [False] * n
|
||||
curflow[s] = float('inf')
|
||||
while not finished[t] and q:
|
||||
(prio_u, u) = heappop(q)
|
||||
if prio_u != prio[u]:
|
||||
continue
|
||||
finished[u] = True
|
||||
for i in range(len(graph[u])):
|
||||
e = graph[u][i]
|
||||
if e.f >= e.cap:
|
||||
continue
|
||||
v = e.to
|
||||
nprio = prio[u] + e.cost + pot[u] - pot[v]
|
||||
if prio[v] > nprio:
|
||||
prio[v] = nprio
|
||||
heappush(q, (nprio, v))
|
||||
prevnode[v] = u
|
||||
prevedge[v] = i
|
||||
curflow[v] = min(curflow[u], e.cap - e.f)
|
||||
if prio[t] == float('inf'):
|
||||
break
|
||||
for i in range(n):
|
||||
if finished[i]:
|
||||
pot[i] += prio[i] - prio[t]
|
||||
df = min(curflow[t], maxf - flow)
|
||||
flow += df
|
||||
v = t
|
||||
while v != s:
|
||||
e = graph[prevnode[v]][prevedge[v]]
|
||||
e.f += df
|
||||
graph[v][e.rev].f -= df
|
||||
flow_cost += df * e.cost
|
||||
v = prevnode[v]
|
||||
return flow, flow_cost
|
||||
|
||||
|
||||
def test():
|
||||
graph = [[] for _ in range(3)]
|
||||
|
||||
add_edge(graph, 0, 1, 3, 1)
|
||||
add_edge(graph, 0, 2, 2, 1)
|
||||
add_edge(graph, 1, 2, 2, 1)
|
||||
assert (4, 6) == min_cost_flow(graph, 0, 2, float('inf'))
|
||||
|
||||
|
||||
test()
|
||||
17
python/Algorithms/permutations.py
Normal file
17
python/Algorithms/permutations.py
Normal file
@@ -0,0 +1,17 @@
|
||||
def generate_permutations(p, depth):
|
||||
n = len(p)
|
||||
if depth == n:
|
||||
yield p
|
||||
for i in range(n):
|
||||
if p[i] == 0:
|
||||
p[i] = depth
|
||||
yield from generate_permutations(p, depth + 1)
|
||||
p[i] = 0
|
||||
|
||||
|
||||
def test():
|
||||
for p in generate_permutations([0] * 3, 1):
|
||||
print(p)
|
||||
|
||||
|
||||
test()
|
||||
6
python/Algorithms/plot.py
Normal file
6
python/Algorithms/plot.py
Normal file
@@ -0,0 +1,6 @@
|
||||
from cmath import sin
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
plt.plot([sin(x) for x in range(100)])
|
||||
plt.show()
|
||||
15
python/Algorithms/primes.py
Normal file
15
python/Algorithms/primes.py
Normal file
@@ -0,0 +1,15 @@
|
||||
def generate_primes(n):
|
||||
sieve = [False, False] + [True] * (n - 1)
|
||||
i = 2
|
||||
while i * i <= n:
|
||||
if sieve[i]:
|
||||
sieve[2 * i::i] = [False] * (n // i - 1)
|
||||
i += 1
|
||||
return [i for i in range(len(sieve)) if sieve[i]]
|
||||
|
||||
|
||||
def test():
|
||||
print(generate_primes(10))
|
||||
|
||||
|
||||
test()
|
||||
4
python/Algorithms/read_file.py
Normal file
4
python/Algorithms/read_file.py
Normal file
@@ -0,0 +1,4 @@
|
||||
file = open("input.txt", "r")
|
||||
for line in file:
|
||||
print(line)
|
||||
file.close()
|
||||
35
python/Algorithms/segment_tree_simple.py
Normal file
35
python/Algorithms/segment_tree_simple.py
Normal file
@@ -0,0 +1,35 @@
|
||||
def get(t, i):
|
||||
return t[i + len(t) // 2]
|
||||
|
||||
|
||||
def add(t, i, value):
|
||||
i += len(t) // 2
|
||||
t[i] += value
|
||||
while i > 1:
|
||||
t[i >> 1] = max(t[i], t[i ^ 1])
|
||||
i >>= 1
|
||||
|
||||
|
||||
def max_value(t, a, b):
|
||||
res = float('-inf')
|
||||
a += len(t) // 2
|
||||
b += len(t) // 2
|
||||
while a <= b:
|
||||
if (a & 1) != 0:
|
||||
res = max(res, t[a])
|
||||
if (b & 1) == 0:
|
||||
res = max(res, t[b])
|
||||
a = (a + 1) >> 1
|
||||
b = (b - 1) >> 1
|
||||
return res
|
||||
|
||||
|
||||
def test():
|
||||
n = 10
|
||||
t = [0] * (2 * n)
|
||||
add(t, 0, 1)
|
||||
add(t, 9, 2)
|
||||
assert 2 == max_value(t, 0, 9)
|
||||
|
||||
|
||||
test()
|
||||
34
python/Algorithms/string_distances.py
Normal file
34
python/Algorithms/string_distances.py
Normal file
@@ -0,0 +1,34 @@
|
||||
# https://en.wikipedia.org/wiki/Levenshtein_distance
|
||||
import time
|
||||
import random
|
||||
|
||||
|
||||
def levenstein_distance(a, b):
|
||||
m = len(a)
|
||||
n = len(b)
|
||||
dp = [[0] * (n + 1) for i in range(m + 1)]
|
||||
for i in range(m + 1):
|
||||
dp[i][0] = i
|
||||
for j in range(n + 1):
|
||||
dp[0][j] = j
|
||||
for i in range(m):
|
||||
for j in range(n):
|
||||
if a[i] == b[j]:
|
||||
dp[i + 1][j + 1] = dp[i][j]
|
||||
else:
|
||||
dp[i + 1][j + 1] = 1 + min(dp[i][j], dp[i + 1][j], dp[i][j + 1])
|
||||
return dp[m][n]
|
||||
|
||||
|
||||
def test():
|
||||
start = time.time()
|
||||
print(levenstein_distance('abc', 'ab'))
|
||||
print(levenstein_distance(random_string(1000), random_string(1000)))
|
||||
print(time.time() - start)
|
||||
|
||||
|
||||
def random_string(len):
|
||||
return ''.join(random.choice('ab') for _ in range(len))
|
||||
|
||||
|
||||
test()
|
||||
31
python/Algorithms/topological_sort.py
Normal file
31
python/Algorithms/topological_sort.py
Normal file
@@ -0,0 +1,31 @@
|
||||
# https://en.wikipedia.org/wiki/Topological_sorting
|
||||
|
||||
|
||||
def topological_sort(graph):
|
||||
def dfs(graph, used, order, u):
|
||||
used[u] = True
|
||||
for v in graph[u]:
|
||||
if not used[v]:
|
||||
dfs(graph, used, order, v)
|
||||
order.append(u)
|
||||
|
||||
n = len(graph)
|
||||
used = [False] * n
|
||||
order = []
|
||||
for i in range(n):
|
||||
if not used[i]:
|
||||
dfs(graph, used, order, i)
|
||||
|
||||
return order[::-1]
|
||||
|
||||
|
||||
def test():
|
||||
g = [[] for _ in range(3)]
|
||||
g[2].append(0)
|
||||
g[2].append(1)
|
||||
g[0].append(1)
|
||||
|
||||
assert topological_sort(g) == [2, 0, 1]
|
||||
|
||||
|
||||
test()
|
||||
104
python/Algorithms/treap_bst.py
Normal file
104
python/Algorithms/treap_bst.py
Normal file
@@ -0,0 +1,104 @@
|
||||
# https://en.wikipedia.org/wiki/Treap
|
||||
|
||||
import random
|
||||
|
||||
import time
|
||||
|
||||
|
||||
class Treap:
|
||||
def __init__(self, key):
|
||||
self.key = key
|
||||
self.prio = random.randint(0, 1000000000)
|
||||
self.size = 1
|
||||
self.left = None
|
||||
self.right = None
|
||||
|
||||
def update(self):
|
||||
self.size = 1 + size(self.left) + size(self.right)
|
||||
|
||||
|
||||
def size(treap):
|
||||
return 0 if treap is None else treap.size
|
||||
|
||||
|
||||
def split(root, minRight):
|
||||
if root is None:
|
||||
return None, None
|
||||
if root.key >= minRight:
|
||||
left, right = split(root.left, minRight)
|
||||
root.left = right
|
||||
root.update()
|
||||
return left, root
|
||||
else:
|
||||
left, right = split(root.right, minRight)
|
||||
root.right = left
|
||||
root.update()
|
||||
return root, right
|
||||
|
||||
|
||||
def merge(left, right):
|
||||
if left is None:
|
||||
return right
|
||||
if right is None:
|
||||
return left
|
||||
if left.prio > right.prio:
|
||||
left.right = merge(left.right, right)
|
||||
left.update()
|
||||
return left
|
||||
else:
|
||||
right.left = merge(left, right.left)
|
||||
right.update()
|
||||
return right
|
||||
|
||||
|
||||
def insert(root, key):
|
||||
left, right = split(root, key)
|
||||
return merge(merge(left, Treap(key)), right)
|
||||
|
||||
|
||||
def remove(root, key):
|
||||
left, right = split(root, key)
|
||||
return merge(left, split(right, key + 1)[1])
|
||||
|
||||
|
||||
def kth(root, k):
|
||||
if k < size(root.left):
|
||||
return kth(root.left, k)
|
||||
elif k > size(root.left):
|
||||
return kth(root.right, k - size(root.left) - 1)
|
||||
return root.key
|
||||
|
||||
|
||||
def print_treap(root):
|
||||
def dfs_print(root):
|
||||
if root is None:
|
||||
return
|
||||
dfs_print(root.left)
|
||||
print(str(root.key) + ' ', end='')
|
||||
dfs_print(root.right)
|
||||
|
||||
dfs_print(root)
|
||||
print()
|
||||
|
||||
|
||||
def test():
|
||||
start = time.time()
|
||||
treap = None
|
||||
s = set()
|
||||
for i in range(100000):
|
||||
key = random.randint(0, 10000)
|
||||
if random.randint(0, 1) == 0:
|
||||
if key in s:
|
||||
treap = remove(treap, key)
|
||||
s.remove(key)
|
||||
elif key not in s:
|
||||
treap = insert(treap, key)
|
||||
s.add(key)
|
||||
assert len(s) == size(treap)
|
||||
|
||||
for i in range(size(treap)):
|
||||
assert kth(treap, i) in s
|
||||
print(time.time() - start)
|
||||
|
||||
|
||||
test()
|
||||
@@ -0,0 +1,13 @@
|
||||
class Circle():
|
||||
def __init__(self, r):
|
||||
self.radius = r
|
||||
|
||||
def area(self):
|
||||
return self.radius**2*3.14
|
||||
|
||||
def perimeter(self):
|
||||
return 2*self.radius*3.14
|
||||
|
||||
NewCircle = Circle(8)
|
||||
print(NewCircle.area())
|
||||
print(NewCircle.perimeter())
|
||||
@@ -0,0 +1,10 @@
|
||||
class Rectangle():
|
||||
def __init__(self, l, w):
|
||||
self.length = l
|
||||
self.width = w
|
||||
|
||||
def rectangle_area(self):
|
||||
return self.length*self.width
|
||||
|
||||
newRectangle = Rectangle(12, 10)
|
||||
print(newRectangle.rectangle_area())
|
||||
@@ -0,0 +1,13 @@
|
||||
class IOString():
|
||||
def __init__(self):
|
||||
self.str1 = ""
|
||||
|
||||
def get_String(self):
|
||||
self.str1 = input()
|
||||
|
||||
def print_String(self):
|
||||
print(self.str1.upper())
|
||||
|
||||
str1 = IOString()
|
||||
str1.get_String()
|
||||
str1.print_String()
|
||||
@@ -0,0 +1,14 @@
|
||||
class py_solution:
|
||||
def roman_to_int(self, s):
|
||||
rom_val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
|
||||
int_val = 0
|
||||
for i in range(len(s)):
|
||||
if i > 0 and rom_val[s[i]] > rom_val[s[i - 1]]:
|
||||
int_val += rom_val[s[i]] - 2 * rom_val[s[i - 1]]
|
||||
else:
|
||||
int_val += rom_val[s[i]]
|
||||
return int_val
|
||||
|
||||
print(py_solution().roman_to_int('MMMCMLXXXVI'))
|
||||
print(py_solution().roman_to_int('MMMM'))
|
||||
print(py_solution().roman_to_int('C'))
|
||||
@@ -0,0 +1,26 @@
|
||||
class py_solution:
|
||||
def int_to_Roman(self, num):
|
||||
val = [
|
||||
1000, 900, 500, 400,
|
||||
100, 90, 50, 40,
|
||||
10, 9, 5, 4,
|
||||
1
|
||||
]
|
||||
syb = [
|
||||
"M", "CM", "D", "CD",
|
||||
"C", "XC", "L", "XL",
|
||||
"X", "IX", "V", "IV",
|
||||
"I"
|
||||
]
|
||||
roman_num = ''
|
||||
i = 0
|
||||
while num > 0:
|
||||
for _ in range(num // val[i]):
|
||||
roman_num += syb[i]
|
||||
num -= val[i]
|
||||
i += 1
|
||||
return roman_num
|
||||
|
||||
|
||||
print(py_solution().int_to_Roman(1))
|
||||
print(py_solution().int_to_Roman(4000))
|
||||
@@ -0,0 +1,8 @@
|
||||
class py_solution:
|
||||
def twoSum(self, nums, target):
|
||||
lookup = {}
|
||||
for i, num in enumerate(nums):
|
||||
if target - num in lookup:
|
||||
return (lookup[target - num] + 1, i + 1)
|
||||
lookup[num] = i
|
||||
print("index1=%d, index2=%d" % py_solution().twoSum((10,20,10,40,50,60,70),50))
|
||||
@@ -0,0 +1,23 @@
|
||||
class py_solution:
|
||||
def threeSum(self, nums):
|
||||
nums, result, i = sorted(nums), [], 0
|
||||
while i < len(nums) - 2:
|
||||
j, k = i + 1, len(nums) - 1
|
||||
while j < k:
|
||||
if nums[i] + nums[j] + nums[k] < 0:
|
||||
j += 1
|
||||
elif nums[i] + nums[j] + nums[k] > 0:
|
||||
k -= 1
|
||||
else:
|
||||
result.append([nums[i], nums[j], nums[k]])
|
||||
j, k = j + 1, k - 1
|
||||
while j < k and nums[j] == nums[j - 1]:
|
||||
j += 1
|
||||
while j < k and nums[k] == nums[k + 1]:
|
||||
k -= 1
|
||||
i += 1
|
||||
while i < len(nums) - 2 and nums[i] == nums[i - 1]:
|
||||
i += 1
|
||||
return result
|
||||
|
||||
print(py_solution().threeSum([-25, -10, -7, -3, 2, 4, 8, 10]))
|
||||
@@ -0,0 +1,13 @@
|
||||
class py_solution:
|
||||
def is_valid_parenthese(self, str1):
|
||||
stack, pchar = [], {"(": ")", "{": "}", "[": "]"}
|
||||
for parenthese in str1:
|
||||
if parenthese in pchar:
|
||||
stack.append(parenthese)
|
||||
elif len(stack) == 0 or pchar[stack.pop()] != parenthese:
|
||||
return False
|
||||
return len(stack) == 0
|
||||
|
||||
print(py_solution().is_valid_parenthese("(){}[]"))
|
||||
print(py_solution().is_valid_parenthese("()[{)}"))
|
||||
print(py_solution().is_valid_parenthese("()"))
|
||||
@@ -0,0 +1,10 @@
|
||||
class py_solution:
|
||||
def sub_sets(self, sset):
|
||||
return self.subsetsRecur([], sorted(sset))
|
||||
|
||||
def subsetsRecur(self, current, sset):
|
||||
if sset:
|
||||
return self.subsetsRecur(current, sset[1:]) + self.subsetsRecur(current + [sset[0]], sset[1:])
|
||||
return [current]
|
||||
|
||||
print(py_solution().sub_sets([4,5,6]))
|
||||
22
python/Class/Python program to implement pow(x, n).py
Normal file
22
python/Class/Python program to implement pow(x, n).py
Normal file
@@ -0,0 +1,22 @@
|
||||
class py_solution:
|
||||
def pow(self, x, n):
|
||||
if x==0 or x==1 or n==1:
|
||||
return x
|
||||
|
||||
if x==-1:
|
||||
if n%2 ==0:
|
||||
return 1
|
||||
else:
|
||||
return -1
|
||||
if n==0:
|
||||
return 1
|
||||
if n<0:
|
||||
return 1/self.pow(x,-n)
|
||||
val = self.pow(x,n//2)
|
||||
if n%2 ==0:
|
||||
return val*val
|
||||
return val*val*x
|
||||
|
||||
print(py_solution().pow(2, -3));
|
||||
print(py_solution().pow(3, 5));
|
||||
print(py_solution().pow(100, 0));
|
||||
@@ -0,0 +1,6 @@
|
||||
class py_solution:
|
||||
def reverse_words(self, s):
|
||||
return ' '.join(reversed(s.split()))
|
||||
|
||||
|
||||
print(py_solution().reverse_words('hello .py'))
|
||||
11
python/Date/Calculate a number of days between two dates.py
Normal file
11
python/Date/Calculate a number of days between two dates.py
Normal file
@@ -0,0 +1,11 @@
|
||||
import datetime
|
||||
from datetime import date
|
||||
def differ_days(date1, date2):
|
||||
|
||||
a = date1
|
||||
b = date2
|
||||
return (a-b).days
|
||||
print()
|
||||
print(differ_days((date(2016,10,12)), date(2015,12,10)))
|
||||
print(differ_days((date(2016,3,23)), date(2017,12,10)))
|
||||
print()
|
||||
9
python/Date/Calculate an age in year.py
Normal file
9
python/Date/Calculate an age in year.py
Normal file
@@ -0,0 +1,9 @@
|
||||
from datetime import date
|
||||
|
||||
def calculate_age(dtob):
|
||||
today = date.today()
|
||||
return today.year - dtob.year - ((today.month, today.day) < (dtob.month, dtob.day))
|
||||
print()
|
||||
print(calculate_age(date(2006,10,12)))
|
||||
print(calculate_age(date(1989,1,12)))
|
||||
print()
|
||||
@@ -0,0 +1,11 @@
|
||||
import datetime
|
||||
from datetime import datetime
|
||||
|
||||
def differ_days(date1, date2):
|
||||
a = date1
|
||||
b = date2
|
||||
return (a-b).days
|
||||
print()
|
||||
print(differ_days((datetime(2016,10,12,0,0,0)), datetime(2015,12,10,0,0,0)))
|
||||
print(differ_days((datetime(2016,10,12,0,0,0)), datetime(2015,12,10,23,59,59)))
|
||||
print()
|
||||
10
python/Date/Calculate two date difference in seconds.py
Normal file
10
python/Date/Calculate two date difference in seconds.py
Normal file
@@ -0,0 +1,10 @@
|
||||
from datetime import datetime, time
|
||||
def date_diff_in_Seconds(dt2, dt1):
|
||||
timedelta = dt2 - dt1
|
||||
return timedelta.days * 24 * 3600 + timedelta.seconds
|
||||
#Specified date
|
||||
date1 = datetime.strptime('2015-01-01 01:00:00', '%Y-%m-%d %H:%M:%S')
|
||||
#Current date
|
||||
date2 = datetime.now()
|
||||
print("\n%d seconds" %(date_diff_in_Seconds(date2, date1)))
|
||||
print()
|
||||
@@ -0,0 +1,2 @@
|
||||
import datetime
|
||||
print((datetime.date.today() + datetime.timedelta(6*365/12)).isoformat())
|
||||
6
python/Date/Convert a date to Unix timestamp.py
Normal file
6
python/Date/Convert a date to Unix timestamp.py
Normal file
@@ -0,0 +1,6 @@
|
||||
import datetime
|
||||
import time
|
||||
dt = datetime.datetime(2016, 2, 25, 23, 23)
|
||||
print()
|
||||
print("Unix Timestamp: ",(time.mktime(dt.timetuple())))
|
||||
print()
|
||||
6
python/Date/Convert a date to timestamp.py
Normal file
6
python/Date/Convert a date to timestamp.py
Normal file
@@ -0,0 +1,6 @@
|
||||
import time
|
||||
import datetime
|
||||
now = datetime.datetime.now()
|
||||
print()
|
||||
print(time.mktime(now.timetuple()))
|
||||
print()
|
||||
6
python/Date/Convert a string date to the timestamp.py
Normal file
6
python/Date/Convert a string date to the timestamp.py
Normal file
@@ -0,0 +1,6 @@
|
||||
import time
|
||||
import datetime
|
||||
s = "01/10/2016"
|
||||
print()
|
||||
print(time.mktime(datetime.datetime.strptime(s, "%d/%m/%Y").timetuple()))
|
||||
print()
|
||||
6
python/Date/Convert a string into datetime.py
Normal file
6
python/Date/Convert a string into datetime.py
Normal file
@@ -0,0 +1,6 @@
|
||||
from datetime import datetime
|
||||
|
||||
date_obj = datetime.strptime('May 12 2016 2:25AM', '%b %d %Y %I:%M%p')
|
||||
print()
|
||||
print(date_obj)
|
||||
print()
|
||||
@@ -0,0 +1,10 @@
|
||||
import datetime
|
||||
def every_20_days(date):
|
||||
print('Starting Date: {d}'.format(d=date))
|
||||
print("Next 12 days :")
|
||||
for _ in range(12):
|
||||
date=date+datetime.timedelta(days=20)
|
||||
print('{d}'.format(d=date))
|
||||
|
||||
dt = datetime.date(2016,8,1)
|
||||
every_20_days(dt)
|
||||
@@ -0,0 +1,3 @@
|
||||
import calendar
|
||||
htmlcal = calendar.HTMLCalendar(calendar.MONDAY)
|
||||
print(htmlcal.formatmonth(2020, 12))
|
||||
3
python/Date/Display a calendar for a locale.py
Normal file
3
python/Date/Display a calendar for a locale.py
Normal file
@@ -0,0 +1,3 @@
|
||||
import calendar
|
||||
cal = calendar.LocaleTextCalendar(locale='en_AU.utf8')
|
||||
print(cal.prmonth(2025, 9))
|
||||
@@ -0,0 +1,18 @@
|
||||
import calendar
|
||||
# Show every month
|
||||
for month in range(1, 13):
|
||||
cal = calendar.monthcalendar(2020, month)
|
||||
first_week = cal[0]
|
||||
second_week = cal[1]
|
||||
third_week = cal[2]
|
||||
|
||||
# If a Saturday presents in the first week, the second Saturday
|
||||
# is in the second week. Otherwise, the second Saturday must
|
||||
# be in the third week.
|
||||
|
||||
if first_week[calendar.THURSDAY]:
|
||||
holi_day = second_week[calendar.THURSDAY]
|
||||
else:
|
||||
holi_day = third_week[calendar.THURSDAY]
|
||||
|
||||
print('%3s: %2s' % (calendar.month_abbr[month], holi_day))
|
||||
@@ -0,0 +1,37 @@
|
||||
import calendar
|
||||
print('Print a calendar for a year and month:')
|
||||
month = int(input('Month (mm): '))
|
||||
year = int(input('Year (yyyy): '))
|
||||
print('\n')
|
||||
|
||||
calendar.setfirstweekday(calendar.SUNDAY)
|
||||
cal = calendar.monthcalendar(year, month)
|
||||
|
||||
if len(str(month)) == 1:
|
||||
month = '0%s' % month
|
||||
|
||||
# Header
|
||||
print('|++++++ %s-%s +++++|' % (month, year))
|
||||
print('|Su Mo Tu We Th Fr Sa|')
|
||||
print('|--------------------|')
|
||||
|
||||
# display calendar
|
||||
border = '|'
|
||||
for week in cal:
|
||||
line = border
|
||||
|
||||
|
||||
for day in week:
|
||||
if day == 0:
|
||||
# 3 spaces for blank days
|
||||
line += ' '
|
||||
elif len(str(day)) == 1:
|
||||
line += ' %d ' % day
|
||||
else:
|
||||
line += '%d ' % day
|
||||
# remove space in last column
|
||||
line = line[0:len(line) - 1]
|
||||
line += border
|
||||
print(line)
|
||||
|
||||
print('|--------------------|\n')
|
||||
@@ -0,0 +1,4 @@
|
||||
import calendar
|
||||
cal = calendar.TextCalendar(calendar.SUNDAY)
|
||||
print('First Month - 2022')
|
||||
print(cal.prmonth(2022, 1))
|
||||
@@ -0,0 +1,4 @@
|
||||
import time
|
||||
print()
|
||||
print(time.ctime())
|
||||
print()
|
||||
5
python/Date/Drop microseconds from datetime.py
Normal file
5
python/Date/Drop microseconds from datetime.py
Normal file
@@ -0,0 +1,5 @@
|
||||
import datetime
|
||||
dt = datetime.datetime.today().replace(microsecond=0)
|
||||
print()
|
||||
print(dt)
|
||||
print()
|
||||
@@ -0,0 +1,2 @@
|
||||
import time
|
||||
print(time.asctime(time.strptime('2015 50 1', '%Y %W %w')))
|
||||
5
python/Date/Generate RFC 3339 timestamp.py
Normal file
5
python/Date/Generate RFC 3339 timestamp.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from datetime import datetime, timezone
|
||||
local_time = datetime.now(timezone.utc).astimezone()
|
||||
print()
|
||||
print(local_time.isoformat())
|
||||
print()
|
||||
9
python/Date/Generate a date and times as a string.py
Normal file
9
python/Date/Generate a date and times as a string.py
Normal file
@@ -0,0 +1,9 @@
|
||||
import datetime
|
||||
# Current time
|
||||
now = datetime.datetime.now()
|
||||
# Make a note of the date and time in a string
|
||||
# Date and time in string : 2016-11-05 11:24:24 PM
|
||||
datestr = "# In string: " + now.strftime("%Y-%m-%d %H:%M:%S %p") + "\n"
|
||||
print()
|
||||
print(datestr)
|
||||
print()
|
||||
10
python/Date/Get a list of dates between two dates.py
Normal file
10
python/Date/Get a list of dates between two dates.py
Normal file
@@ -0,0 +1,10 @@
|
||||
from datetime import timedelta, date
|
||||
|
||||
def daterange(date1, date2):
|
||||
for n in range(int ((date2 - date1).days)+1):
|
||||
yield date1 + timedelta(n)
|
||||
|
||||
start_dt = date(2015, 12, 20)
|
||||
end_dt = date(2016, 1, 11)
|
||||
for dt in daterange(start_dt, end_dt):
|
||||
print(dt.strftime("%Y-%m-%d"))
|
||||
34
python/Date/Get last modified information of a file.py
Normal file
34
python/Date/Get last modified information of a file.py
Normal file
@@ -0,0 +1,34 @@
|
||||
import os, time
|
||||
def last_modified_fileinfo(filepath):
|
||||
|
||||
filestat = os.stat(filepath)
|
||||
date = time.localtime((filestat.st_mtime))
|
||||
|
||||
# Extract year, month and day from the date
|
||||
year = date[0]
|
||||
month = date[1]
|
||||
day = date[2]
|
||||
# Extract hour, minute, second
|
||||
hour = date[3]
|
||||
minute = date[4]
|
||||
second = date[5]
|
||||
|
||||
# Year
|
||||
strYear = str(year)[0:]
|
||||
|
||||
# Month
|
||||
if (month <=9):
|
||||
strMonth = '0' + str(month)
|
||||
else:
|
||||
strMonth = str(month)
|
||||
|
||||
# Date
|
||||
if (day <=9):
|
||||
strDay = '0' + str(day)
|
||||
else:
|
||||
strDay = str(day)
|
||||
|
||||
return (strYear+"-"+strMonth+"-"+strDay+" "+str(hour)+":"+str(minute)+":"+str(second))
|
||||
print()
|
||||
print(last_modified_fileinfo('test.txt'))
|
||||
print()
|
||||
4
python/Date/Get the GMT and local current time.py
Normal file
4
python/Date/Get the GMT and local current time.py
Normal file
@@ -0,0 +1,4 @@
|
||||
from time import gmtime, strftime
|
||||
import time
|
||||
print("\nGMT: "+time.strftime("%a, %d %b %Y %I:%M:%S %p %Z", time.gmtime()))
|
||||
print("Local: "+strftime("%a, %d %b %Y %I:%M:%S %p %Z\n"))
|
||||
15
python/Date/Get the current date time information.py
Normal file
15
python/Date/Get the current date time information.py
Normal file
@@ -0,0 +1,15 @@
|
||||
import time
|
||||
import datetime
|
||||
|
||||
print()
|
||||
print("Time in seconds since the epoch: %s" %time.time())
|
||||
print("Current date and time: " , datetime.datetime.now())
|
||||
print("Alternate date and time: " ,datetime.datetime.now().strftime("%y-%m-%d-%H-%M"))
|
||||
print("Current year: ", datetime.date.today().strftime("%Y"))
|
||||
print("Month of year: ", datetime.date.today().strftime("%B"))
|
||||
print("Week number of the year: ", datetime.date.today().strftime("%W"))
|
||||
print("Weekday of the week: ", datetime.date.today().strftime("%w"))
|
||||
print("Day of year: ", datetime.date.today().strftime("%j"))
|
||||
print("Day of the month : ", datetime.date.today().strftime("%d"))
|
||||
print("Day of week: ", datetime.date.today().strftime("%A"))
|
||||
print()
|
||||
6
python/Date/Get the current week.py
Normal file
6
python/Date/Get the current week.py
Normal file
@@ -0,0 +1,6 @@
|
||||
import datetime
|
||||
Jan1st = datetime.date(2017,10,12)
|
||||
year,week_num,day_of_week = Jan1st.isocalendar() # DOW = day of week
|
||||
print()
|
||||
print("Year %d, Week Number %d, Day of the Week %d" %(year,week_num, day_of_week))
|
||||
print()
|
||||
@@ -0,0 +1,9 @@
|
||||
from datetime import date, timedelta
|
||||
|
||||
current_date = date.today().isoformat()
|
||||
days_before = (date.today()-timedelta(days=30)).isoformat()
|
||||
days_after = (date.today()+timedelta(days=30)).isoformat()
|
||||
|
||||
print("\nCurrent Date: ",current_date)
|
||||
print("30 days before current date: ",days_before)
|
||||
print("30 days after current date : ",days_after)
|
||||
3
python/Date/Get the first and last second.py
Normal file
3
python/Date/Get the first and last second.py
Normal file
@@ -0,0 +1,3 @@
|
||||
import datetime
|
||||
print("First Second: ", datetime.time.min)
|
||||
print("Last Second: ", datetime.time.max)
|
||||
@@ -0,0 +1,6 @@
|
||||
import calendar
|
||||
cal = calendar.TextCalendar(calendar.SUNDAY)
|
||||
# year: 2022, column width: 2, lines per week: 1
|
||||
# number of spaces between month columns: 1
|
||||
# 3: no. of months per column.
|
||||
print(cal.formatyear(2022, 2, 1, 1, 3))
|
||||
@@ -0,0 +1,7 @@
|
||||
import time
|
||||
x=0
|
||||
print("\nw3resource will print five times, delay for three seconds.")
|
||||
while x<5:
|
||||
print("w3resource")
|
||||
time.sleep(3)
|
||||
x=x+1
|
||||
@@ -0,0 +1,5 @@
|
||||
from datetime import date, timedelta
|
||||
import calendar
|
||||
start_date = date(2014, 12, 25)
|
||||
days_in_month = calendar.monthrange(start_date.year, start_date.month)[1]
|
||||
print(start_date + timedelta(days=days_in_month))
|
||||
@@ -0,0 +1,9 @@
|
||||
import datetime
|
||||
from datetime import datetime
|
||||
monday1 = 0
|
||||
months = range(1,13)
|
||||
for year in range(2015, 2017):
|
||||
for month in months:
|
||||
if datetime(year, month, 1).weekday() == 0:
|
||||
monday1 += 1
|
||||
print(monday1)
|
||||
4
python/Date/Program to get days between two dates.py
Normal file
4
python/Date/Program to get days between two dates.py
Normal file
@@ -0,0 +1,4 @@
|
||||
from datetime import date
|
||||
a = date(2000,2,28)
|
||||
b = date(2001,2,28)
|
||||
print(b-a)
|
||||
@@ -0,0 +1,6 @@
|
||||
from datetime import date
|
||||
from datetime import timedelta
|
||||
today = date.today()
|
||||
offset = (today.weekday() - 1) % 7
|
||||
last_tuesday = today - timedelta(days=offset)
|
||||
print(last_tuesday)
|
||||
@@ -0,0 +1,4 @@
|
||||
import calendar
|
||||
year = 2015
|
||||
month = 2
|
||||
print(calendar.monthrange(year, month)[1])
|
||||
@@ -0,0 +1,4 @@
|
||||
from calendar import monthrange
|
||||
year = 2016
|
||||
month = 2
|
||||
print(monthrange(year, month))
|
||||
2
python/Date/Program to get week number.py
Normal file
2
python/Date/Program to get week number.py
Normal file
@@ -0,0 +1,2 @@
|
||||
import datetime
|
||||
print(datetime.date(2015, 6, 16).isocalendar()[1])
|
||||
@@ -0,0 +1,13 @@
|
||||
from datetime import date, timedelta
|
||||
|
||||
def all_sundays(year):
|
||||
# January 1st of the given year
|
||||
dt = date(year, 1, 1)
|
||||
# First Sunday of the given year
|
||||
dt += timedelta(days = 6 - dt.weekday())
|
||||
while dt.year == year:
|
||||
yield dt
|
||||
dt += timedelta(days = 7)
|
||||
|
||||
for s in all_sundays(2020):
|
||||
print(s)
|
||||
@@ -0,0 +1,8 @@
|
||||
from datetime import datetime
|
||||
def is_third_tuesday(s):
|
||||
d = datetime.strptime(s, '%b %d, %Y')
|
||||
return d.weekday() == 1 and 14 < d.day < 22
|
||||
|
||||
print(is_third_tuesday('Jun 23, 2015')) #False
|
||||
print(is_third_tuesday('Jun 16, 2015')) #True
|
||||
print(is_third_tuesday('Jul 21, 2015')) #False
|
||||
@@ -0,0 +1,5 @@
|
||||
import datetime
|
||||
x= datetime.datetime.now()
|
||||
y = x + datetime.timedelta(0,5)
|
||||
print(x.time())
|
||||
print(y.time())
|
||||
@@ -0,0 +1,4 @@
|
||||
import datetime
|
||||
today = datetime.datetime.now()
|
||||
day_of_year = (today - datetime.datetime(today.year, 1, 1)).days + 1
|
||||
print(day_of_year)
|
||||
@@ -0,0 +1,3 @@
|
||||
from datetime import datetime
|
||||
date_object = datetime.strptime('Jul 1 2014 2:43PM', '%b %d %Y %I:%M%p')
|
||||
print(date_object)
|
||||
@@ -0,0 +1,4 @@
|
||||
from datetime import date
|
||||
from datetime import datetime
|
||||
dt = date.today()
|
||||
print(datetime.combine(dt, datetime.min.time()))
|
||||
@@ -0,0 +1,6 @@
|
||||
import datetime
|
||||
print(
|
||||
datetime.datetime.fromtimestamp(
|
||||
int("1284105682")
|
||||
).strftime('%Y-%m-%d %H:%M:%S')
|
||||
)
|
||||
@@ -0,0 +1,11 @@
|
||||
def leap_year(y):
|
||||
if y % 400 == 0:
|
||||
return True
|
||||
if y % 100 == 0:
|
||||
return False
|
||||
if y % 4 == 0:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
print(leap_year(1900))
|
||||
print(leap_year(2004))
|
||||
@@ -0,0 +1,3 @@
|
||||
import time
|
||||
milli_sec = int(round(time.time() * 1000))
|
||||
print(milli_sec)
|
||||
2
python/Date/Python program to get the current time.py
Normal file
2
python/Date/Python program to get the current time.py
Normal file
@@ -0,0 +1,2 @@
|
||||
import datetime
|
||||
print(datetime.datetime.now().time())
|
||||
@@ -0,0 +1,4 @@
|
||||
import datetime
|
||||
base = datetime.datetime.today()
|
||||
for x in range(0, 5):
|
||||
print(base + datetime.timedelta(days=x))
|
||||
@@ -0,0 +1,7 @@
|
||||
import datetime
|
||||
today = datetime.date.today()
|
||||
yesterday = today - datetime.timedelta(days = 1)
|
||||
tomorrow = today + datetime.timedelta(days = 1)
|
||||
print('Yesterday : ',yesterday)
|
||||
print('Today : ',today)
|
||||
print('Tomorrow : ',tomorrow)
|
||||
@@ -0,0 +1,4 @@
|
||||
from datetime import date, timedelta
|
||||
dt = date.today() - timedelta(5)
|
||||
print('Current Date :',date.today())
|
||||
print('5 days before Current Date :',dt)
|
||||
@@ -0,0 +1,4 @@
|
||||
d = {0:10, 1:20}
|
||||
print(d)
|
||||
d.update({2:30})
|
||||
print(d)
|
||||
@@ -0,0 +1,4 @@
|
||||
my_dict = {}
|
||||
|
||||
if not bool(my_dict):
|
||||
print("Dictionary is empty")
|
||||
@@ -0,0 +1,8 @@
|
||||
d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
|
||||
def is_key_present(x):
|
||||
if x in d:
|
||||
print('Key is present in the dictionary')
|
||||
else:
|
||||
print('Key is not present in the dictionary')
|
||||
is_key_present(5)
|
||||
is_key_present(9)
|
||||
@@ -0,0 +1,6 @@
|
||||
dic1={1:10, 2:20}
|
||||
dic2={3:30, 4:40}
|
||||
dic3={5:50,6:60}
|
||||
dic4 = {}
|
||||
for d in (dic1, dic2, dic3): dic4.update(d)
|
||||
print(dic4)
|
||||
@@ -0,0 +1,9 @@
|
||||
class dictObj(object):
|
||||
def __init__(self):
|
||||
self.x = 'red'
|
||||
self.y = 'Yellow'
|
||||
self.z = 'Green'
|
||||
def do_nothing(self):
|
||||
pass
|
||||
test = dictObj()
|
||||
print(test.__dict__)
|
||||
@@ -0,0 +1,7 @@
|
||||
my_dict = {'x':500, 'y':5874, 'z': 560}
|
||||
|
||||
key_max = max(my_dict.keys(), key=(lambda k: my_dict[k]))
|
||||
key_min = min(my_dict.keys(), key=(lambda k: my_dict[k]))
|
||||
|
||||
print('Maximum Value: ',my_dict[key_max])
|
||||
print('Minimum Value: ',my_dict[key_min])
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user