Skip to content
Closed
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
8 changes: 5 additions & 3 deletions greedy_methods/fractional_knapsack.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,11 @@ def frac_knapsack(vl, wt, w, n):
return (
0
if k == 0
else sum(vl[:k]) + (w - acc[k - 1]) * (vl[k]) / (wt[k])
if k != n
else sum(vl[:k])
else (
sum(vl[:k]) + (w - acc[k - 1]) * (vl[k]) / (wt[k])
if k != n
else sum(vl[:k])
)
)


Expand Down
2 changes: 1 addition & 1 deletion machine_learning/frequent_pattern_growth.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ def ascend_tree(leaf_node: TreeNode, prefix_path: list[str]) -> None:
ascend_tree(leaf_node.parent, prefix_path)


def find_prefix_path(base_pat: frozenset, tree_node: TreeNode | None) -> dict: # noqa: ARG001
def find_prefix_path(_base_pat: frozenset, tree_node: TreeNode | None) -> dict:
"""
Find the conditional pattern base for a given base pattern.

Expand Down
8 changes: 5 additions & 3 deletions matrix/matrix_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,9 +204,11 @@ def cofactors(self) -> Matrix:
return Matrix(
[
[
self.minors().rows[row][column]
if (row + column) % 2 == 0
else self.minors().rows[row][column] * -1
(
self.minors().rows[row][column]
if (row + column) % 2 == 0
else self.minors().rows[row][column] * -1
)
for column in range(self.minors().num_columns)
]
for row in range(self.minors().num_rows)
Expand Down
3 changes: 2 additions & 1 deletion quantum/quantum_teleportation.py.DISABLED.txt
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ https://qiskit.org/textbook/ch-algorithms/teleportation.html

import numpy as np
import qiskit
from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute
from qiskit import (Aer, ClassicalRegister, QuantumCircuit, QuantumRegister,
execute)


def quantum_teleportation(
Expand Down
34 changes: 27 additions & 7 deletions sorts/bead_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@
https://en.wikipedia.org/wiki/Bead_sort
"""

from itertools import pairwise

Check failure on line 6 in sorts/bead_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (F401)

sorts/bead_sort.py:6:23: F401 `itertools.pairwise` imported but unused

Check failure on line 6 in sorts/bead_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (I001)

sorts/bead_sort.py:6:1: I001 Import block is un-sorted or un-formatted

def bead_sort(sequence: list) -> list:
"""
Sorts a list of non-negative integers using bead sort.

>>> bead_sort([6, 11, 12, 4, 1, 5])
[1, 4, 5, 6, 11, 12]

Expand All @@ -28,16 +31,33 @@
...
TypeError: Sequence must be list of non-negative integers
"""
from itertools import pairwise

Check failure on line 34 in sorts/bead_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (F401)

sorts/bead_sort.py:34:27: F401 `itertools.pairwise` imported but unused

Check failure on line 34 in sorts/bead_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (F811)

sorts/bead_sort.py:34:27: F811 Redefinition of unused `pairwise` from line 6

if any(not isinstance(x, int) or x < 0 for x in sequence):
raise TypeError("Sequence must be list of non-negative integers")
for _ in range(len(sequence)):
for i, (rod_upper, rod_lower) in enumerate(zip(sequence, sequence[1:])): # noqa: RUF007
if rod_upper > rod_lower:
sequence[i] -= rod_upper - rod_lower
sequence[i + 1] += rod_upper - rod_lower
return sequence

# Early return for empty list
if not sequence:
return []

max_value = max(sequence)
beads = [[0] * len(sequence) for _ in range(max_value)]

# Drop beads
for i, num in enumerate(sequence):
for j in range(num):
beads[j][i] = 1

# Let beads "fall"
for row in beads:
count = sum(row)
for i in range(len(row)):
row[i] = 1 if i < count else 0

# Read off sorted sequence
return [sum(beads[j][i] for j in range(max_value)) for i in range(len(sequence))]


if __name__ == "__main__":
assert bead_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
assert bead_sort([7, 9, 4, 3, 5]) == [3, 4, 5, 7, 9]
assert bead_sort([7, 9, 4, 3, 5]) == [3, 4, 5, 7, 9]

Check failure on line 63 in sorts/bead_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W292)

sorts/bead_sort.py:63:57: W292 No newline at end of file
2 changes: 1 addition & 1 deletion strings/min_cost_string_conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ def assemble_transformation(ops: list[list[str]], i: int, j: int) -> list[str]:
elif op[0] == "R":
string[i] = op[2]

file.write("%-16s" % ("Replace %c" % op[1] + " with " + str(op[2]))) # noqa: UP031
file.write(f"{'Replace ' + op[1] + ' with ' + str(op[2]):<16}")
file.write("\t\t" + "".join(string))
file.write("\r\n")

Expand Down
190 changes: 190 additions & 0 deletions strings/string_to_num.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
"""Converts a given string to integer and float
This works with only Indian system of wording

* Indian system uses crore, lakh, thousand and not million and billions

For the part after the decimal example ( .159 ):
* Digit by digit ( .159 ) -> point one five nine is allowed
* Anything else will throw an error

>>> to_int("Five")
5
>>> to_float("Five")
5.0

>>> to_int("One thousand five hundred and two")
1502
>>> to_float("One thousand five hundred and two")
1502.0

>>> to_int(
... "Ninety nine crore three lakh seventy two thousand and six point one five nine"
... )
990372006

>>> to_float(
... "Ninety nine crore three lakh seventy two thousand and six point one five nine"
... )
990372006.159

wikipedia explanation - https://en.wikipedia.org/wiki/Numeral_(linguistics)
"""


def to_int(word: str) -> int:
if len(word.strip()) > 0:
units = {
"zero": 0,
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
"six": 6,
"seven": 7,
"eight": 8,
"nine": 9,
"eleven": 11,
"twelve": 12,
"thirteen": 13,
"fourteen": 14,
"fifteen": 15,
"sixteen": 16,
"seventeen": 17,
"eighteen": 18,
"nineteen": 19,
}

tens = {
"ten": 10,
"twenty": 20,
"thirty": 30,
"forty": 40,
"fifty": 50,
"sixty": 60,
"seventy": 70,
"eighty": 80,
"ninety": 90,
}

multipliers = {
"hundred": 100,
"thousand": 1_000,
"lakh": 1_00_000,
"crore": 1_00_00_000,
}

if "point" in word:
word_lst = word.split("point")
word = "".join(word_lst[:-1])

words = (
word.strip()
.replace(" and", "")
.replace("-", "")
.replace("_", "")
.lower()
.split()
)

number = 0
temp = 0

for index, word in enumerate(words):
if index == 0:
if word in units:
temp += units[word]
elif word in tens:
temp += tens[word]
else:
temp += multipliers[word]
elif index == (len(words) - 1):
if word in units:
temp += units[word]
number += temp
elif word in tens:
temp += tens[word]
number += temp
else:
temp *= multipliers[word]
number += temp
elif word in units:
temp += units[word]
elif word in tens:
temp += tens[word]
elif word in multipliers:
temp *= multipliers[word]
number += temp
temp = 0

if len(words) > 1:
return number
else:
return temp
else:
raise ValueError("Empty input is not a valid number in words")


def to_float(word: str) -> float:
units = {
"zero": 0,
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
"six": 6,
"seven": 7,
"eight": 8,
"nine": 9,
"eleven": 11,
"twelve": 12,
"thirteen": 13,
"fourteen": 14,
"fifteen": 15,
"sixteen": 16,
"seventeen": 17,
"eighteen": 18,
"nineteen": 19,
}

all_words = (
word.strip()
.replace(" and", "")
.replace("-", "")
.replace("_", "")
.lower()
.split("point")
)
if len(all_words) > 1:
word = all_words[0]
after_point = all_words[1].split()

integer_part = to_int(word)

decimal_part = ""
for num in after_point:
if num in units:
decimal_part += str(units[num])

str_float = str(integer_part) + str(decimal_part)
divider = "1" + ("0" * len(after_point))
return int(str_float) / int(divider)

else:
return float(to_int(word))


if __name__ == "__main__":
import doctest

doctest.testmod()
# while True:
# word = input("Enter a number in words (q to quit) :- ").lower().strip()
# if word == "q":
# break
# else:
# integer = to_int(word)
# print(f"\nThe number in {type(integer)} --> {integer} ")
# floater = to_float(word)
# print(f"\nThe number in {type(floater)} --> {floater} ")
Loading