Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions algorithms/bit_manipulation/sum_of_two_integers.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,4 @@ def getSum(a, b):
carry = carry << 1
a = diff
b = carry
if b > 0: return (a & mask)
else: return a
return (a & mask) if b > 0 else a
2 changes: 1 addition & 1 deletion algorithms/dynamic_programming/01_knapsack.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ def knapsack(values, weights, total):
# rows are the number of items
# columns are the values of weights required

t = [[0 for i in range(cols)] for i in range(rows)]
t = [[0 for _ in range(cols)] for _ in range(rows)]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function knapsack refactored with the following changes:


for i in range(1, rows):
for j in range(1, cols):
Expand Down
10 changes: 3 additions & 7 deletions algorithms/dynamic_programming/Z_Algorithm.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,9 @@ def z_function(text:str , size:int):
z[i] = min(r - i + 1 , z[i - l])
while i + z[i] < len(text) and text[z[i]] == text[i + z[i]]:
z[i] += 1

if i + z[i] - 1 > r:
l = i
r = i + z[i] - 1

res = []
for i in range(size , len(text)):
if z[i] == size:
res.append(i - size - 1)
return res

return [i - size - 1 for i in range(size , len(text)) if z[i] == size]
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ def lcs(s1, s2):
cols = len(s1) + 1
rows = len(s2) + 1

t = [[0 for i in range(cols)] for i in range(rows)]
t = [[0 for _ in range(cols)] for _ in range(rows)]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function lcs refactored with the following changes:


max_length = 0

Expand Down
2 changes: 1 addition & 1 deletion algorithms/dynamic_programming/longest_common_substring.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ def lcs(s1, s2):
cols = len(s1) + 1
rows = len(s2) + 1

t = [[0 for i in range(cols)] for i in range(rows)]
t = [[0 for _ in range(cols)] for _ in range(rows)]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function lcs refactored with the following changes:


max_length = 0

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,16 @@
"""

def find_seq(arr, n):
s = set()

for num in arr:
s.add(num)

s = set(arr)
ans = 0
elements = []

for i in range(n):
temp = []

if arr[i] - 1 not in s:
j = arr[i]

temp = []
Comment on lines -16 to +24
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function find_seq refactored with the following changes:


while j in s:
temp.append(j)
j += 1
Expand Down
13 changes: 5 additions & 8 deletions algorithms/dynamic_programming/longest_palindromic_substring.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
def longest_palindromic_substring_DP(s):

S = [[False for i in range(len(s))] for j in range(len(s))]
S = [[False for _ in range(len(s))] for _ in range(len(s))]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function longest_palindromic_substring_DP refactored with the following changes:


max_palindrome = ""

Expand All @@ -23,10 +23,10 @@ def longest_palindromic_substring_expansion(s):
max_palindrome = ""

for i in range(len(s) * 2 - 1):
# This is when you are "on" an actual character
# o = offset, ind = current character
o = 0
if i % 2 == 0:
# This is when you are "on" an actual character
# o = offset, ind = current character
o = 0
Comment on lines +26 to -29
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function longest_palindromic_substring_expansion refactored with the following changes:

This removes the following comments ( why? ):

# This is when you are "in the middle of" two characters
# o = offset, sind = start char, eind = end char

ind = i // 2
while ind + o < len(s) and ind - o >= 0:
if(s[ind + o] != s[ind - o]):
Expand All @@ -35,9 +35,6 @@ def longest_palindromic_substring_expansion(s):
max_palindrome = s[ind-o:ind+o + 1]
o += 1
else:
# This is when you are "in the middle of" two characters
# o = offset, sind = start char, eind = end char
o = 0
sind = i // 2
eind = i // 2 + 1
while sind - o >= 0 and eind + o < len(s):
Expand All @@ -54,4 +51,4 @@ def longest_palindromic_substring_expansion(s):

ans_DP = longest_palindromic_substring_DP(input_string)
ans_expansion = longest_palindromic_substring_expansion(input_string)
print("DP Solution: {}, Expansion Solution: {}".format(ans_DP, ans_expansion))
print(f"DP Solution: {ans_DP}, Expansion Solution: {ans_expansion}")
Comment on lines -57 to +54
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 57-57 refactored with the following changes:

Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,14 @@ def find_length(arr, k):
for i in range(0, len(mod_arr)):
if mod_arr[i] == 0:
length += 1
elif mod_arr[i] in hash_table:
if length < (i - mod_arr[i]):
length = i - mod_arr[i]
start = mod_arr[i]
end = i - 1 # i-1 because the current number is not to considered as it makes the sum not divisible by k

else:
if mod_arr[i] not in hash_table:
hash_table[mod_arr[i]] = i
else:
if length < (i - mod_arr[i]):
length = i - mod_arr[i]
start = mod_arr[i]
end = i - 1 # i-1 because the current number is not to considered as it makes the sum not divisible by k

hash_table[mod_arr[i]] = i
Comment on lines +42 to +49
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function find_length refactored with the following changes:

return length, arr[start:end+1]


Expand Down
7 changes: 1 addition & 6 deletions algorithms/greedy/activity_selection.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,11 @@

def find_activities(arr):
n = len(arr)
selected = []

arr.sort(key = lambda x: x[1])

i = 0

# since it is a greedy algorithm, the first acitivity is always
# selected because it is the most optimal choice at that point
selected.append(arr[i])

selected = [arr[i]]
Comment on lines -10 to +14
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function find_activities refactored with the following changes:

This removes the following comments ( why? ):

# selected because it is the most optimal choice at that point
# since it is a greedy algorithm, the first acitivity is always

for j in range(1, n):
start_time_next_activity = arr[j][0]
end_time_prev_activity = arr[i][1]
Expand Down
11 changes: 5 additions & 6 deletions algorithms/greedy/cost_of_tiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,19 @@ def cost(arr, A, B):

for i in range(n):
j = 0

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function cost refactored with the following changes:

while j < m:
if arr[i][j] == '*': # tile is already there
j += 1
continue

if j == m - 1: # if j is pointing to last tile, you can use only 1*1 tile
ans += A
elif arr[i][j+1] == '.':
ans += min(2 * A, B)
j += 1
else:
if arr[i][j+1] == '.':
ans += min(2 * A, B)
j += 1
else:
ans += A
ans += A

j += 1

Expand Down
22 changes: 9 additions & 13 deletions algorithms/greedy/dijkstra_greedy.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,19 @@
def dijkstra(graph, start, end):
shortest_distance = {}
non_visited_nodes = {}
for i in graph:
non_visited_nodes[i] = graph[i]

non_visited_nodes = {i: graph[i] for i in graph}
infinit = float('inf')

for no in non_visited_nodes:
shortest_distance[no] = infinit
shortest_distance = {no: infinit for no in non_visited_nodes}
shortest_distance[start] = 0

while non_visited_nodes != {}:
shortest_extracted_node = None
for i in non_visited_nodes:
if shortest_extracted_node is None:
shortest_extracted_node = i
elif shortest_distance[i] < shortest_distance[shortest_extracted_node]:
if (
shortest_extracted_node is None
or shortest_distance[i]
< shortest_distance[shortest_extracted_node]
):
shortest_extracted_node = i

Comment on lines -2 to -20
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function dijkstra refactored with the following changes:

for no_v, Weight in graph[shortest_extracted_node]:
if Weight + shortest_distance[shortest_extracted_node] < shortest_distance[no_v]:
shortest_distance[no_v] = Weight + shortest_distance[shortest_extracted_node]
Expand All @@ -31,7 +27,7 @@ def dijkstra(graph, start, end):

cities, origin, destiny = map(int, input().split())
graph = {i:[] for i in range(1, cities+1)}
for i in range(cities-1):
for _ in range(cities-1):
Comment on lines -34 to +30
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 34-34 refactored with the following changes:

u, v, w = map(int, input().split())
graph[v].append((u, w))
graph[u].append((v, w))
2 changes: 1 addition & 1 deletion algorithms/greedy/min_platforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def find_platforms(arrival, departure):
plat += 1
i += 1

elif arrival[i] > departure[j]:
else:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function find_platforms refactored with the following changes:

plat -= 1
j += 1

Expand Down
30 changes: 6 additions & 24 deletions algorithms/math/divisors.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,46 +3,28 @@
class divisors:

def findAllDivisors(self, n):
result = list()

for i in range(1, n+1):
if (n%i == 0):
result.append(i)

return result
return [i for i in range(1, n+1) if (n%i == 0)]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function divisors.findAllDivisors refactored with the following changes:


def divisorsCount(self, n):
divs = self.findAllDivisors(n)
return len(divs)

def oddFactors(self, n):
result = list()

for i in range(1, n+1):
if (n%i == 0 and i%2==1):
result.append(i)

return result
return [i for i in range(1, n+1) if (n%i == 0 and i%2==1)]
Comment on lines -19 to +13
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function divisors.oddFactors refactored with the following changes:


def oddFactorsSum(self, n):
divs = self.evenFactors(n)
return sum(divs)

def evenFactors(self, n):
result = list()

for i in range(1, n+1):
if (n%i == 0 and i%2==0):
result.append(i)

return result
return [i for i in range(1, n+1) if (n%i == 0 and i%2==0)]
Comment on lines -32 to +20
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function divisors.evenFactors refactored with the following changes:


def evenFactorsSum(self, n):
divs = self.evenFactors(n)
return sum(divs)

def primeFactors(self, n):
result = list()
result = []
Comment on lines -45 to +27
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function divisors.primeFactors refactored with the following changes:


while n % 2 == 0:
result.append(2)
Expand All @@ -52,10 +34,10 @@ def primeFactors(self, n):
while n % i== 0:
result.append(i)
n = n / i

if n > 2:
result.append(n)

return result

def primeFactorsSum(self, n):
Expand Down
5 changes: 2 additions & 3 deletions algorithms/math/factorial_iterative.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,8 @@ def factorial(number):

if number == 0:
return 1
else:
for num in range(1, number+1):
answer = answer * num
for num in range(1, number+1):
answer = answer * num
Comment on lines -9 to +10
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function factorial refactored with the following changes:

return answer

if __name__ == '__main__':
Expand Down
7 changes: 1 addition & 6 deletions algorithms/math/factorial_recursive.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,7 @@

def factorial(number):

if number == 0 or number == 1:
return 1

answer = number * factorial(number - 1)

return answer
return 1 if number in [0, 1] else number * factorial(number - 1)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function factorial refactored with the following changes:


if __name__ == '__main__':

Expand Down
5 changes: 1 addition & 4 deletions algorithms/math/greatest_common_divisor.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,7 @@ def gcd(x, y):
def gcd(x, y):
if x == 0:
return y
if y == 0:
return x

return gcd(y, x % y)
return x if y == 0 else gcd(y, x % y)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function gcd refactored with the following changes:


# Iterative optimized
def gcd(x, y):
Expand Down
15 changes: 6 additions & 9 deletions algorithms/math/number_convertion.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,7 @@ def verify_base(x):
try:
return int(x)
except:
if x in bases:
return bases[x]
else:
return default
return bases[x] if x in bases else default
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function verify_base refactored with the following changes:



def decimal_value(x):
Expand Down Expand Up @@ -91,10 +88,10 @@ def convert(n, from_base, to_base):
decimal_number += (multi * decimal_value(n[i]))
multi *= from_base

if(to_base == 10):
if (to_base == 10):
decimal_number = str(decimal_number)
if(negative):
decimal_number = '-' + decimal_number
if negative:
decimal_number = f'-{decimal_number}'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function convert refactored with the following changes:


return decimal_number

Expand All @@ -105,8 +102,8 @@ def convert(n, from_base, to_base):
result = to_special_caracter(value) + result
decimal_number = int((decimal_number - value)/to_base)

if(negative):
result = '-' + result
if negative:
result = f'-{result}'

return result

Expand Down
7 changes: 2 additions & 5 deletions algorithms/math/perfect_square.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,9 @@ def is_perfect_square(num):
:rtype: bool
"""
i = 0
while i * i < num:
while i**2 < num:
i += 1
if i * i == num:
return True
else:
return False
return i**2 == num
Comment on lines -11 to +13
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function is_perfect_square refactored with the following changes:



# Test
Expand Down
2 changes: 1 addition & 1 deletion algorithms/math/recursive_fibonacci.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def rec_fib(n):
return rec_fib(n-1)+rec_fib(n-2)

def binary_rec_fib(n):
if n == 2 or n == 1:
if n in [2, 1]:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function binary_rec_fib refactored with the following changes:

return 1
elif n == 0:
return 0
Expand Down
Loading