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) else: match_index = self.match_in_pattern(self.text[mismatch_index]) i = ( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions
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: dict[int, str] = {} for freq in freq_to_letter: freq_to_letter[freq].sort(key=ETAOIN.find, reverse=True) freq_to_letter_str[freq] = "".join(freq_to_letter[freq]) freq_pairs = list(freq_to_letter_str.items()) freq_pairs.sort(key=get_item_at_index_zero, reverse=True) freq_order: list[str] = [freq_pair[1] for freq_pair in freq_pairs] return "".join(freq_order)
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:]: match_score += 1 return match_score
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 ".".join(word_pattern)
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 = message_letters_percentage >= letter_percentage return words_match and letters_match
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] != input_string[j]: j = prefix_result[j - 1] if input_string[i] == input_string[j]: j += 1 prefix_result[i] = j return prefix_result
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] = {} for character in lower_case_input_str: character_freq_dict[character] = character_freq_dict.get(character, 0) + 1 odd_char = 0 for character_count in character_freq_dict.values(): if character_count % 2: odd_char += 1 if odd_char > 1: return False return True
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_rearranged_as_palindrome_counter(z.check_str)", setup="import __main__ as z", ), "seconds", ) print( "> can_string_be_rearranged_as_palindrome()", "\tans =", can_string_be_rearranged_as_palindrome(input_str), "\ttime =", timeit( "z.can_string_be_rearranged_as_palindrome(z.check_str)", setup="import __main__ as z", ), "seconds", )
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 spaces we can # better with iteration method. end = len(s) // 2 n = len(s) # We need to traverse till half of the length of string # as we can get access of the i'th last element from # i'th index. # eg: [0,1,2,3,4,5] => 4th index can be accessed # with the help of 1st index (i==n-i-1) # where n is length of string return all(s[i] == s[n - i - 1] for i in range(end))
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] + " " * overall_spaces_count else: spaces_to_insert_between_words = words_count - 1 # num_spaces_between_words_list[i] : tells you to insert # num_spaces_between_words_list[i] spaces # after word on line[i] num_spaces_between_words_list = spaces_to_insert_between_words * [ overall_spaces_count // spaces_to_insert_between_words ] spaces_count_in_locations = ( overall_spaces_count % spaces_to_insert_between_words ) # distribute spaces via round robin to the left words for i in range(spaces_count_in_locations): num_spaces_between_words_list[i] += 1 aligned_words_list = [] for i in range(spaces_to_insert_between_words): # add the word aligned_words_list.append(line[i]) # add the spaces to insert aligned_words_list.append(num_spaces_between_words_list[i] * " ") # just add the last word to the sentence aligned_words_list.append(line[-1]) # join the aligned words list to form a justified line return "".join(aligned_words_list)
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_hash * alphabet_size) % modulus text_hash = (ord(text[i]) + text_hash * alphabet_size) % modulus if i == p_len - 1: continue modulus_power = (modulus_power * alphabet_size) % modulus for i in range(0, t_len - p_len + 1): if text_hash == p_hash and text[i : i + p_len] == pattern: return True if i == t_len - p_len: continue # Calculate the https://en.wikipedia.org/wiki/Rolling_hash text_hash = ( (text_hash - ord(text[i]) * modulus_power) * alphabet_size + ord(text[i + p_len]) ) % modulus return False
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(pattern, text) # Test 3) pattern = "AAAB" text = "ABAAAAAB" assert rabin_karp(pattern, text) # Test 4) pattern = "abcdabcy" text = "abcxabcdabxabcdabcdabcy" assert rabin_karp(pattern, text) # Test 5) pattern = "Lü" text = "Lüsai" assert rabin_karp(pattern, text) pattern = "Lue" assert not rabin_karp(pattern, text) print("Success.")
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): return True j += 1 # if this is a prefix in our pattern # just go back far enough to continue elif j > 0: j = failure[j - 1] continue i += 1 return False
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_found: position.append(i) return position
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 = len(source_seq) len_destination_seq = len(destination_seq) costs = [ [0 for _ in range(len_destination_seq + 1)] for _ in range(len_source_seq + 1) ] ops = [ ["0" for _ in range(len_destination_seq + 1)] for _ in range(len_source_seq + 1) ] for i in range(1, len_source_seq + 1): costs[i][0] = i * delete_cost ops[i][0] = f"D{source_seq[i - 1]:c}" for i in range(1, len_destination_seq + 1): costs[0][i] = i * insert_cost ops[0][i] = f"I{destination_seq[i - 1]:c}" for i in range(1, len_source_seq + 1): for j in range(1, len_destination_seq + 1): if source_seq[i - 1] == destination_seq[j - 1]: costs[i][j] = costs[i - 1][j - 1] + copy_cost ops[i][j] = f"C{source_seq[i - 1]:c}" else: costs[i][j] = costs[i - 1][j - 1] + replace_cost ops[i][j] = f"R{source_seq[i - 1]:c}" + str(destination_seq[j - 1]) if costs[i - 1][j] + delete_cost < costs[i][j]: costs[i][j] = costs[i - 1][j] + delete_cost ops[i][j] = f"D{source_seq[i - 1]:c}" if costs[i][j - 1] + insert_cost < costs[i][j]: costs[i][j] = costs[i][j - 1] + insert_cost ops[i][j] = f"I{destination_seq[j - 1]:c}" return costs, ops
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 ops[i][j][0] == "D": seq = assemble_transformation(ops, i - 1, j) seq.append(ops[i][j]) return seq else: seq = assemble_transformation(ops, i, j - 1) seq.append(ops[i][j]) return seq
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 % 10)) % 10
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 for dynamic programming. dp = [[0 for i in range(len_pattern)] for j in range(len_string)] # since string of zero length match pattern of zero length dp[0][0] = 1 # since pattern of zero length will never match with string of non-zero length for i in range(1, len_string): dp[i][0] = 0 # since string of zero length will match with pattern where there # is at least one * alternatively for j in range(1, len_pattern): dp[0][j] = dp[0][j - 2] if pattern[j - 1] == "*" else 0 # now using bottom-up approach to find for all remaining lengths for i in range(1, len_string): for j in range(1, len_pattern): if input_string[i - 1] == pattern[j - 1] or pattern[j - 1] == ".": dp[i][j] = dp[i - 1][j - 1] elif pattern[j - 1] == "*": if dp[i][j - 2] == 1: dp[i][j] = 1 elif pattern[j - 2] in (input_string[i - 1], "."): dp[i][j] = dp[i - 1][j] else: dp[i][j] = 0 else: dp[i][j] = 0 return bool(dp[-1][-1])
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_words.append(string[last_index : index + 1]) return split_words
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_count in range(abs_length): if char_count < first_str_length: output_list.append(first_str[char_count]) if char_count < second_str_length: output_list.append(second_str[char_count]) return "".join(output_list)
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 "a" <= alpha.lower() <= "z": frequency.add(alpha.lower()) return len(frequency) == 26
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, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173
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) + 1)) for i, c1 in enumerate(first_word): current_row = [i + 1] for j, c2 in enumerate(second_word): # Calculate insertions, deletions and substitutions insertions = previous_row[j + 1] + 1 deletions = current_row[j] + 1 substitutions = previous_row[j] + (c1 != c2) # Get the minimum to append to the current row current_row.append(min(insertions, deletions, substitutions)) # Store the previous row previous_row = current_row # Returns the last element (distance) return previous_row[-1]
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) try: number = int(spanish_id_clean[0:8]) letter = spanish_id_clean[8] except ValueError as ex: raise ValueError(NUMBERS_PLUS_LETTER) from ex if letter.isdigit(): raise ValueError(NUMBERS_PLUS_LETTER) return letter == LOOKUP_LETTERS[number % 23]
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, found {type(use_pascal)}" ) words = input_str.split("_") start_index = 0 if use_pascal else 1 words_to_capitalize = words[start_index:] capitalized_words = [word[0].upper() + word[1:] for word in words_to_capitalize] initial_word = "" if use_pascal else words[0] return "".join([initial_word, *capitalized_words])
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 len(first_str) != len(second_str): return False # Default values for count should be 0 count: DefaultDict[str, int] = defaultdict(int) # For each character in input strings, # increment count in the corresponding for i in range(len(first_str)): count[first_str[i]] += 1 count[second_str[i]] -= 1 return all(_count == 0 for _count in count.values())
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, "next_states": [], "fail_state": 0, "output": [], } ) self.adlist[current_state]["next_states"].append(len(self.adlist) - 1) current_state = len(self.adlist) - 1 else: current_state = next_state self.adlist[current_state]["output"].append(keyword)
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(child) state = self.adlist[r]["fail_state"] while ( self.find_next_state(state, self.adlist[child]["value"]) is None and state != 0 ): state = self.adlist[state]["fail_state"] self.adlist[child]["fail_state"] = self.find_next_state( state, self.adlist[child]["value"] ) if self.adlist[child]["fail_state"] is None: self.adlist[child]["fail_state"] = 0 self.adlist[child]["output"] = ( self.adlist[child]["output"] + self.adlist[self.adlist[child]["fail_state"]]["output"] )
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 current_state != 0 ): current_state = self.adlist[current_state]["fail_state"] next_state = self.find_next_state(current_state, string[i]) if next_state is None: current_state = 0 else: current_state = next_state for key in self.adlist[current_state]["output"]: if key not in result: result[key] = [] result[key].append(i - len(key) + 1) return result
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]: new_input_string += i + "|" # append last character new_input_string += input_string[-1] # we will store the starting and ending of previous furthest ending palindromic # substring l, r = 0, 0 # length[i] shows the length of palindromic substring with center i length = [1 for i in range(len(new_input_string))] # for each character in new_string find corresponding palindromic string start = 0 for j in range(len(new_input_string)): k = 1 if j > r else min(length[l + r - j] // 2, r - j + 1) while ( j - k >= 0 and j + k < len(new_input_string) and new_input_string[k + j] == new_input_string[j - k] ): k += 1 length[j] = 2 * k - 1 # does this string is ending after the previously explored end (that is r) ? # if yes the update the new r to the last index of this if j + k - 1 > r: l = j - k + 1 # noqa: E741 r = j + k - 1 # update max_length and start position if max_length < length[j]: max_length = length[j] start = j # create that string s = new_input_string[start - max_length // 2 : start + max_length // 2 + 1] for i in s: if i != "|": output_string += i return output_string
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 in a two digit number # i.e greater than 9(e.g., 6 × 2 = 12), # then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6), # to get a single digit number. if digit > 9: digit %= 10 digit += 1 cc_number = cc_number[:i] + str(digit) + cc_number[i + 1 :] total += digit # Sum up the remaining digits for i in range(len(cc_number) - 1, -1, -2): total += int(cc_number[i]) return total % 10 == 0
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) <= 16: print(f"{error_message} of its length.") return False if not validate_initial_digits(credit_card_number): print(f"{error_message} of its first two digits.") return False if not luhn_validation(credit_card_number): print(f"{error_message} it fails the Luhn check.") return False print(f"{credit_card_number} is a valid credit card number.") return True
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) # If we already turned on bit for current character's unicode if bitmap >> ch_unicode & 1 == 1: return False bitmap |= ch_bit_index_on return True
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 # loop won't run 32 times it will only run the number of `1` times number &= number - 1 count += 1 return count
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" + "0" * (binary_number_length - len(twos_complement_number)) + twos_complement_number ) if number < 0 else "0" ) return "0b" + twos_complement_number
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" + "".join( str(int(char_a == "1" and char_b == "1")) for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len)) )
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) number = number >> 1 return bit_string
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' and 'int'") result = 0 # iterator over [1 to 32],since we are dealing with 32 bit integer for _ in range(1, 33): # left shift the bits by unity result = result << 1 # get the end bit end_bit = number % 2 # right shift the bits by unity number = number >> 1 # add that bit to our ans result = result | end_bit return get_reverse_bit_string(result)
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[: len(binary_number) - shift_amount] return "0b" + shifted_binary_number
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:]) # Find 2's complement of number binary_number = bin(abs(number) - (1 << binary_number_length))[3:] binary_number = ( "1" + "0" * (binary_number_length - len(binary_number)) + binary_number ) if shift_amount >= len(binary_number): return "0b" + binary_number[0] * len(binary_number) return ( "0b" + binary_number[0] * shift_amount + binary_number[: len(binary_number) - shift_amount] )
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" + "".join( str(int(char_a != char_b)) for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len)) )
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 {timing} seconds") print(f"{get_set_bits_count_using_brian_kernighans_algorithm(number) = }") timing = timeit( "z.get_set_bits_count_using_brian_kernighans_algorithm(25)", setup=setup, ) print(f"timeit() runs in {timing} seconds")
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 in range(len(sequence)): sequence[i] = int(sequence[i], 2) return sequence
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 equivalent to 2^n # recursive answer will generate answer for n-1 bits smaller_sequence = gray_code_sequence_string(bit_count - 1) sequence = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2): generated_no = "0" + smaller_sequence[i] sequence.append(generated_no) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2)): generated_no = "1" + smaller_sequence[i] sequence.append(generated_no) return sequence
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 (char_a, char_b))) for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len)) )
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 candidate return None
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 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True
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