function stringlengths 18 3.86k | intent_category stringlengths 5 24 |
|---|---|
def is_palindrome_slice(s: str) -> bool:
return s == s[::-1] | strings |
def __init__(self, text: str, pattern: str):
self.text, self.pattern = text, pattern
self.textLen, self.patLen = len(text), len(pattern) | strings |
def match_in_pattern(self, char: str) -> int:
for i in range(self.patLen - 1, -1, -1):
if char == self.pattern[i]:
return i
return -1 | strings |
def mismatch_in_text(self, current_pos: int) -> int:
for i in range(self.patLen - 1, -1, -1):
if self.pattern[i] != self.text[current_pos + i]:
return current_pos + i
return -1 | strings |
def bad_character_heuristic(self) -> list[int]:
# searches pattern in text and returns index positions
positions = []
for i in range(self.textLen - self.patLen + 1):
mismatch_index = self.mismatch_in_text(i)
if mismatch_index == -1:
positions.append(i)
... | strings |
def get_letter_count(message: str) -> dict[str, int]:
letter_count = {letter: 0 for letter in string.ascii_uppercase}
for letter in message.upper():
if letter in LETTERS:
letter_count[letter] += 1
return letter_count | strings |
def get_item_at_index_zero(x: tuple) -> str:
return x[0] | strings |
def get_frequency_order(message: str) -> str:
letter_to_freq = get_letter_count(message)
freq_to_letter: dict[int, list[str]] = {
freq: [] for letter, freq in letter_to_freq.items()
}
for letter in LETTERS:
freq_to_letter[letter_to_freq[letter]].append(letter)
freq_to_letter_str: di... | strings |
def english_freq_match_score(message: str) -> int:
freq_order = get_frequency_order(message)
match_score = 0
for common_letter in ETAOIN[:6]:
if common_letter in freq_order[:6]:
match_score += 1
for uncommon_letter in ETAOIN[-6:]:
if uncommon_letter in freq_order[-6:]:
... | strings |
def get_word_pattern(word: str) -> str:
word = word.upper()
next_num = 0
letter_nums = {}
word_pattern = []
for letter in word:
if letter not in letter_nums:
letter_nums[letter] = str(next_num)
next_num += 1
word_pattern.append(letter_nums[letter])
return... | strings |
def reverse_words(input_str: str) -> str:
return " ".join(input_str.split()[::-1]) | strings |
def wave(txt: str) -> list:
return [
txt[:a] + txt[a].upper() + txt[a + 1 :]
for a in range(len(txt))
if txt[a].isalpha()
] | strings |
def signature(word: str) -> str:
return "".join(sorted(word)) | strings |
def anagram(my_word: str) -> list[str]:
return word_by_signature[signature(my_word)] | strings |
def load_dictionary() -> dict[str, None]:
path = os.path.split(os.path.realpath(__file__))
english_words: dict[str, None] = {}
with open(path[0] + "/dictionary.txt") as dictionary_file:
for word in dictionary_file.read().split("\n"):
english_words[word] = None
return english_words | strings |
def get_english_count(message: str) -> float:
message = message.upper()
message = remove_non_letters(message)
possible_words = message.split()
matches = len([word for word in possible_words if word in ENGLISH_WORDS])
return float(matches) / len(possible_words) | strings |
def remove_non_letters(message: str) -> str:
return "".join(symbol for symbol in message if symbol in LETTERS_AND_SPACE) | strings |
def is_english(
message: str, word_percentage: int = 20, letter_percentage: int = 85
) -> bool:
words_match = get_english_count(message) * 100 >= word_percentage
num_letters = len(remove_non_letters(message))
message_letters_percentage = (float(num_letters) / len(message)) * 100
letters_match = mess... | strings |
def upper(word: str) -> str:
# Converting to ascii value int value and checking to see if char is a lower letter
# if it is a lowercase letter it is getting shift by 32 which makes it an uppercase
# case letter
return "".join(chr(ord(char) - 32) if "a" <= char <= "z" else char for char in word) | strings |
def prefix_function(input_string: str) -> list:
# list for the result values
prefix_result = [0] * len(input_string)
for i in range(1, len(input_string)):
# use last results for better performance - dynamic programming
j = prefix_result[i - 1]
while j > 0 and input_string[i] != inp... | strings |
def longest_prefix(input_str: str) -> int:
# just returning maximum value of the array gives us answer
return max(prefix_function(input_str)) | strings |
def can_string_be_rearranged_as_palindrome_counter(
input_str: str = "",
) -> bool:
return sum(c % 2 for c in Counter(input_str.replace(" ", "").lower()).values()) < 2 | strings |
def can_string_be_rearranged_as_palindrome(input_str: str = "") -> bool:
if len(input_str) == 0:
return True
lower_case_input_str = input_str.replace(" ", "").lower()
# character_freq_dict: Stores the frequency of every character in the input string
character_freq_dict: dict[str, int] = {}
... | strings |
def benchmark(input_str: str = "") -> None:
print("\nFor string = ", input_str, ":")
print(
"> can_string_be_rearranged_as_palindrome_counter()",
"\tans =",
can_string_be_rearranged_as_palindrome_counter(input_str),
"\ttime =",
timeit(
"z.can_string_be_rearran... | strings |
def reverse_long_words(sentence: str) -> str:
return " ".join(
"".join(word[::-1]) if len(word) > 4 else word for word in sentence.split()
) | strings |
def is_palindrome(s: str) -> bool:
# Since punctuation, capitalization, and spaces are often ignored while checking
# palindromes, we first remove them from our string.
s = "".join(character for character in s.lower() if character.isalnum())
# return s == s[::-1] the slicing method
# uses extra spac... | strings |
def justify(line: list, width: int, max_width: int) -> str:
overall_spaces_count = max_width - width
words_count = len(line)
if len(line) == 1:
# if there is only word in line
# just insert overall_spaces_count for the remainder of line
return line[0] + " " * ... | strings |
def word_occurrence(sentence: str) -> dict:
occurrence: DefaultDict[str, int] = defaultdict(int)
# Creating a dictionary containing count of each word
for word in sentence.split():
occurrence[word] += 1
return occurrence | strings |
def rabin_karp(pattern: str, text: str) -> bool:
p_len = len(pattern)
t_len = len(text)
if p_len > t_len:
return False
p_hash = 0
text_hash = 0
modulus_power = 1
# Calculating the hash of pattern and substring of text
for i in range(p_len):
p_hash = (ord(pattern[i]) + p... | strings |
def test_rabin_karp() -> None:
# Test 1)
pattern = "abc1abc12"
text1 = "alskfjaldsabc1abc1abc12k23adsfabcabc"
text2 = "alskfjaldsk23adsfabcabc"
assert rabin_karp(pattern, text1) and not rabin_karp(pattern, text2)
# Test 2)
pattern = "ABABX"
text = "ABABZABABYABABX"
assert rabin_karp... | strings |
def __init__(self) -> None:
self._trie: dict = {} | strings |
def insert_word(self, text: str) -> None:
trie = self._trie
for char in text:
if char not in trie:
trie[char] = {}
trie = trie[char]
trie[END] = True | strings |
def find_word(self, prefix: str) -> tuple | list:
trie = self._trie
for char in prefix:
if char in trie:
trie = trie[char]
else:
return []
return self._elements(trie) | strings |
def _elements(self, d: dict) -> tuple:
result = []
for c, v in d.items():
sub_result = [" "] if c == END else [(c + s) for s in self._elements(v)]
result.extend(sub_result)
return tuple(result) | strings |
def autocomplete_using_trie(string: str) -> tuple:
suffixes = trie.find_word(string)
return tuple(string + word for word in suffixes) | strings |
def main() -> None:
print(autocomplete_using_trie("de")) | strings |
def join(separator: str, separated: list[str]) -> str:
joined = ""
for word_or_phrase in separated:
if not isinstance(word_or_phrase, str):
raise Exception("join() accepts only strings to be joined")
joined += word_or_phrase + separator
return joined.strip(separator) | strings |
def dna(dna: str) -> str:
if len(re.findall("[ATCG]", dna)) != len(dna):
raise ValueError("Invalid Strand")
return dna.translate(dna.maketrans("ATCG", "TAGC")) | strings |
def kmp(pattern: str, text: str) -> bool:
# 1) Construct the failure array
failure = get_failure_array(pattern)
# 2) Step through text searching for pattern
i, j = 0, 0 # index into text, pattern
while i < len(text):
if pattern[j] == text[i]:
if j == (len(pattern) - 1):
... | strings |
def get_failure_array(pattern: str) -> list[int]:
failure = [0]
i = 0
j = 1
while j < len(pattern):
if pattern[i] == pattern[j]:
i += 1
elif i > 0:
i = failure[i - 1]
continue
j += 1
failure.append(i)
return failure | strings |
def naive_pattern_search(s: str, pattern: str) -> list:
pat_len = len(pattern)
position = []
for i in range(len(s) - pat_len + 1):
match_found = True
for j in range(pat_len):
if s[i + j] != pattern[j]:
match_found = False
break
if match_fou... | strings |
def lower(word: str) -> str:
# converting to ascii value int value and checking to see if char is a capital
# letter if it is a capital letter it is getting shift by 32 which makes it a lower
# case letter
return "".join(chr(ord(char) + 32) if "A" <= char <= "Z" else char for char in word) | strings |
def is_sri_lankan_phone_number(phone: str) -> bool:
pattern = re.compile(
r"^(?:0|94|\+94|0{2}94)" r"7(0|1|2|4|5|6|7|8)" r"(-| |)" r"\d{7}$"
)
return bool(re.search(pattern, phone)) | strings |
def compute_transform_tables(
source_string: str,
destination_string: str,
copy_cost: int,
replace_cost: int,
delete_cost: int,
insert_cost: int,
) -> tuple[list[list[int]], list[list[str]]]:
source_seq = list(source_string)
destination_seq = list(destination_string)
len_source_seq =... | strings |
def assemble_transformation(ops: list[list[str]], i: int, j: int) -> list[str]:
if i == 0 and j == 0:
return []
else:
if ops[i][j][0] == "C" or ops[i][j][0] == "R":
seq = assemble_transformation(ops, i - 1, j - 1)
seq.append(ops[i][j])
return seq
elif ... | strings |
def get_check_digit(barcode: int) -> int:
barcode //= 10 # exclude the last digit
checker = False
s = 0
# extract and check each digit
while barcode != 0:
mult = 1 if checker else 3
s += mult * (barcode % 10)
barcode //= 10
checker = not checker
return (10 - (s... | strings |
def is_valid(barcode: int) -> bool:
return len(str(barcode)) == 13 and get_check_digit(barcode) == barcode % 10 | strings |
def get_barcode(barcode: str) -> int:
if str(barcode).isalpha():
raise ValueError(f"Barcode '{barcode}' has alphabetic characters.")
elif int(barcode) < 0:
raise ValueError("The entered barcode has a negative value. Try again.")
else:
return int(barcode) | strings |
def match_pattern(input_string: str, pattern: str) -> bool:
len_string = len(input_string) + 1
len_pattern = len(pattern) + 1
# dp is a 2d matrix where dp[i][j] denotes whether prefix string of
# length i of input_string matches with prefix string of length j of
# given pattern.
# "dp" stands ... | strings |
def split(string: str, separator: str = " ") -> list:
split_words = []
last_index = 0
for index, char in enumerate(string):
if char == separator:
split_words.append(string[last_index:index])
last_index = index + 1
elif index + 1 == len(string):
split_wor... | strings |
def alternative_string_arrange(first_str: str, second_str: str) -> str:
first_str_length: int = len(first_str)
second_str_length: int = len(second_str)
abs_length: int = (
first_str_length if first_str_length > second_str_length else second_str_length
)
output_list: list = []
for char_co... | strings |
def is_pangram(
input_str: str = "The quick brown fox jumps over the lazy dog",
) -> bool:
# Declare frequency as a set to have unique occurrences of letters
frequency = set()
# Replace all the whitespace in our sentence
input_str = input_str.replace(" ", "")
for alpha in input_str:
if ... | strings |
def is_pangram_faster(
input_str: str = "The quick brown fox jumps over the lazy dog",
) -> bool:
flag = [False] * 26
for char in input_str:
if char.islower():
flag[ord(char) - 97] = True
elif char.isupper():
flag[ord(char) - 65] = True
return all(flag) | strings |
def is_pangram_fastest(
input_str: str = "The quick brown fox jumps over the lazy dog",
) -> bool:
return len({char for char in input_str.lower() if char.isalpha()}) == 26 | strings |
def benchmark() -> None:
from timeit import timeit
setup = "from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest"
print(timeit("is_pangram()", setup=setup))
print(timeit("is_pangram_faster()", setup=setup))
print(timeit("is_pangram_fastest()", setup=setup))
# 5.348480500048026... | strings |
def levenshtein_distance(first_word: str, second_word: str) -> int:
# The longer word should come first
if len(first_word) < len(second_word):
return levenshtein_distance(second_word, first_word)
if len(second_word) == 0:
return len(first_word)
previous_row = list(range(len(second_word... | strings |
def is_spain_national_id(spanish_id: str) -> bool:
if not isinstance(spanish_id, str):
raise TypeError(f"Expected string as input, found {type(spanish_id).__name__}")
spanish_id_clean = spanish_id.replace("-", "").upper()
if len(spanish_id_clean) != 9:
raise ValueError(NUMBERS_PLUS_LETTER)... | strings |
def snake_to_camel_case(input_str: str, use_pascal: bool = False) -> str:
if not isinstance(input_str, str):
raise ValueError(f"Expected string as input, found {type(input_str)}")
if not isinstance(use_pascal, bool):
raise ValueError(
f"Expected boolean as use_pascal parameter, foun... | strings |
def check_anagrams(first_str: str, second_str: str) -> bool:
first_str = first_str.lower().strip()
second_str = second_str.lower().strip()
# Remove whitespace
first_str = first_str.replace(" ", "")
second_str = second_str.replace(" ", "")
# Strings of different lengths are not anagrams
if ... | strings |
def __init__(self, keywords: list[str]):
self.adlist: list[dict] = []
self.adlist.append(
{"value": "", "next_states": [], "fail_state": 0, "output": []}
)
for keyword in keywords:
self.add_keyword(keyword)
self.set_fail_transitions() | strings |
def find_next_state(self, current_state: int, char: str) -> int | None:
for state in self.adlist[current_state]["next_states"]:
if char == self.adlist[state]["value"]:
return state
return None | strings |
def add_keyword(self, keyword: str) -> None:
current_state = 0
for character in keyword:
next_state = self.find_next_state(current_state, character)
if next_state is None:
self.adlist.append(
{
"value": character,
... | strings |
def set_fail_transitions(self) -> None:
q: deque = deque()
for node in self.adlist[0]["next_states"]:
q.append(node)
self.adlist[node]["fail_state"] = 0
while q:
r = q.popleft()
for child in self.adlist[r]["next_states"]:
q.append(c... | strings |
def search_in(self, string: str) -> dict[str, list[int]]:
result: dict = {} # returns a dict with keywords and list of its occurrences
current_state = 0
for i in range(len(string)):
while (
self.find_next_state(current_state, string[i]) is None
and cu... | strings |
def hamming_distance(string1: str, string2: str) -> int:
if len(string1) != len(string2):
raise ValueError("String lengths must match!")
count = 0
for char1, char2 in zip(string1, string2):
if char1 != char2:
count += 1
return count | strings |
def palindromic_string(input_string: str) -> str:
max_length = 0
# if input_string is "aba" than new_input_string become "a|b|a"
new_input_string = ""
output_string = ""
# append each character + "|" in new_string for range(0, length-1)
for i in input_string[: len(input_string) - 1]:
n... | strings |
def reverse_letters(input_str: str) -> str:
return " ".join([word[::-1] for word in input_str.split()]) | strings |
def validate_initial_digits(credit_card_number: str) -> bool:
return credit_card_number.startswith(("34", "35", "37", "4", "5", "6")) | strings |
def luhn_validation(credit_card_number: str) -> bool:
cc_number = credit_card_number
total = 0
half_len = len(cc_number) - 2
for i in range(half_len, -1, -2):
# double the value of every second digit
digit = int(cc_number[i])
digit *= 2
# If doubling of a number results ... | strings |
def validate_credit_card_number(credit_card_number: str) -> bool:
error_message = f"{credit_card_number} is an invalid credit card number because"
if not credit_card_number.isdigit():
print(f"{error_message} it has nonnumerical characters.")
return False
if not 13 <= len(credit_card_number)... | strings |
def is_isogram(string: str) -> bool:
if not all(x.isalpha() for x in string):
raise ValueError("String must only contain alphabetic characters.")
letters = sorted(string.lower())
return len(letters) == len(set(letters)) | strings |
def is_contains_unique_chars(input_str: str) -> bool:
# Each bit will represent each unicode character
# For example 65th bit representing 'A'
# https://stackoverflow.com/a/12811293
bitmap = 0
for ch in input_str:
ch_unicode = ord(ch)
ch_bit_index_on = pow(2, ch_unicode)
# ... | strings |
def capitalize(sentence: str) -> str:
if not sentence:
return ""
lower_to_upper = {lc: uc for lc, uc in zip(ascii_lowercase, ascii_uppercase)}
return lower_to_upper.get(sentence[0], sentence[0]) + sentence[1:] | strings |
def get_1s_count(number: int) -> int:
if not isinstance(number, int) or number < 0:
raise ValueError("Input must be a non-negative integer")
count = 0
while number:
# This way we arrive at next set bit (next 1) instead of looping
# through each bit and checking for 1s hence the
... | bit_manipulation |
def binary_count_setbits(a: int) -> int:
if a < 0:
raise ValueError("Input value must be a positive integer")
elif isinstance(a, float):
raise TypeError("Input value must be a 'int' type")
return bin(a).count("1") | bit_manipulation |
def twos_complement(number: int) -> str:
if number > 0:
raise ValueError("input must be a negative integer")
binary_number_length = len(bin(number)[3:])
twos_complement_number = bin(abs(number) - (1 << binary_number_length))[3:]
twos_complement_number = (
(
"1"
+ ... | bit_manipulation |
def binary_and(a: int, b: int) -> str:
if a < 0 or b < 0:
raise ValueError("the value of both inputs must be positive")
a_binary = str(bin(a))[2:] # remove the leading "0b"
b_binary = str(bin(b))[2:] # remove the leading "0b"
max_len = max(len(a_binary), len(b_binary))
return "0b" + "".... | bit_manipulation |
def get_reverse_bit_string(number: int) -> str:
if not isinstance(number, int):
raise TypeError(
"operation can not be conducted on a object of type "
f"{type(number).__name__}"
)
bit_string = ""
for _ in range(0, 32):
bit_string += str(number % 2)
num... | bit_manipulation |
def reverse_bit(number: int) -> str:
if number < 0:
raise ValueError("the value of input must be positive")
elif isinstance(number, float):
raise TypeError("Input value must be a 'int' type")
elif isinstance(number, str):
raise TypeError("'<' not supported between instances of 'str' ... | bit_manipulation |
def different_signs(num1: int, num2: int) -> bool:
return num1 ^ num2 < 0 | bit_manipulation |
def is_even(number: int) -> bool:
return number & 1 == 0 | bit_manipulation |
def is_power_of_two(number: int) -> bool:
if number < 0:
raise ValueError("number must not be negative")
return number & (number - 1) == 0 | bit_manipulation |
def logical_left_shift(number: int, shift_amount: int) -> str:
if number < 0 or shift_amount < 0:
raise ValueError("both inputs must be positive integers")
binary_number = str(bin(number))
binary_number += "0" * shift_amount
return binary_number | bit_manipulation |
def logical_right_shift(number: int, shift_amount: int) -> str:
if number < 0 or shift_amount < 0:
raise ValueError("both inputs must be positive integers")
binary_number = str(bin(number))[2:]
if shift_amount >= len(binary_number):
return "0b0"
shifted_binary_number = binary_number[: l... | bit_manipulation |
def arithmetic_right_shift(number: int, shift_amount: int) -> str:
if number >= 0: # Get binary representation of positive number
binary_number = "0" + str(bin(number)).strip("-")[2:]
else: # Get binary (2's complement) representation of negative number
binary_number_length = len(bin(number)[3... | bit_manipulation |
def binary_xor(a: int, b: int) -> str:
if a < 0 or b < 0:
raise ValueError("the value of both inputs must be positive")
a_binary = str(bin(a))[2:] # remove the leading "0b"
b_binary = str(bin(b))[2:] # remove the leading "0b"
max_len = max(len(a_binary), len(b_binary))
return "0b" + "".... | bit_manipulation |
def get_set_bits_count_using_brian_kernighans_algorithm(number: int) -> int:
if number < 0:
raise ValueError("the value of input must not be negative")
result = 0
while number:
number &= number - 1
result += 1
return result | bit_manipulation |
def get_set_bits_count_using_modulo_operator(number: int) -> int:
if number < 0:
raise ValueError("the value of input must not be negative")
result = 0
while number:
if number % 2 == 1:
result += 1
number >>= 1
return result | bit_manipulation |
def do_benchmark(number: int) -> None:
setup = "import __main__ as z"
print(f"Benchmark when {number = }:")
print(f"{get_set_bits_count_using_modulo_operator(number) = }")
timing = timeit("z.get_set_bits_count_using_modulo_operator(25)", setup=setup)
print(f"timeit() runs in {tim... | bit_manipulation |
def gray_code(bit_count: int) -> list:
# bit count represents no. of bits in the gray code
if bit_count < 0:
raise ValueError("The given input must be positive")
# get the generated string sequence
sequence = gray_code_sequence_string(bit_count)
#
# convert them to integers
for i i... | bit_manipulation |
def gray_code_sequence_string(bit_count: int) -> list:
# The approach is a recursive one
# Base case achieved when either n = 0 or n=1
if bit_count == 0:
return ["0"]
if bit_count == 1:
return ["0", "1"]
seq_len = 1 << bit_count # defines the length of the sequence
# 1<< n is... | bit_manipulation |
def binary_count_trailing_zeros(a: int) -> int:
if a < 0:
raise ValueError("Input value must be a positive integer")
elif isinstance(a, float):
raise TypeError("Input value must be a 'int' type")
return 0 if (a == 0) else int(log2(a & -a)) | bit_manipulation |
def get_index_of_rightmost_set_bit(number: int) -> int:
if not isinstance(number, int) or number < 0:
raise ValueError("Input must be a non-negative integer")
intermediate = number & ~(number - 1)
index = 0
while intermediate:
intermediate >>= 1
index += 1
return index - 1 | bit_manipulation |
def get_highest_set_bit_position(number: int) -> int:
if not isinstance(number, int):
raise TypeError("Input value must be an 'int' type")
position = 0
while number:
position += 1
number >>= 1
return position | bit_manipulation |
def binary_or(a: int, b: int) -> str:
if a < 0 or b < 0:
raise ValueError("the value of both inputs must be positive")
a_binary = str(bin(a))[2:] # remove the leading "0b"
b_binary = str(bin(b))[2:]
max_len = max(len(a_binary), len(b_binary))
return "0b" + "".join(
str(int("1" in (c... | bit_manipulation |
def is_9_pandigital(n: int) -> bool:
s = str(n)
return len(s) == 9 and set(s) == set("123456789") | project_euler |
def solution() -> int | None:
for base_num in range(9999, 4999, -1):
candidate = 100002 * base_num
if is_9_pandigital(candidate):
return candidate
for base_num in range(333, 99, -1):
candidate = 1002003 * base_num
if is_9_pandigital(candidate):
return can... | project_euler |
def is_prime(number: int) -> bool:
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
# All primes number are in format of 6k +/- 1
... | project_euler |
def prime_generator():
num = 2
while True:
if is_prime(num):
yield num
num += 1 | project_euler |
def solution(nth: int = 10001) -> int:
return next(itertools.islice(prime_generator(), nth - 1, nth)) | project_euler |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.