Description
stringlengths
18
161k
Code
stringlengths
15
300k
sort the given list of strings in the way that humans expect the normal python sort algorithm sorts lexicographically so you might not get the results that you expect example1 2 ft 7 in 1 ft 5 in 10 ft 2 in 2 ft 11 in 7 ft 6 in sortedexample1 1 ft 5 in 10 ft 2 in 2 ft 11 in 2 ft 7 in 7 ft 6 in the natural sort algorithm sort based on meaning and not computer code point naturalsortexample1 1 ft 5 in 2 ft 7 in 2 ft 11 in 7 ft 6 in 10 ft 2 in example2 elm11 elm12 elm2 elm0 elm1 elm10 elm13 elm9 sortedexample2 elm11 elm12 elm2 elm0 elm1 elm10 elm13 elm9 naturalsortexample2 elm0 elm1 elm2 elm9 elm10 elm11 elm12 elm13 sort the given list of strings in the way that humans expect the normal python sort algorithm sorts lexicographically so you might not get the results that you expect example1 2 ft 7 in 1 ft 5 in 10 ft 2 in 2 ft 11 in 7 ft 6 in sorted example1 1 ft 5 in 10 ft 2 in 2 ft 11 in 2 ft 7 in 7 ft 6 in the natural sort algorithm sort based on meaning and not computer code point natural_sort example1 1 ft 5 in 2 ft 7 in 2 ft 11 in 7 ft 6 in 10 ft 2 in example2 elm11 elm12 elm2 elm0 elm1 elm10 elm13 elm9 sorted example2 elm11 elm12 elm2 elm0 elm1 elm10 elm13 elm9 natural_sort example2 elm0 elm1 elm2 elm9 elm10 elm11 elm12 elm13
from __future__ import annotations import re def natural_sort(input_list: list[str]) -> list[str]: def alphanum_key(key): return [int(s) if s.isdigit() else s.lower() for s in re.split("([0-9]+)", key)] return sorted(input_list, key=alphanum_key) if __name__ == "__main__": import doctest doctest.testmod()
odd even sort implementation https en wikipedia orgwikiodde28093evensort sort input with odd even sort this algorithm uses the same idea of bubblesort but by first dividing in two phase odd and even originally developed for use on parallel processors with local interconnections param collection mutable ordered sequence of elements return same collection in ascending order examples oddevensort5 4 3 2 1 1 2 3 4 5 oddevensort oddevensort10 1 10 2 10 1 2 10 oddevensort1 2 3 4 1 2 3 4 swapping if elements not in order swapping if elements not in order inputing elements of the list in one line sort input with odd even sort this algorithm uses the same idea of bubblesort but by first dividing in two phase odd and even originally developed for use on parallel processors with local interconnections param collection mutable ordered sequence of elements return same collection in ascending order examples odd_even_sort 5 4 3 2 1 1 2 3 4 5 odd_even_sort odd_even_sort 10 1 10 2 10 1 2 10 odd_even_sort 1 2 3 4 1 2 3 4 until all the indices are traversed keep looping iterating over all even indices swapping if elements not in order iterating over all odd indices swapping if elements not in order inputing elements of the list in one line
def odd_even_sort(input_list: list) -> list: is_sorted = False while is_sorted is False: is_sorted = True for i in range(0, len(input_list) - 1, 2): if input_list[i] > input_list[i + 1]: input_list[i], input_list[i + 1] = input_list[i + 1], input_list[i] is_sorted = False for i in range(1, len(input_list) - 1, 2): if input_list[i] > input_list[i + 1]: input_list[i], input_list[i + 1] = input_list[i + 1], input_list[i] is_sorted = False return input_list if __name__ == "__main__": print("Enter list to be sorted") input_list = [int(x) for x in input().split()] sorted_list = odd_even_sort(input_list) print("The sorted list is") print(sorted_list)
this is an implementation of oddeven transposition sort it works by performing a series of parallel swaps between odd and even pairs of variables in the list this implementation represents each variable in the list with a process and each process communicates with its neighboring processes in the list to perform comparisons they are synchronized with locks and message passing but other forms of synchronization could be used lock used to ensure that two processes do not access a pipe at the same time note this breaks testing on build runner may work better locally processlock lock the function run by the processes that sorts the list position the position in the list the process represents used to know which neighbor we pass our value to value the initial value at listposition lsend rsend the pipes we use to send to our left and right neighbors lrcv rrcv the pipes we use to receive from our left and right neighbors resultpipe the pipe used to send results back to main we perform n swaps since after n swaps we know we are sorted we could stop early if we are sorted already but it takes as long to find out we are sorted as it does to sort the list with this algorithm send your value to your right neighbor receive your right neighbor s value take the lower value since you are on the left send your value to your left neighbor receive your left neighbor s value take the higher value since you are on the right after all swaps are performed send the values back to main the function which creates the processes that perform the parallel swaps arr the list to be sorted oddeventranspositionlistrange10 1 sortedlistrange10 1 true oddeventranspositiona x c sortedx a c true oddeventransposition1 9 42 0 2 8 sorted1 9 42 0 2 8 true oddeventranspositionfalse true false sortedfalse false true true oddeventransposition1 32 0 9 sortedfalse false true false oddeventransposition1 32 0 9 sorted1 0 32 9 0 true unsortedlist 442 98 554 266 491 985 53 529 82 429 oddeventranspositionunsortedlist sortedunsortedlist true unsortedlist 442 98 554 266 491 985 53 529 82 429 oddeventranspositionunsortedlist sortedunsortedlist 1 false initialize the list of pipes where the values will be retrieved creates the processes the first and last process only have one neighbor so they are made outside of the loop start the processes wait for the processes to end and write their values to the list creates a reverse sorted list and sorts it lock used to ensure that two processes do not access a pipe at the same time note this breaks testing on build runner may work better locally process_lock lock the function run by the processes that sorts the list position the position in the list the process represents used to know which neighbor we pass our value to value the initial value at list position lsend rsend the pipes we use to send to our left and right neighbors lrcv rrcv the pipes we use to receive from our left and right neighbors resultpipe the pipe used to send results back to main we perform n swaps since after n swaps we know we are sorted we could stop early if we are sorted already but it takes as long to find out we are sorted as it does to sort the list with this algorithm send your value to your right neighbor receive your right neighbor s value take the lower value since you are on the left send your value to your left neighbor receive your left neighbor s value take the higher value since you are on the right after all swaps are performed send the values back to main the function which creates the processes that perform the parallel swaps arr the list to be sorted odd_even_transposition list range 10 1 sorted list range 10 1 true odd_even_transposition a x c sorted x a c true odd_even_transposition 1 9 42 0 2 8 sorted 1 9 42 0 2 8 true odd_even_transposition false true false sorted false false true true odd_even_transposition 1 32 0 9 sorted false false true false odd_even_transposition 1 32 0 9 sorted 1 0 32 9 0 true unsorted_list 442 98 554 266 491 985 53 529 82 429 odd_even_transposition unsorted_list sorted unsorted_list true unsorted_list 442 98 554 266 491 985 53 529 82 429 odd_even_transposition unsorted_list sorted unsorted_list 1 false initialize the list of pipes where the values will be retrieved creates the processes the first and last process only have one neighbor so they are made outside of the loop start the processes wait for the processes to end and write their values to the list creates a reverse sorted list and sorts it
from multiprocessing import Lock, Pipe, Process def oe_process(position, value, l_send, r_send, lr_cv, rr_cv, result_pipe): process_lock = Lock() for i in range(10): if (i + position) % 2 == 0 and r_send is not None: process_lock.acquire() r_send[1].send(value) process_lock.release() process_lock.acquire() temp = rr_cv[0].recv() process_lock.release() value = min(value, temp) elif (i + position) % 2 != 0 and l_send is not None: process_lock.acquire() l_send[1].send(value) process_lock.release() process_lock.acquire() temp = lr_cv[0].recv() process_lock.release() value = max(value, temp) result_pipe[1].send(value) def odd_even_transposition(arr): process_array_ = [] result_pipe = [] for _ in arr: result_pipe.append(Pipe()) temp_rs = Pipe() temp_rr = Pipe() process_array_.append( Process( target=oe_process, args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]), ) ) temp_lr = temp_rs temp_ls = temp_rr for i in range(1, len(arr) - 1): temp_rs = Pipe() temp_rr = Pipe() process_array_.append( Process( target=oe_process, args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]), ) ) temp_lr = temp_rs temp_ls = temp_rr process_array_.append( Process( target=oe_process, args=( len(arr) - 1, arr[len(arr) - 1], temp_ls, None, temp_lr, None, result_pipe[len(arr) - 1], ), ) ) for p in process_array_: p.start() for p in range(len(result_pipe)): arr[p] = result_pipe[p][0].recv() process_array_[p].join() return arr def main(): arr = list(range(10, 0, -1)) print("Initial List") print(*arr) arr = odd_even_transposition(arr) print("Sorted List\n") print(*arr) if __name__ == "__main__": main()
source https en wikipedia orgwikiodde28093evensort this is a nonparallelized implementation of oddeven transposition sort normally the swaps in each set happen simultaneously without that the algorithm is no better than bubble sort oddeventransposition5 4 3 2 1 1 2 3 4 5 oddeventransposition13 11 18 0 1 1 0 11 13 18 oddeventransposition 1 1 1 1 2 9 2 9 0 1 0 1 1 1 odd_even_transposition 5 4 3 2 1 1 2 3 4 5 odd_even_transposition 13 11 18 0 1 1 0 11 13 18 odd_even_transposition 1 1 1 1 2 9 2 9 0 1 0 1 1 1
def odd_even_transposition(arr: list) -> list: arr_size = len(arr) for _ in range(arr_size): for i in range(_ % 2, arr_size - 1, 2): if arr[i + 1] < arr[i]: arr[i], arr[i + 1] = arr[i + 1], arr[i] return arr if __name__ == "__main__": arr = list(range(10, 0, -1)) print(f"Original: {arr}. Sorted: {odd_even_transposition(arr)}")
this is a pure python implementation of the pancake sort algorithm for doctests run following command python3 m doctest v pancakesort py or python m doctest v pancakesort py for manual testing run python pancakesort py sort array with pancake sort param arr collection containing comparable items return collection ordered in ascending order of items examples pancakesort0 5 3 2 2 0 2 2 3 5 pancakesort pancakesort2 5 45 45 5 2 find the maximum number in arr reverse from 0 to mi reverse whole list sort array with pancake sort param arr collection containing comparable items return collection ordered in ascending order of items examples pancake_sort 0 5 3 2 2 0 2 2 3 5 pancake_sort pancake_sort 2 5 45 45 5 2 find the maximum number in arr reverse from 0 to mi reverse whole list
def pancake_sort(arr): cur = len(arr) while cur > 1: mi = arr.index(max(arr[0:cur])) arr = arr[mi::-1] + arr[mi + 1 : len(arr)] arr = arr[cur - 1 :: -1] + arr[cur : len(arr)] cur -= 1 return arr if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(pancake_sort(unsorted))
a pure python implementation of the patience sort algorithm for more information https en wikipedia orgwikipatiencesorting this algorithm is based on the card game patience for doctests run following command python3 m doctest v patiencesort py for manual testing run python3 patiencesort py a pure implementation of patience sort algorithm in python param collection some mutable ordered collection with heterogeneous comparable items inside return the same collection ordered by ascending examples patiencesort1 9 5 21 17 6 1 5 6 9 17 21 patiencesort patiencesort3 17 48 48 17 3 sort into stacks use a heapbased merge to merge stack efficiently a pure python implementation of the patience sort algorithm for more information https en wikipedia org wiki patience_sorting this algorithm is based on the card game patience for doctests run following command python3 m doctest v patience_sort py for manual testing run python3 patience_sort py a pure implementation of patience sort algorithm in python param collection some mutable ordered collection with heterogeneous comparable items inside return the same collection ordered by ascending examples patience_sort 1 9 5 21 17 6 1 5 6 9 17 21 patience_sort patience_sort 3 17 48 48 17 3 sort into stacks use a heap based merge to merge stack efficiently
from __future__ import annotations from bisect import bisect_left from functools import total_ordering from heapq import merge @total_ordering class Stack(list): def __lt__(self, other): return self[-1] < other[-1] def __eq__(self, other): return self[-1] == other[-1] def patience_sort(collection: list) -> list: stacks: list[Stack] = [] for element in collection: new_stacks = Stack([element]) i = bisect_left(stacks, new_stacks) if i != len(stacks): stacks[i].append(element) else: stacks.append(new_stacks) collection[:] = merge(*(reversed(stack) for stack in stacks)) return collection if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(patience_sort(unsorted))
this is an implementation of pigeon hole sort for doctests run following command python3 m doctest v pigeonsort py or python m doctest v pigeonsort py for manual testing run python pigeonsort py implementation of pigeon hole sort algorithm param array collection of comparable items return collection sorted in ascending order pigeonsort0 5 3 2 2 0 2 2 3 5 pigeonsort pigeonsort2 5 45 45 5 2 compute the variables make the sorting makes the array back by replacing the numbers returns the sorted array implementation of pigeon hole sort algorithm param array collection of comparable items return collection sorted in ascending order pigeon_sort 0 5 3 2 2 0 2 2 3 5 pigeon_sort pigeon_sort 2 5 45 45 5 2 compute the variables make the sorting makes the array back by replacing the numbers returns the sorted array
from __future__ import annotations def pigeon_sort(array: list[int]) -> list[int]: if len(array) == 0: return array _min, _max = min(array), max(array) holes_range = _max - _min + 1 holes, holes_repeat = [0] * holes_range, [0] * holes_range for i in array: index = i - _min holes[index] = i holes_repeat[index] += 1 index = 0 for i in range(holes_range): while holes_repeat[i] > 0: array[index] = holes[i] index += 1 holes_repeat[i] -= 1 return array if __name__ == "__main__": import doctest doctest.testmod() user_input = input("Enter numbers separated by comma:\n") unsorted = [int(x) for x in user_input.split(",")] print(pigeon_sort(unsorted))
python program to implement pigeonhole sorting in python algorithm for the pigeonhole sorting a 8 3 2 7 4 6 8 b sorteda a nondestructive sort pigeonholesorta a destructive sort a b true size of range of values in the list ie number of pigeonholes we need list of pigeonholes of size equal to the variable size populate the pigeonholes putting the elements back into the array in an order python program to implement pigeonhole sorting in python algorithm for the pigeonhole sorting a 8 3 2 7 4 6 8 b sorted a a nondestructive sort pigeonhole_sort a a destructive sort a b true size of range of values in the list ie number of pigeonholes we need min finds the minimum value max finds the maximum value size is difference of max and min values plus one list of pigeonholes of size equal to the variable size populate the pigeonholes putting the elements back into the array in an order
def pigeonhole_sort(a): min_val = min(a) max_val = max(a) size = max_val - min_val + 1 holes = [0] * size for x in a: assert isinstance(x, int), "integers only please" holes[x - min_val] += 1 i = 0 for count in range(size): while holes[count] > 0: holes[count] -= 1 a[i] = count + min_val i += 1 def main(): a = [8, 3, 2, 7, 4, 6, 8] pigeonhole_sort(a) print("Sorted order is:", " ".join(a)) if __name__ == "__main__": main()
a pure python implementation of the quick sort algorithm for doctests run following command python3 m doctest v quicksort py for manual testing run python3 quicksort py a pure python implementation of quick sort algorithm param collection a mutable collection of comparable items return the same collection ordered by ascending examples quicksort0 5 3 2 2 0 2 2 3 5 quicksort quicksort2 5 0 45 45 2 0 5 a pure python implementation of quick sort algorithm param collection a mutable collection of comparable items return the same collection ordered by ascending examples quick_sort 0 5 3 2 2 0 2 2 3 5 quick_sort quick_sort 2 5 0 45 45 2 0 5 use random element as pivot all elements greater than pivot all elements less than or equal to pivot
from __future__ import annotations from random import randrange def quick_sort(collection: list) -> list: if len(collection) < 2: return collection pivot_index = randrange(len(collection)) pivot = collection[pivot_index] greater: list[int] = [] lesser: list[int] = [] for element in collection[:pivot_index]: (greater if element > pivot else lesser).append(element) for element in collection[pivot_index + 1 :]: (greater if element > pivot else lesser).append(element) return [*quick_sort(lesser), pivot, *quick_sort(greater)] if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(quick_sort(unsorted))
a pure python implementation of quick sort algorithminplace with lomuto partition scheme https en wikipedia orgwikiquicksortlomutopartitionscheme param sorting sort list param left left endpoint of sorting param right right endpoint of sorting return none examples nums1 0 5 3 1 2 quicksortlomutopartitionnums1 0 4 nums1 0 1 2 3 5 nums2 quicksortlomutopartitionnums2 0 0 nums2 nums3 2 5 0 4 quicksortlomutopartitionnums3 0 3 nums3 4 2 0 5 example lomutopartition1 5 7 6 0 3 2 threeway radix quicksort https en wikipedia orgwikiquicksortthreewayradixquicksort first divide the list into three parts then recursively sort the less than and greater than partitions threewayradixquicksort threewayradixquicksort1 1 threewayradixquicksort5 2 1 2 0 1 5 2 2 0 1 1 threewayradixquicksort1 2 5 1 2 0 0 5 2 1 1 0 0 1 1 2 2 2 5 5 a pure python implementation of quick sort algorithm in place with lomuto partition scheme https en wikipedia org wiki quicksort lomuto_partition_scheme param sorting sort list param left left endpoint of sorting param right right endpoint of sorting return none examples nums1 0 5 3 1 2 quick_sort_lomuto_partition nums1 0 4 nums1 0 1 2 3 5 nums2 quick_sort_lomuto_partition nums2 0 0 nums2 nums3 2 5 0 4 quick_sort_lomuto_partition nums3 0 3 nums3 4 2 0 5 example lomuto_partition 1 5 7 6 0 3 2 three way radix quicksort https en wikipedia org wiki quicksort three way_radix_quicksort first divide the list into three parts then recursively sort the less than and greater than partitions three_way_radix_quicksort three_way_radix_quicksort 1 1 three_way_radix_quicksort 5 2 1 2 0 1 5 2 2 0 1 1 three_way_radix_quicksort 1 2 5 1 2 0 0 5 2 1 1 0 0 1 1 2 2 2 5 5
def quick_sort_3partition(sorting: list, left: int, right: int) -> None: if right <= left: return a = i = left b = right pivot = sorting[left] while i <= b: if sorting[i] < pivot: sorting[a], sorting[i] = sorting[i], sorting[a] a += 1 i += 1 elif sorting[i] > pivot: sorting[b], sorting[i] = sorting[i], sorting[b] b -= 1 else: i += 1 quick_sort_3partition(sorting, left, a - 1) quick_sort_3partition(sorting, b + 1, right) def quick_sort_lomuto_partition(sorting: list, left: int, right: int) -> None: if left < right: pivot_index = lomuto_partition(sorting, left, right) quick_sort_lomuto_partition(sorting, left, pivot_index - 1) quick_sort_lomuto_partition(sorting, pivot_index + 1, right) def lomuto_partition(sorting: list, left: int, right: int) -> int: pivot = sorting[right] store_index = left for i in range(left, right): if sorting[i] < pivot: sorting[store_index], sorting[i] = sorting[i], sorting[store_index] store_index += 1 sorting[right], sorting[store_index] = sorting[store_index], sorting[right] return store_index def three_way_radix_quicksort(sorting: list) -> list: if len(sorting) <= 1: return sorting return ( three_way_radix_quicksort([i for i in sorting if i < sorting[0]]) + [i for i in sorting if i == sorting[0]] + three_way_radix_quicksort([i for i in sorting if i > sorting[0]]) ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] quick_sort_3partition(unsorted, 0, len(unsorted) - 1) print(unsorted)
this is a pure python implementation of the radix sort algorithm source https en wikipedia orgwikiradixsort examples radixsort0 5 3 2 2 0 2 2 3 5 radixsortlistrange15 sortedrange15 true radixsortlistrange14 1 1 sortedrange15 true radixsort1 100 10 1000 sorted1 100 10 1000 true declare and initialize empty buckets split listofints between the buckets put each buckets contents into listofints move to next examples radix_sort 0 5 3 2 2 0 2 2 3 5 radix_sort list range 15 sorted range 15 true radix_sort list range 14 1 1 sorted range 15 true radix_sort 1 100 10 1000 sorted 1 100 10 1000 true declare and initialize empty buckets split list_of_ints between the buckets put each buckets contents into list_of_ints move to next
from __future__ import annotations RADIX = 10 def radix_sort(list_of_ints: list[int]) -> list[int]: placement = 1 max_digit = max(list_of_ints) while placement <= max_digit: buckets: list[list] = [[] for _ in range(RADIX)] for i in list_of_ints: tmp = int((i / placement) % RADIX) buckets[tmp].append(i) a = 0 for b in range(RADIX): for i in buckets[b]: list_of_ints[a] = i a += 1 placement *= RADIX return list_of_ints if __name__ == "__main__": import doctest doctest.testmod()
a recursive implementation of the insertion sort algorithm given a collection of numbers and its length sorts the collections in ascending order param collection a mutable collection of comparable elements param n the length of collections col 1 2 1 recinsertionsortcol lencol col 1 1 2 col 2 1 0 1 2 recinsertionsortcol lencol col 2 1 0 1 2 col 1 recinsertionsortcol lencol col 1 checks if the entire collection has been sorted inserts the index1th element into place col 3 2 4 2 insertnextcol 1 col 2 3 4 2 col 3 2 3 insertnextcol 2 col 3 2 3 col insertnextcol 1 col checks order between adjacent elements swaps adjacent elements since they are not in ascending order given a collection of numbers and its length sorts the collections in ascending order param collection a mutable collection of comparable elements param n the length of collections col 1 2 1 rec_insertion_sort col len col col 1 1 2 col 2 1 0 1 2 rec_insertion_sort col len col col 2 1 0 1 2 col 1 rec_insertion_sort col len col col 1 checks if the entire collection has been sorted inserts the index 1 th element into place col 3 2 4 2 insert_next col 1 col 2 3 4 2 col 3 2 3 insert_next col 2 col 3 2 3 col insert_next col 1 col checks order between adjacent elements swaps adjacent elements since they are not in ascending order
from __future__ import annotations def rec_insertion_sort(collection: list, n: int): if len(collection) <= 1 or n <= 1: return insert_next(collection, n - 1) rec_insertion_sort(collection, n - 1) def insert_next(collection: list, index: int): if index >= len(collection) or collection[index - 1] <= collection[index]: return collection[index - 1], collection[index] = ( collection[index], collection[index - 1], ) insert_next(collection, index + 1) if __name__ == "__main__": numbers = input("Enter integers separated by spaces: ") number_list: list[int] = [int(num) for num in numbers.split()] rec_insertion_sort(number_list, len(number_list)) print(number_list)
a merge sort which accepts an array as input and recursively splits an array in half and sorts and combines them https en wikipedia orgwikimergesort def mergearr listint listint if lenarr 1 middlelength lenarr 2 finds the middle of the array leftarray arr middlelength creates an array of the elements in the first half rightarray arr middlelength creates an array of the elements in the second half leftsize lenleftarray rightsize lenrightarray mergeleftarray starts sorting the left mergerightarray starts sorting the right leftindex 0 left counter rightindex 0 right counter index 0 position counter while leftindex leftsize and rightindex rightsize runs until the lowers size of the left and right are sorted if leftarrayleftindex rightarrayrightindex arrindex leftarrayleftindex leftindex 1 else arrindex rightarrayrightindex rightindex 1 index 1 while leftindex leftsize adds the left over elements in the left half of the array arrindex leftarrayleftindex leftindex 1 index 1 while rightindex rightsize adds the left over elements in the right half of the array arrindex rightarrayrightindex rightindex 1 index 1 return arr if name main import doctest doctest testmod https en wikipedia org wiki merge_sort return a sorted array merge 10 9 8 7 6 5 4 3 2 1 1 2 3 4 5 6 7 8 9 10 merge 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 merge 10 22 1 2 3 9 15 23 1 2 3 9 10 15 22 23 merge 100 100 merge finds the middle of the array creates an array of the elements in the first half creates an array of the elements in the second half starts sorting the left starts sorting the right left counter right counter position counter runs until the lowers size of the left and right are sorted adds the left over elements in the left half of the array adds the left over elements in the right half of the array
def merge(arr: list[int]) -> list[int]: if len(arr) > 1: middle_length = len(arr) // 2 left_array = arr[ :middle_length ] right_array = arr[ middle_length: ] left_size = len(left_array) right_size = len(right_array) merge(left_array) merge(right_array) left_index = 0 right_index = 0 index = 0 while ( left_index < left_size and right_index < right_size ): if left_array[left_index] < right_array[right_index]: arr[index] = left_array[left_index] left_index += 1 else: arr[index] = right_array[right_index] right_index += 1 index += 1 while ( left_index < left_size ): arr[index] = left_array[left_index] left_index += 1 index += 1 while ( right_index < right_size ): arr[index] = right_array[right_index] right_index += 1 index += 1 return arr if __name__ == "__main__": import doctest doctest.testmod()
for data in 2 1 0 2 2 1 1 0 quicksort quicksortdata sorteddata true true true for data in 2 1 0 2 2 1 1 0 quick_sort quick_sort data sorted data true true true
def quick_sort(data: list) -> list: if len(data) <= 1: return data else: return [ *quick_sort([e for e in data[1:] if e <= data[0]]), data[0], *quick_sort([e for e in data[1:] if e > data[0]]), ] if __name__ == "__main__": import doctest doctest.testmod()
sorts a list in ascending order using the selection sort algorithm param collection a list of integers to be sorted return the sorted list examples selectionsort0 5 3 2 2 0 2 2 3 5 selectionsort selectionsort2 5 45 45 5 2 sorts a list in ascending order using the selection sort algorithm param collection a list of integers to be sorted return the sorted list examples selection_sort 0 5 3 2 2 0 2 2 3 5 selection_sort selection_sort 2 5 45 45 5 2
def selection_sort(collection: list[int]) -> list[int]: length = len(collection) for i in range(length - 1): min_index = i for k in range(i + 1, length): if collection[k] < collection[min_index]: min_index = k if min_index != i: collection[i], collection[min_index] = collection[min_index], collection[i] return collection if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] sorted_list = selection_sort(unsorted) print("Sorted List:", sorted_list)
https en wikipedia orgwikishellsortpseudocode pure implementation of shell sort algorithm in python param collection some mutable ordered collection with heterogeneous comparable items inside return the same collection ordered by ascending shellsort0 5 3 2 2 0 2 2 3 5 shellsort shellsort2 5 45 45 5 2 marcin ciura s gap sequence pure implementation of shell sort algorithm in python param collection some mutable ordered collection with heterogeneous comparable items inside return the same collection ordered by ascending shell_sort 0 5 3 2 2 0 2 2 3 5 shell_sort shell_sort 2 5 45 45 5 2 marcin ciura s gap sequence
def shell_sort(collection: list[int]) -> list[int]: gaps = [701, 301, 132, 57, 23, 10, 4, 1] for gap in gaps: for i in range(gap, len(collection)): insert_value = collection[i] j = i while j >= gap and collection[j - gap] > insert_value: collection[j] = collection[j - gap] j -= gap if j != i: collection[j] = insert_value return collection if __name__ == "__main__": from doctest import testmod testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(shell_sort(unsorted))
this function implements the shell sort algorithm which is slightly faster than its pure implementation this shell sort is implemented using a gap which shrinks by a certain factor each iteration in this implementation the gap is initially set to the length of the collection the gap is then reduced by a certain factor 1 3 each iteration for each iteration the algorithm compares elements that are a certain number of positions apart determined by the gap if the element at the higher position is greater than the element at the lower position the two elements are swapped the process is repeated until the gap is equal to 1 the reason this is more efficient is that it reduces the number of comparisons that need to be made by using a smaller gap the list is sorted more quickly implementation of shell sort algorithm in python param collection some mutable ordered collection with heterogeneous comparable items inside return the same collection ordered by ascending shellsort3 2 1 1 2 3 shellsort shellsort1 1 choose an initial gap value set the gap value to be decreased by a factor of 1 3 after each iteration continue sorting until the gap is 1 decrease the gap value sort the elements using insertion sort implementation of shell sort algorithm in python param collection some mutable ordered collection with heterogeneous comparable items inside return the same collection ordered by ascending shell_sort 3 2 1 1 2 3 shell_sort shell_sort 1 1 choose an initial gap value set the gap value to be decreased by a factor of 1 3 after each iteration continue sorting until the gap is 1 decrease the gap value sort the elements using insertion sort
def shell_sort(collection: list) -> list: gap = len(collection) shrink = 1.3 while gap > 1: gap = int(gap / shrink) for i in range(gap, len(collection)): temp = collection[i] j = i while j >= gap and collection[j - gap] > temp: collection[j] = collection[j - gap] j -= gap collection[j] = temp return collection if __name__ == "__main__": import doctest doctest.testmod()
slowsort is a sorting algorithm it is of humorous nature and not useful it s based on the principle of multiply and surrender a tongueincheek joke of divide and conquer it was published in 1986 by andrei broder and jorge stolfi in their paper pessimal algorithms and simplexity analysis a parody of optimal algorithms and complexity analysis source https en wikipedia orgwikislowsort sorts sequencestart end both inclusive inplace start defaults to 0 if not given end defaults to lensequence 1 if not given it returns none seq 1 6 2 5 3 4 4 5 slowsortseq seq 1 2 3 4 4 5 5 6 seq slowsortseq seq seq 2 slowsortseq seq 2 seq 1 2 3 4 slowsortseq seq 1 2 3 4 seq 4 3 2 1 slowsortseq seq 1 2 3 4 seq 9 8 7 6 5 4 3 2 1 0 slowsortseq 2 7 seq 9 8 2 3 4 5 6 7 1 0 seq 9 8 7 6 5 4 3 2 1 0 slowsortseq end 4 seq 5 6 7 8 9 4 3 2 1 0 seq 9 8 7 6 5 4 3 2 1 0 slowsortseq start 5 seq 9 8 7 6 5 0 1 2 3 4 sorts sequence start end both inclusive in place start defaults to 0 if not given end defaults to len sequence 1 if not given it returns none seq 1 6 2 5 3 4 4 5 slowsort seq seq 1 2 3 4 4 5 5 6 seq slowsort seq seq seq 2 slowsort seq seq 2 seq 1 2 3 4 slowsort seq seq 1 2 3 4 seq 4 3 2 1 slowsort seq seq 1 2 3 4 seq 9 8 7 6 5 4 3 2 1 0 slowsort seq 2 7 seq 9 8 2 3 4 5 6 7 1 0 seq 9 8 7 6 5 4 3 2 1 0 slowsort seq end 4 seq 5 6 7 8 9 4 3 2 1 0 seq 9 8 7 6 5 4 3 2 1 0 slowsort seq start 5 seq 9 8 7 6 5 0 1 2 3 4
from __future__ import annotations def slowsort(sequence: list, start: int | None = None, end: int | None = None) -> None: if start is None: start = 0 if end is None: end = len(sequence) - 1 if start >= end: return mid = (start + end) // 2 slowsort(sequence, start, mid) slowsort(sequence, mid + 1, end) if sequence[end] < sequence[mid]: sequence[end], sequence[mid] = sequence[mid], sequence[end] slowsort(sequence, start, end - 1) if __name__ == "__main__": from doctest import testmod testmod()
examples stoogesort18 1 0 7 1 1 2 2 7 1 1 0 2 2 18 1 stoogesort if first element is smaller than the last then swap them if there are more than 2 elements in the array recursively sort first 23 elements recursively sort last 23 elements recursively sort first 23 elements examples stooge_sort 18 1 0 7 1 1 2 2 7 1 1 0 2 2 18 1 stooge_sort if first element is smaller than the last then swap them if there are more than 2 elements in the array recursively sort first 2 3 elements recursively sort last 2 3 elements recursively sort first 2 3 elements
def stooge_sort(arr: list[int]) -> list[int]: stooge(arr, 0, len(arr) - 1) return arr def stooge(arr: list[int], i: int, h: int) -> None: if i >= h: return if arr[i] > arr[h]: arr[i], arr[h] = arr[h], arr[i] if h - i + 1 > 2: t = (int)((h - i + 1) / 3) stooge(arr, i, (h - t)) stooge(arr, i + t, (h)) stooge(arr, i, (h - t)) if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(stooge_sort(unsorted))
strand sort implementation source https en wikipedia orgwikistrandsort param arr unordered input list param reverse descent ordering flag param solution ordered items container examples strandsort4 2 5 3 0 1 0 1 2 3 4 5 strandsort4 2 5 3 0 1 reversetrue 5 4 3 2 1 0 merging sublist into solution list strand sort implementation source https en wikipedia org wiki strand_sort param arr unordered input list param reverse descent ordering flag param solution ordered items container examples strand_sort 4 2 5 3 0 1 0 1 2 3 4 5 strand_sort 4 2 5 3 0 1 reverse true 5 4 3 2 1 0 merging sublist into solution list
import operator def strand_sort(arr: list, reverse: bool = False, solution: list | None = None) -> list: _operator = operator.lt if reverse else operator.gt solution = solution or [] if not arr: return solution sublist = [arr.pop(0)] for i, item in enumerate(arr): if _operator(item, sublist[-1]): sublist.append(item) arr.pop(i) if not solution: solution.extend(sublist) else: while sublist: item = sublist.pop(0) for i, xx in enumerate(solution): if not _operator(item, xx): solution.insert(i, item) break else: solution.append(item) strand_sort(arr, reverse, solution) return solution if __name__ == "__main__": assert strand_sort([4, 3, 5, 1, 2]) == [1, 2, 3, 4, 5] assert strand_sort([4, 3, 5, 1, 2], reverse=True) == [5, 4, 3, 2, 1]
timsortpython p h n o t y timsort1 1 1 0 1 1 1 1 1 1 0 1 1 1 timsortlistreversedlistrange7 0 1 2 3 4 5 6 timsort3 2 1 insertionsort3 2 1 true timsort3 2 1 sorted3 2 1 true tim_sort python p h n o t y tim_sort 1 1 1 0 1 1 1 1 1 1 0 1 1 1 tim_sort list reversed list range 7 0 1 2 3 4 5 6 tim_sort 3 2 1 insertion_sort 3 2 1 true tim_sort 3 2 1 sorted 3 2 1 true
def binary_search(lst, item, start, end): if start == end: return start if lst[start] > item else start + 1 if start > end: return start mid = (start + end) // 2 if lst[mid] < item: return binary_search(lst, item, mid + 1, end) elif lst[mid] > item: return binary_search(lst, item, start, mid - 1) else: return mid def insertion_sort(lst): length = len(lst) for index in range(1, length): value = lst[index] pos = binary_search(lst, value, 0, index - 1) lst = lst[:pos] + [value] + lst[pos:index] + lst[index + 1 :] return lst def merge(left, right): if not left: return right if not right: return left if left[0] < right[0]: return [left[0], *merge(left[1:], right)] return [right[0], *merge(left, right[1:])] def tim_sort(lst): length = len(lst) runs, sorted_runs = [], [] new_run = [lst[0]] sorted_array = [] i = 1 while i < length: if lst[i] < lst[i - 1]: runs.append(new_run) new_run = [lst[i]] else: new_run.append(lst[i]) i += 1 runs.append(new_run) for run in runs: sorted_runs.append(insertion_sort(run)) for run in sorted_runs: sorted_array = merge(sorted_array, run) return sorted_array def main(): lst = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7] sorted_lst = tim_sort(lst) print(sorted_lst) if __name__ == "__main__": main()
topological sort a b c d e edges dictstr liststr a c b b d e c d e vertices liststr a b c d e def topologicalsortstart str visited liststr sort liststr liststr add current to visited if neighbor not in visited visit if all neighbors visited add current to sort if all vertices haven t been visited select a new one to visit return sort a b c d e perform topological sort on a directed acyclic graph add current to visited if neighbor not in visited visit if all neighbors visited add current to sort if all vertices haven t been visited select a new one to visit return sort
edges: dict[str, list[str]] = { "a": ["c", "b"], "b": ["d", "e"], "c": [], "d": [], "e": [], } vertices: list[str] = ["a", "b", "c", "d", "e"] def topological_sort(start: str, visited: list[str], sort: list[str]) -> list[str]: current = start visited.append(current) neighbors = edges[current] for neighbor in neighbors: if neighbor not in visited: sort = topological_sort(neighbor, visited, sort) sort.append(current) if len(visited) != len(vertices): for vertice in vertices: if vertice not in visited: sort = topological_sort(vertice, visited, sort) return sort if __name__ == "__main__": sort = topological_sort("a", [], []) print(sort)
treesort algorithm build a binary search tree and then iterate thru it to get a sorted list treesort treesort1 1 treesort1 2 1 2 treesort5 2 7 2 5 7 treesort5 4 9 2 7 4 2 5 7 9 treesort5 6 1 1 4 37 2 7 1 1 2 4 5 6 7 37 treesortrange10 10 1 tuplesortedrange10 10 1 true tree_sort tree_sort 1 1 tree_sort 1 2 1 2 tree_sort 5 2 7 2 5 7 tree_sort 5 4 9 2 7 4 2 5 7 9 tree_sort 5 6 1 1 4 37 2 7 1 1 2 4 5 6 7 37 tree_sort range 10 10 1 tuple sorted range 10 10 1 true
from __future__ import annotations from collections.abc import Iterator from dataclasses import dataclass @dataclass class Node: val: int left: Node | None = None right: Node | None = None def __iter__(self) -> Iterator[int]: if self.left: yield from self.left yield self.val if self.right: yield from self.right def __len__(self) -> int: return sum(1 for _ in self) def insert(self, val: int) -> None: if val < self.val: if self.left is None: self.left = Node(val) else: self.left.insert(val) elif val > self.val: if self.right is None: self.right = Node(val) else: self.right.insert(val) def tree_sort(arr: list[int]) -> tuple[int, ...]: if len(arr) == 0: return tuple(arr) root = Node(arr[0]) for item in arr[1:]: root.insert(item) return tuple(root) if __name__ == "__main__": import doctest doctest.testmod() print(f"{tree_sort([5, 6, 1, -1, 4, 37, -3, 7]) = }")
python implementation of a sort algorithm best case scenario on worst case scenario on2 because native python functions min max and remove are already on pure implementation of the fastest merge sort algorithm in python param collection some mutable ordered collection with heterogeneous comparable items inside return a collection ordered by ascending examples mergesort0 5 3 2 2 0 2 2 3 5 mergesort mergesort2 5 45 45 5 2 pure implementation of the fastest merge sort algorithm in python param collection some mutable ordered collection with heterogeneous comparable items inside return a collection ordered by ascending examples merge_sort 0 5 3 2 2 0 2 2 3 5 merge_sort merge_sort 2 5 45 45 5 2
def merge_sort(collection): start, end = [], [] while len(collection) > 1: min_one, max_one = min(collection), max(collection) start.append(min_one) end.append(max_one) collection.remove(min_one) collection.remove(max_one) end.reverse() return start + collection + end if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(*merge_sort(unsorted), sep=",")
wiggle sort given an unsorted array nums reorder it such that nums0 nums1 nums2 nums3 for example if input numbers 3 5 2 1 6 4 one possible wiggle sorted answer is 3 5 1 6 2 4 python implementation of wiggle example wigglesort0 5 3 2 2 0 5 2 3 2 wigglesort wigglesort2 5 45 45 2 5 wigglesort2 1 5 68 45 11 45 11 2 1 5 68 python implementation of wiggle example wiggle_sort 0 5 3 2 2 0 5 2 3 2 wiggle_sort wiggle_sort 2 5 45 45 2 5 wiggle_sort 2 1 5 68 45 11 45 11 2 1 5 68
def wiggle_sort(nums: list) -> list: for i, _ in enumerate(nums): if (i % 2 == 1) == (nums[i - 1] > nums[i]): nums[i - 1], nums[i] = nums[i], nums[i - 1] return nums if __name__ == "__main__": print("Enter the array elements:") array = list(map(int, input().split())) print("The unsorted array is:") print(array) print("Array after Wiggle sort:") print(wiggle_sort(array))
a automatonwhat hat ver er a searchinwhatever err wherever what 0 hat 1 ver 5 25 er 6 10 22 26 a automaton what hat ver er a search_in whatever err wherever what 0 hat 1 ver 5 25 er 6 10 22 26 returns a dict with keywords and list of its occurrences
from __future__ import annotations from collections import deque class Automaton: 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() 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 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) 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"] ) def search_in(self, string: str) -> dict[str, list[int]]: result: dict = {} 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 if __name__ == "__main__": import doctest doctest.testmod()
return the alternative arrangements of the two strings param firststr param secondstr return string alternativestringarrangeabcd xy axbycd alternativestringarrangexy abcd xaybcd alternativestringarrangeab xyz axbyz alternativestringarrangeabc abc return the alternative arrangements of the two strings param first_str param second_str return string alternative_string_arrange abcd xy axbycd alternative_string_arrange xy abcd xaybcd alternative_string_arrange ab xyz axbyz alternative_string_arrange abc abc
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) if __name__ == "__main__": print(alternative_string_arrange("AB", "XYZ"), end=" ")
return a word sorted signaturetest estt signaturethis is a test aehiisssttt signaturefinaltest aefilnstt return every anagram of the given word anagram test sett stet test anagram this is a test anagram final final return a word sorted signature test estt signature this is a test aehiisssttt signature finaltest aefilnstt return every anagram of the given word anagram test sett stet test anagram this is a test anagram final final
from __future__ import annotations import collections import pprint from pathlib import Path def signature(word: str) -> str: return "".join(sorted(word)) def anagram(my_word: str) -> list[str]: return word_by_signature[signature(my_word)] data: str = Path(__file__).parent.joinpath("words.txt").read_text(encoding="utf-8") word_list = sorted({word.strip().lower() for word in data.splitlines()}) word_by_signature = collections.defaultdict(list) for word in word_list: word_by_signature[signature(word)].append(word) if __name__ == "__main__": all_anagrams = {word: anagram(word) for word in word_list if len(anagram(word)) > 1} with open("anagrams.txt", "w") as file: file.write("all_anagrams = \n ") file.write(pprint.pformat(all_anagrams))
https en wikipedia orgwikicheckdigitalgorithms returns the last digit of barcode by excluding the last digit first and then computing to reach the actual last digit from the remaining 12 digits getcheckdigit8718452538119 9 getcheckdigit87184523 5 getcheckdigit87193425381086 9 getcheckdigitx for x in range0 100 10 0 7 4 1 8 5 2 9 6 3 extract and check each digit checks for length of barcode and lastdigit returns boolean value of validity of barcode isvalid8718452538119 true isvalid87184525 false isvalid87193425381089 false isvalid0 false isvaliddwefgiweuf traceback most recent call last nameerror name dwefgiweuf is not defined returns the barcode as an integer getbarcode8718452538119 8718452538119 getbarcodedwefgiweuf traceback most recent call last valueerror barcode dwefgiweuf has alphabetic characters enter a barcode returns the last digit of barcode by excluding the last digit first and then computing to reach the actual last digit from the remaining 12 digits get_check_digit 8718452538119 9 get_check_digit 87184523 5 get_check_digit 87193425381086 9 get_check_digit x for x in range 0 100 10 0 7 4 1 8 5 2 9 6 3 exclude the last digit extract and check each digit checks for length of barcode and last digit returns boolean value of validity of barcode is_valid 8718452538119 true is_valid 87184525 false is_valid 87193425381089 false is_valid 0 false is_valid dwefgiweuf traceback most recent call last nameerror name dwefgiweuf is not defined returns the barcode as an integer get_barcode 8718452538119 8718452538119 get_barcode dwefgiweuf traceback most recent call last valueerror barcode dwefgiweuf has alphabetic characters enter a barcode
def get_check_digit(barcode: int) -> int: barcode //= 10 checker = False s = 0 while barcode != 0: mult = 1 if checker else 3 s += mult * (barcode % 10) barcode //= 10 checker = not checker return (10 - (s % 10)) % 10 def is_valid(barcode: int) -> bool: return len(str(barcode)) == 13 and get_check_digit(barcode) == barcode % 10 def get_barcode(barcode: str) -> int: if str(barcode).isalpha(): msg = f"Barcode '{barcode}' has alphabetic characters." raise ValueError(msg) elif int(barcode) < 0: raise ValueError("The entered barcode has a negative value. Try again.") else: return int(barcode) if __name__ == "__main__": import doctest doctest.testmod() barcode = get_barcode(input("Barcode: ").strip()) if is_valid(barcode): print(f"'{barcode}' is a valid barcode.") else: print(f"'{barcode}' is NOT a valid barcode.")
bitap exact string matching https en wikipedia orgwikibitapalgorithm searches for a pattern inside text and returns the index of the first occurrence of the pattern both text and pattern consist of lowercase alphabetical characters only complexity omn n length of text m length of pattern python doctests can be run using this command python3 m doctest v bitapstringmatch py retrieves the index of the first occurrence of pattern in text args text a string consisting only of lowercase alphabetical characters pattern a string consisting only of lowercase alphabetical characters returns int the index where pattern first occurs return 1 if not found bitapstringmatch abdabababc ababc 5 bitapstringmatch aaaaaaaaaaaaaaaaaa a 0 bitapstringmatch zxywsijdfosdfnso zxywsijdfosdfnso 0 bitapstringmatch abdabababc 0 bitapstringmatch abdabababc c 9 bitapstringmatch abdabababc fofosdfo 1 bitapstringmatch abdab fofosdfo 1 initial state of bit string 1110 bit 0 if character appears at index and 1 otherwise for the pattern mask for this character set the bit to 0 for each i the character appears if this character does not appear in pattern it s pattern mask is 1111 performing a bitwise or between state and 1111 will reset the state to 1111 and start searching the start of pattern again if the mth bit counting right to left of the state is 0 then we have found pattern in text retrieves the index of the first occurrence of pattern in text args text a string consisting only of lowercase alphabetical characters pattern a string consisting only of lowercase alphabetical characters returns int the index where pattern first occurs return 1 if not found bitap_string_match abdabababc ababc 5 bitap_string_match aaaaaaaaaaaaaaaaaa a 0 bitap_string_match zxywsijdfosdfnso zxywsijdfosdfnso 0 bitap_string_match abdabababc 0 bitap_string_match abdabababc c 9 bitap_string_match abdabababc fofosdfo 1 bitap_string_match abdab fofosdfo 1 initial state of bit string 1110 bit 0 if character appears at index and 1 otherwise 1111 for the pattern mask for this character set the bit to 0 for each i the character appears if this character does not appear in pattern it s pattern mask is 1111 performing a bitwise or between state and 1111 will reset the state to 1111 and start searching the start of pattern again if the mth bit counting right to left of the state is 0 then we have found pattern in text
def bitap_string_match(text: str, pattern: str) -> int: if not pattern: return 0 m = len(pattern) if m > len(text): return -1 state = ~1 pattern_mask: list[int] = [~0] * 27 for i, char in enumerate(pattern): pattern_index: int = ord(char) - ord("a") pattern_mask[pattern_index] &= ~(1 << i) for i, char in enumerate(text): text_index = ord(char) - ord("a") state |= pattern_mask[text_index] state <<= 1 if (state & (1 << m)) == 0: return i - m + 1 return -1 if __name__ == "__main__": import doctest doctest.testmod()
the algorithm finds the pattern in given text using following rule the badcharacter rule considers the mismatched character in text the next occurrence of that character to the left in pattern is found if the mismatched character occurs to the left in pattern a shift is proposed that aligns text block and pattern if the mismatched character does not occur to the left in pattern a shift is proposed that moves the entirety of pattern past the point of mismatch in the text if there no mismatch then the pattern matches with text block time complexity onm nlength of main string mlength of pattern string finds the index of char in pattern in reverse order parameters char chr character to be searched returns i int index of char from last in pattern 1 int if char is not found in pattern find the index of mismatched character in text when compared with pattern from last parameters currentpos int current index position of text returns i int index of mismatched char from last in text 1 int if there is no mismatch between pattern and text block searches pattern in text and returns index positions finds the index of char in pattern in reverse order parameters char chr character to be searched returns i int index of char from last in pattern 1 int if char is not found in pattern find the index of mis matched character in text when compared with pattern from last parameters current_pos int current index position of text returns i int index of mismatched char from last in text 1 int if there is no mismatch between pattern and text block searches pattern in text and returns index positions shifting index lgtm py multiple definition
from __future__ import annotations class BoyerMooreSearch: def __init__(self, text: str, pattern: str): self.text, self.pattern = text, pattern self.textLen, self.patLen = len(text), len(pattern) 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 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 def bad_character_heuristic(self) -> list[int]: 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 ) return positions text = "ABAABA" pattern = "AB" bms = BoyerMooreSearch(text, pattern) positions = bms.bad_character_heuristic() if len(positions) == 0: print("No match found") else: print("Pattern found in following positions: ") print(positions)
transforms a camelcase or pascalcase string to snakecase cameltosnakecasesomerandomstring somerandomstring cameltosnakecasesomerandomstrng somerandomstrng cameltosnakecase123somerandom123string123 123somerandom123string123 cameltosnakecase123somerandom123string123 123somerandom123string123 cameltosnakecase123 traceback most recent call last valueerror expected string as input found class int check for invalid input type if char is lowercase but proceeded by a digit if char is a digit proceeded by a letter if char is not alphanumeric remove leading underscore transforms a camelcase or pascalcase string to snake_case camel_to_snake_case somerandomstring some_random_string camel_to_snake_case somerandomstr ng some_random_str_ng camel_to_snake_case 123somerandom123string123 123_some_random_123_string_123 camel_to_snake_case 123somerandom123string123 123_some_random_123_string_123 camel_to_snake_case 123 traceback most recent call last valueerror expected string as input found class int check for invalid input type if char is lowercase but proceeded by a digit if char is a digit proceeded by a letter if char is not alphanumeric remove leading underscore
def camel_to_snake_case(input_str: str) -> str: if not isinstance(input_str, str): msg = f"Expected string as input, found {type(input_str)}" raise ValueError(msg) snake_str = "" for index, char in enumerate(input_str): if char.isupper(): snake_str += "_" + char.lower() elif input_str[index - 1].isdigit() and char.islower(): snake_str += "_" + char elif input_str[index - 1].isalpha() and char.isnumeric(): snake_str += "_" + char.lower() elif not char.isalnum(): snake_str += "_" else: snake_str += char if snake_str[0] == "_": snake_str = snake_str[1:] return snake_str if __name__ == "__main__": from doctest import testmod testmod()
susmith98 problem description check if characters of the given string can be rearranged to form a palindrome counter is faster for long strings and noncounter is faster for short strings a palindrome is a string that reads the same forward as it does backwards examples of palindromes mom dad malayalam canstringberearrangedaspalindromecountermomo true canstringberearrangedaspalindromecountermother false canstringberearrangedaspalindromecounterfather false canstringberearrangedaspalindromecountera man a plan a canal panama true a palindrome is a string that reads the same forward as it does backwards examples of palindromes mom dad malayalam canstringberearrangedaspalindromemomo true canstringberearrangedaspalindromemother false canstringberearrangedaspalindromefather false canstringberearrangedaspalindromecountera man a plan a canal panama true characterfreqdict stores the frequency of every character in the input string above line of code is equivalent to 1 getting the frequency of current character till previous index characterfreq characterfreqdict getcharacter 0 2 incrementing the frequency of current character by 1 characterfreq characterfreq 1 3 updating the frequency of current character characterfreqdictcharacter characterfreq observations even length palindrome every character appears even no of times odd length palindrome every character appears even no of times except for one character logic step 1 we ll count number of characters that appear odd number of times i e oddchar step 2 if we find more than 1 character that appears odd number of times it is not possible to rearrange as a palindrome benchmark code for comparing above 2 functions susmith98 problem description check if characters of the given string can be rearranged to form a palindrome counter is faster for long strings and non counter is faster for short strings a palindrome is a string that reads the same forward as it does backwards examples of palindromes mom dad malayalam can_string_be_rearranged_as_palindrome_counter momo true can_string_be_rearranged_as_palindrome_counter mother false can_string_be_rearranged_as_palindrome_counter father false can_string_be_rearranged_as_palindrome_counter a man a plan a canal panama true a palindrome is a string that reads the same forward as it does backwards examples of palindromes mom dad malayalam can_string_be_rearranged_as_palindrome momo true can_string_be_rearranged_as_palindrome mother false can_string_be_rearranged_as_palindrome father false can_string_be_rearranged_as_palindrome_counter a man a plan a canal panama true character_freq_dict stores the frequency of every character in the input string above line of code is equivalent to 1 getting the frequency of current character till previous index character_freq character_freq_dict get character 0 2 incrementing the frequency of current character by 1 character_freq character_freq 1 3 updating the frequency of current character character_freq_dict character character_freq observations even length palindrome every character appears even no of times odd length palindrome every character appears even no of times except for one character logic step 1 we ll count number of characters that appear odd number of times i e oddchar step 2 if we find more than 1 character that appears odd number of times it is not possible to rearrange as a palindrome benchmark code for comparing above 2 functions
from collections import Counter from timeit import timeit 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 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: 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 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", ) if __name__ == "__main__": check_str = input( "Enter string to determine if it can be rearranged as a palindrome or not: " ).strip() benchmark(check_str) status = can_string_be_rearranged_as_palindrome_counter(check_str) print(f"{check_str} can {'' if status else 'not '}be rearranged as a palindrome")
capitalizes the first letter of a sentence or word capitalizehello world hello world capitalize123 hello world 123 hello world capitalize hello world hello world capitalizea a capitalize create a dictionary that maps lowercase letters to uppercase letters capitalize the first character if it s a lowercase letter concatenate the capitalized character with the rest of the string capitalizes the first letter of a sentence or word capitalize hello world hello world capitalize 123 hello world 123 hello world capitalize hello world hello world capitalize a a capitalize create a dictionary that maps lowercase letters to uppercase letters capitalize the first character if it s a lowercase letter concatenate the capitalized character with the rest of the string
from string import ascii_lowercase, ascii_uppercase def capitalize(sentence: str) -> str: if not sentence: return "" lower_to_upper = dict(zip(ascii_lowercase, ascii_uppercase)) return lower_to_upper.get(sentence[0], sentence[0]) + sentence[1:] if __name__ == "__main__": from doctest import testmod testmod()
wiki https en wikipedia orgwikianagram two strings are anagrams if they are made up of the same letters but are arranged differently ignoring the case checkanagrams silent listen true checkanagrams this is a string is this a string true checkanagrams this is a string is this a string true checkanagrams there their false remove whitespace strings of different lengths are not anagrams default values for count should be 0 for each character in input strings increment count in the corresponding two strings are anagrams if they are made up of the same letters but are arranged differently ignoring the case check_anagrams silent listen true check_anagrams this is a string is this a string true check_anagrams this is a string is this a string true check_anagrams there their false remove whitespace strings of different lengths are not anagrams default values for count should be 0 for each character in input strings increment count in the corresponding
from collections import defaultdict def check_anagrams(first_str: str, second_str: str) -> bool: first_str = first_str.lower().strip() second_str = second_str.lower().strip() first_str = first_str.replace(" ", "") second_str = second_str.replace(" ", "") if len(first_str) != len(second_str): return False count: defaultdict[str, int] = defaultdict(int) 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()) if __name__ == "__main__": from doctest import testmod testmod() input_a = input("Enter the first string ").strip() input_b = input("Enter the second string ").strip() status = check_anagrams(input_a, input_b) print(f"{input_a} and {input_b} are {'' if status else 'not '}anagrams.")
functions for testing the validity of credit card numbers https en wikipedia orgwikiluhnalgorithm function to validate initial digits of a given credit card number valid 4111111111111111 41111111111111 34 35 37 412345 523456 634567 allvalidateinitialdigitscc for cc in valid split true invalid 14 25 76 32323 36111111111111 allvalidateinitialdigitscc is false for cc in invalid split true function to luhn algorithm validation for a given credit card number luhnvalidation 4111111111111111 true luhnvalidation 36111111111111 true luhnvalidation 41111111111111 false double the value of every second digit if doubling of a number results in a two digit number i e greater than 9e 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 sum up the remaining digits function to validate the given credit card number validatecreditcardnumber 4111111111111111 4111111111111111 is a valid credit card number true validatecreditcardnumber helloworld helloworld is an invalid credit card number because it has nonnumerical characters false validatecreditcardnumber 32323 32323 is an invalid credit card number because of its length false validatecreditcardnumber 32323323233232332323 32323323233232332323 is an invalid credit card number because of its length false validatecreditcardnumber 36111111111111 36111111111111 is an invalid credit card number because of its first two digits false validatecreditcardnumber 41111111111111 41111111111111 is an invalid credit card number because it fails the luhn check false function to validate initial digits of a given credit card number valid 4111111111111111 41111111111111 34 35 37 412345 523456 634567 all validate_initial_digits cc for cc in valid split true invalid 14 25 76 32323 36111111111111 all validate_initial_digits cc is false for cc in invalid split true function to luhn algorithm validation for a given credit card number luhn_validation 4111111111111111 true luhn_validation 36111111111111 true luhn_validation 41111111111111 false double the value of every second digit 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 sum up the remaining digits function to validate the given credit card number validate_credit_card_number 4111111111111111 4111111111111111 is a valid credit card number true validate_credit_card_number helloworld helloworld is an invalid credit card number because it has nonnumerical characters false validate_credit_card_number 32323 32323 is an invalid credit card number because of its length false validate_credit_card_number 32323323233232332323 32323323233232332323 is an invalid credit card number because of its length false validate_credit_card_number 36111111111111 36111111111111 is an invalid credit card number because of its first two digits false validate_credit_card_number 41111111111111 41111111111111 is an invalid credit card number because it fails the luhn check false
def validate_initial_digits(credit_card_number: str) -> bool: return credit_card_number.startswith(("34", "35", "37", "4", "5", "6")) 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): digit = int(cc_number[i]) digit *= 2 if digit > 9: digit %= 10 digit += 1 cc_number = cc_number[:i] + str(digit) + cc_number[i + 1 :] total += digit for i in range(len(cc_number) - 1, -1, -2): total += int(cc_number[i]) return total % 10 == 0 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 if __name__ == "__main__": import doctest doctest.testmod() validate_credit_card_number("4111111111111111") validate_credit_card_number("32323")
this script is a implementation of the dameraulevenshtein distance algorithm it s an algorithm that measures the edit distance between two string sequences more information about this algorithm can be found in this wikipedia article https en wikipedia orgwikidameraue28093levenshteindistance implements the dameraulevenshtein distance algorithm that measures the edit distance between two strings parameters firststring the first string to compare secondstring the second string to compare returns distance the edit distance between the first and second strings dameraulevenshteindistancecat cut 1 dameraulevenshteindistancekitten sitting 3 dameraulevenshteindistancehello world 4 dameraulevenshteindistancebook back 2 dameraulevenshteindistancecontainer containment 3 dameraulevenshteindistancecontainer containment 3 create a dynamic programming matrix to store the distances initialize the matrix fill the matrix transposition implements the damerau levenshtein distance algorithm that measures the edit distance between two strings parameters first_string the first string to compare second_string the second string to compare returns distance the edit distance between the first and second strings damerau_levenshtein_distance cat cut 1 damerau_levenshtein_distance kitten sitting 3 damerau_levenshtein_distance hello world 4 damerau_levenshtein_distance book back 2 damerau_levenshtein_distance container containment 3 damerau_levenshtein_distance container containment 3 create a dynamic programming matrix to store the distances initialize the matrix fill the matrix deletion insertion substitution transposition
def damerau_levenshtein_distance(first_string: str, second_string: str) -> int: dp_matrix = [[0] * (len(second_string) + 1) for _ in range(len(first_string) + 1)] for i in range(len(first_string) + 1): dp_matrix[i][0] = i for j in range(len(second_string) + 1): dp_matrix[0][j] = j for i, first_char in enumerate(first_string, start=1): for j, second_char in enumerate(second_string, start=1): cost = int(first_char != second_char) dp_matrix[i][j] = min( dp_matrix[i - 1][j] + 1, dp_matrix[i][j - 1] + 1, dp_matrix[i - 1][j - 1] + cost, ) if ( i > 1 and j > 1 and first_string[i - 1] == second_string[j - 2] and first_string[i - 2] == second_string[j - 1] ): dp_matrix[i][j] = min(dp_matrix[i][j], dp_matrix[i - 2][j - 2] + cost) return dp_matrix[-1][-1] if __name__ == "__main__": import doctest doctest.testmod()
removenonlettershi how are you hi how are you removenonletterspython python removenonletters112 removenonletterswww google com wwwgooglecom removenonletters isenglish hello world true isenglish llold horwd false remove_non_letters hi how are you hi how are you remove_non_letters p y t h o n python remove_non_letters 1 1 2 remove_non_letters www google com wwwgooglecom remove_non_letters is_english hello world true is_english llold horwd false
import os from string import ascii_letters LETTERS_AND_SPACE = ascii_letters + " \t\n" 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 ENGLISH_WORDS = load_dictionary() 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) def remove_non_letters(message: str) -> str: return "".join(symbol for symbol in message if symbol in LETTERS_AND_SPACE) 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 if __name__ == "__main__": import doctest doctest.testmod()
https en wikipedia orgwikidna returns the second side of a dna strand dnagcta cgat dnaatgc tacg dnactga gact dnagfgg traceback most recent call last valueerror invalid strand https en wikipedia org wiki dna returns the second side of a dna strand dna gcta cgat dna atgc tacg dna ctga gact dna gfgg traceback most recent call last valueerror invalid strand
import re def dna(dna: str) -> str: if len(re.findall("[ATCG]", dna)) != len(dna): raise ValueError("Invalid Strand") return dna.translate(dna.maketrans("ATCG", "TAGC")) if __name__ == "__main__": import doctest doctest.testmod()
edit distance algorithm is a string metric i e it is a way of quantifying how dissimilar two strings are to one another it is measured by counting the minimum number of operations required to transform one string into another this implementation assumes that the cost of operations insertion deletion and substitution is always 1 args source the initial string with respect to which we are calculating the edit distance for the target target the target string formed after performing n operations on the source string editdistancegattic galtic 1 edit distance algorithm is a string metric i e it is a way of quantifying how dissimilar two strings are to one another it is measured by counting the minimum number of operations required to transform one string into another this implementation assumes that the cost of operations insertion deletion and substitution is always 1 args source the initial string with respect to which we are calculating the edit distance for the target target the target string formed after performing n operations on the source string edit_distance gattic galtic 1 substitution answer is 4
def edit_distance(source: str, target: str) -> int: if len(source) == 0: return len(target) elif len(target) == 0: return len(source) delta = int(source[-1] != target[-1]) return min( edit_distance(source[:-1], target[:-1]) + delta, edit_distance(source, target[:-1]) + 1, edit_distance(source[:-1], target) + 1, ) if __name__ == "__main__": print(edit_distance("ATCGCTG", "TAGCTAA"))
frequency finder frequency taken from https en wikipedia orgwikiletterfrequency get the frequency order of the letters in the given string getfrequencyorder hello world lowdrhezqxjkvbpygfmucsniat getfrequencyorder hello lhoezqxjkvbpygfwmucdrsniat getfrequencyorder h hzqxjkvbpygfwmucldrsnioate englishfreqmatchscore hello world 1 frequency finder frequency taken from https en wikipedia org wiki letter_frequency get the frequency order of the letters in the given string get_frequency_order hello world lowdrhezqxjkvbpygfmucsniat get_frequency_order hello lhoezqxjkvbpygfwmucdrsniat get_frequency_order h hzqxjkvbpygfwmucldrsnioate english_freq_match_score hello world 1
import string english_letter_freq = { "E": 12.70, "T": 9.06, "A": 8.17, "O": 7.51, "I": 6.97, "N": 6.75, "S": 6.33, "H": 6.09, "R": 5.99, "D": 4.25, "L": 4.03, "C": 2.78, "U": 2.76, "M": 2.41, "W": 2.36, "F": 2.23, "G": 2.02, "Y": 1.97, "P": 1.93, "B": 1.29, "V": 0.98, "K": 0.77, "J": 0.15, "X": 0.15, "Q": 0.10, "Z": 0.07, } ETAOIN = "ETAOINSHRDLCUMWFGYPBVKJXQZ" LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 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 def get_item_at_index_zero(x: tuple) -> str: return x[0] 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) 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 if __name__ == "__main__": import doctest doctest.testmod()
calculate the hamming distance between two equal length strings in information theory the hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different https en wikipedia orgwikihammingdistance args string1 str sequence 1 string2 str sequence 2 returns int hamming distance hammingdistancepython python 0 hammingdistancekarolin kathrin 3 hammingdistance00000 11111 5 hammingdistancekarolin kath traceback most recent call last valueerror string lengths must match calculate the hamming distance between two equal length strings in information theory the hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different https en wikipedia org wiki hamming_distance args string1 str sequence 1 string2 str sequence 2 returns int hamming distance hamming_distance python python 0 hamming_distance karolin kathrin 3 hamming_distance 00000 11111 5 hamming_distance karolin kath traceback most recent call last valueerror string lengths must match
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 if __name__ == "__main__": import doctest doctest.testmod()
determine whether the string is a valid phone number or not param phone return boolean indianphonevalidator91123456789 false indianphonevalidator919876543210 true indianphonevalidator01234567896 false indianphonevalidator919876543218 true indianphonevalidator911234567899 false indianphonevalidator919876543218 true determine whether the string is a valid phone number or not param phone return boolean indian_phone_validator 91123456789 false indian_phone_validator 919876543210 true indian_phone_validator 01234567896 false indian_phone_validator 919876543218 true indian_phone_validator 91 1234567899 false indian_phone_validator 91 9876543218 true
import re def indian_phone_validator(phone: str) -> bool: pat = re.compile(r"^(\+91[\-\s]?)?[0]?(91)?[789]\d{9}$") if match := re.search(pat, phone): return match.string == phone return False if __name__ == "__main__": print(indian_phone_validator("+918827897895"))
check if all characters in the string is unique or not iscontainsuniquecharsilove py true iscontainsuniquecharsi don t love python false time complexity on space complexity o1 19320 bytes as we are having 144697 characters in unicode each bit will represent each unicode character for example 65th bit representing a https stackoverflow coma12811293 if we already turned on bit for current character s unicode check if all characters in the string is unique or not is_contains_unique_chars i_love py true is_contains_unique_chars i don t love python false time complexity o n space complexity o 1 19320 bytes as we are having 144697 characters in unicode each bit will represent each unicode character for example 65th bit representing a https stackoverflow com a 12811293 if we already turned on bit for current character s unicode
def is_contains_unique_chars(input_str: str) -> bool: bitmap = 0 for ch in input_str: ch_unicode = ord(ch) ch_bit_index_on = pow(2, ch_unicode) if bitmap >> ch_unicode & 1 == 1: return False bitmap |= ch_bit_index_on return True if __name__ == "__main__": import doctest doctest.testmod()
wiki https en wikipedia orgwikiheterogramliteratureisograms an isogram is a word in which no letter is repeated examples of isograms are unable and ambidextrously isisogram unable true isisogram allowance false isisogram copy1 traceback most recent call last valueerror string must only contain alphabetic characters an isogram is a word in which no letter is repeated examples of isograms are unable and ambidextrously is_isogram unable true is_isogram allowance false is_isogram copy1 traceback most recent call last valueerror string must only contain alphabetic characters
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)) if __name__ == "__main__": input_str = input("Enter a string ").strip() isogram = is_isogram(input_str) print(f"{input_str} is {'an' if isogram else 'not an'} isogram.")
wiki https en wikipedia orgwikipangram a pangram string contains all the alphabets at least once ispangramthe quick brown fox jumps over the lazy dog true ispangramwaltz bad nymph for quick jigs vex true ispangramjived fox nymph grabs quick waltz true ispangrammy name is unknown false ispangramthe quick brown fox jumps over the lay dog false ispangram true declare frequency as a set to have unique occurrences of letters replace all the whitespace in our sentence ispangramfasterthe quick brown fox jumps over the lazy dog true ispangramfasterwaltz bad nymph for quick jigs vex true ispangramfasterjived fox nymph grabs quick waltz true ispangramfasterthe quick brown fox jumps over the lay dog false ispangramfaster true ispangramfastestthe quick brown fox jumps over the lazy dog true ispangramfastestwaltz bad nymph for quick jigs vex true ispangramfastestjived fox nymph grabs quick waltz true ispangramfastestthe quick brown fox jumps over the lay dog false ispangramfastest true benchmark code comparing different version 5 348480500048026 2 6477354579837993 1 8470395830227062 5 036091582966037 2 644472333951853 1 8869528750656173 a pangram string contains all the alphabets at least once is_pangram the quick brown fox jumps over the lazy dog true is_pangram waltz bad nymph for quick jigs vex true is_pangram jived fox nymph grabs quick waltz true is_pangram my name is unknown false is_pangram the quick brown fox jumps over the la_y dog false is_pangram true declare frequency as a set to have unique occurrences of letters replace all the whitespace in our sentence is_pangram_faster the quick brown fox jumps over the lazy dog true is_pangram_faster waltz bad nymph for quick jigs vex true is_pangram_faster jived fox nymph grabs quick waltz true is_pangram_faster the quick brown fox jumps over the la_y dog false is_pangram_faster true is_pangram_fastest the quick brown fox jumps over the lazy dog true is_pangram_fastest waltz bad nymph for quick jigs vex true is_pangram_fastest jived fox nymph grabs quick waltz true is_pangram_fastest the quick brown fox jumps over the la_y dog false is_pangram_fastest true benchmark code comparing different version 5 348480500048026 2 6477354579837993 1 8470395830227062 5 036091582966037 2 644472333951853 1 8869528750656173
def is_pangram( input_str: str = "The quick brown fox jumps over the lazy dog", ) -> bool: frequency = set() input_str = input_str.replace(" ", "") for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower()) return len(frequency) == 26 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) 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 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)) if __name__ == "__main__": import doctest doctest.testmod() benchmark()
verification of the correctness of the pesel number wwwgovpl translate googwebgovczymjestnumerpesel xtrslautoxtrtlen pesel can start with 0 that s why we take str as input but convert it to int for some calculations ispolishnationalid123 traceback most recent call last valueerror expected str as input found class int ispolishnationalidabc traceback most recent call last valueerror expected number as input ispolishnationalid02070803628 correct pesel true ispolishnationalid02150803629 wrong month false ispolishnationalid02075503622 wrong day false ispolishnationalid99012212349 wrong range false ispolishnationalid990122123499999 wrong range false ispolishnationalid02070803621 wrong checksum false check for invalid input type check if input can be converted to int check number range check month correctness check day correctness check the checksum multiply corresponding digits and multipliers in case of a doubledigit result add only the last digit verification of the correctness of the pesel number www gov pl translate goog web gov czym jest numer pesel _x_tr_sl auto _x_tr_tl en pesel can start with 0 that s why we take str as input but convert it to int for some calculations is_polish_national_id 123 traceback most recent call last valueerror expected str as input found class int is_polish_national_id abc traceback most recent call last valueerror expected number as input is_polish_national_id 02070803628 correct pesel true is_polish_national_id 02150803629 wrong month false is_polish_national_id 02075503622 wrong day false is_polish_national_id 99012212349 wrong range false is_polish_national_id 990122123499999 wrong range false is_polish_national_id 02070803621 wrong checksum false check for invalid input type check if input can be converted to int check number range check month correctness year 1900 1999 2000 2099 2100 2199 2200 2299 1800 1899 check day correctness check the checksum cut off the checksum multiply corresponding digits and multipliers in case of a double digit result add only the last digit
def is_polish_national_id(input_str: str) -> bool: if not isinstance(input_str, str): msg = f"Expected str as input, found {type(input_str)}" raise ValueError(msg) try: input_int = int(input_str) except ValueError: msg = "Expected number as input" raise ValueError(msg) if not 10100000 <= input_int <= 99923199999: return False month = int(input_str[2:4]) if ( month not in range(1, 13) and month not in range(21, 33) and month not in range(41, 53) and month not in range(61, 73) and month not in range(81, 93) ): return False day = int(input_str[4:6]) if day not in range(1, 32): return False multipliers = [1, 3, 7, 9, 1, 3, 7, 9, 1, 3] subtotal = 0 digits_to_check = str(input_str)[:-1] for index, digit in enumerate(digits_to_check): subtotal += (int(digit) * multipliers[index]) % 10 checksum = 10 - subtotal % 10 return checksum == input_int % 10 if __name__ == "__main__": from doctest import testmod testmod()
spain national id is a string composed by 8 numbers plus a letter the letter in fact is not part of the id it acts as a validator checking you didn t do a mistake when entering it on a system or are giving a fake one https en wikipedia orgwikidocumentonacionaldeidentidadspainnumber isspainnationalid12345678z true isspainnationalid12345678z it is caseinsensitive true isspainnationalid12345678x false isspainnationalid12345678i false isspainnationalid12345678z some systems add a dash true isspainnationalid12345678 traceback most recent call last valueerror input must be a string of 8 numbers plus letter isspainnationalid123456709 traceback most recent call last valueerror input must be a string of 8 numbers plus letter isspainnationalid1234567z traceback most recent call last valueerror input must be a string of 8 numbers plus letter isspainnationalid1234z traceback most recent call last valueerror input must be a string of 8 numbers plus letter isspainnationalid1234zzzz traceback most recent call last valueerror input must be a string of 8 numbers plus letter isspainnationalid12345678 traceback most recent call last typeerror expected string as input found int spain national id is a string composed by 8 numbers plus a letter the letter in fact is not part of the id it acts as a validator checking you didn t do a mistake when entering it on a system or are giving a fake one https en wikipedia org wiki documento_nacional_de_identidad_ spain number is_spain_national_id 12345678z true is_spain_national_id 12345678z it is case insensitive true is_spain_national_id 12345678x false is_spain_national_id 12345678i false is_spain_national_id 12345678 z some systems add a dash true is_spain_national_id 12345678 traceback most recent call last valueerror input must be a string of 8 numbers plus letter is_spain_national_id 123456709 traceback most recent call last valueerror input must be a string of 8 numbers plus letter is_spain_national_id 1234567 z traceback most recent call last valueerror input must be a string of 8 numbers plus letter is_spain_national_id 1234z traceback most recent call last valueerror input must be a string of 8 numbers plus letter is_spain_national_id 1234zzzz traceback most recent call last valueerror input must be a string of 8 numbers plus letter is_spain_national_id 12345678 traceback most recent call last typeerror expected string as input found int
NUMBERS_PLUS_LETTER = "Input must be a string of 8 numbers plus letter" LOOKUP_LETTERS = "TRWAGMYFPDXBNJZSQVHLCKE" def is_spain_national_id(spanish_id: str) -> bool: if not isinstance(spanish_id, str): msg = f"Expected string as input, found {type(spanish_id).__name__}" raise TypeError(msg) 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] if __name__ == "__main__": import doctest doctest.testmod()
determine whether the string is a valid sri lankan mobile phone number or not references https aye shblogsrilankanphonenumberregex issrilankanphonenumber94773283048 true issrilankanphonenumber94773283048 true issrilankanphonenumber0718382399 true issrilankanphonenumber0094702343221 true issrilankanphonenumber075 3201568 true issrilankanphonenumber07779209245 false issrilankanphonenumber0957651234 false determine whether the string is a valid sri lankan mobile phone number or not references https aye sh blog sri lankan phone number regex is_sri_lankan_phone_number 94773283048 true is_sri_lankan_phone_number 9477 3283048 true is_sri_lankan_phone_number 0718382399 true is_sri_lankan_phone_number 0094702343221 true is_sri_lankan_phone_number 075 3201568 true is_sri_lankan_phone_number 07779209245 false is_sri_lankan_phone_number 0957651234 false
import re def is_sri_lankan_phone_number(phone: str) -> bool: pattern = re.compile(r"^(?:0|94|\+94|0{2}94)7(0|1|2|4|5|6|7|8)(-| |)\d{7}$") return bool(re.search(pattern, phone)) if __name__ == "__main__": phone = "0094702343221" print(is_sri_lankan_phone_number(phone))
https en wikipedia orgwikijaroe28093winklerdistance def jarowinklerstr1 str str2 str float def getmatchedcharactersstr1 str str2 str str matched limit minlenstr1 lenstr2 2 for i l in enumeratestr1 left intmax0 i limit right intmini limit 1 lenstr2 if l in str2left right matched appendl str2 fstr20 str2 indexl str2str2 indexl 1 return joinmatched matching characters matching1 getmatchedcharactersstr1 str2 matching2 getmatchedcharactersstr2 str1 matchcount lenmatching1 transposition transpositions lenc1 c2 for c1 c2 in zipmatching1 matching2 if c1 c2 2 if not matchcount jaro 0 0 else jaro 1 3 matchcount lenstr1 matchcount lenstr2 matchcount transpositions matchcount common prefix up to 4 characters prefixlen 0 for c1 c2 in zipstr1 4 str2 4 if c1 c2 prefixlen 1 else break return jaro 0 1 prefixlen 1 jaro if name main import doctest doctest testmod printjarowinklerhello world jaro winkler distance is a string metric measuring an edit distance between two sequences output value is between 0 0 and 1 0 jaro_winkler martha marhta 0 9611111111111111 jaro_winkler crate trace 0 7333333333333334 jaro_winkler test dbdbdbdb 0 0 jaro_winkler test test 1 0 jaro_winkler hello world hello w0rld 0 6363636363636364 jaro_winkler test 0 0 jaro_winkler hello world 0 4666666666666666 jaro_winkler hell o world 0 4365079365079365 matching characters transposition common prefix up to 4 characters
def jaro_winkler(str1: str, str2: str) -> float: def get_matched_characters(_str1: str, _str2: str) -> str: matched = [] limit = min(len(_str1), len(_str2)) // 2 for i, l in enumerate(_str1): left = int(max(0, i - limit)) right = int(min(i + limit + 1, len(_str2))) if l in _str2[left:right]: matched.append(l) _str2 = f"{_str2[0:_str2.index(l)]} {_str2[_str2.index(l) + 1:]}" return "".join(matched) matching_1 = get_matched_characters(str1, str2) matching_2 = get_matched_characters(str2, str1) match_count = len(matching_1) transpositions = ( len([(c1, c2) for c1, c2 in zip(matching_1, matching_2) if c1 != c2]) // 2 ) if not match_count: jaro = 0.0 else: jaro = ( 1 / 3 * ( match_count / len(str1) + match_count / len(str2) + (match_count - transpositions) / match_count ) ) prefix_len = 0 for c1, c2 in zip(str1[:4], str2[:4]): if c1 == c2: prefix_len += 1 else: break return jaro + 0.1 * prefix_len * (1 - jaro) if __name__ == "__main__": import doctest doctest.testmod() print(jaro_winkler("hello", "world"))
program to join a list of strings with a separator joins a list of strings using a separator and returns the result param separator separator to be used for joining the strings param separated list of strings to be joined return joined string with the specified separator examples join a b c d abcd join a b c d abcd join a a join you are amazing you are amazing this example should raise an exception for nonstring elements join a b c 1 traceback most recent call last exception join accepts only strings additional test case with a different separator join apple banana cherry applebananacherry remove the trailing separator by stripping it from the result joins a list of strings using a separator and returns the result param separator separator to be used for joining the strings param separated list of strings to be joined return joined string with the specified separator examples join a b c d abcd join a b c d a b c d join a a join you are amazing you are amazing this example should raise an exception for non string elements join a b c 1 traceback most recent call last exception join accepts only strings additional test case with a different separator join apple banana cherry apple banana cherry remove the trailing separator by stripping it from the result
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") joined += word_or_phrase + separator return joined.strip(separator) if __name__ == "__main__": from doctest import testmod testmod()
the knuthmorrispratt algorithm for finding a pattern within a piece of text with complexity on m 1 preprocess pattern to identify any suffixes that are identical to prefixes this tells us where to continue from if we get a mismatch between a character in our pattern and the text 2 step through the text one character at a time and compare it to a character in the pattern updating our location within the pattern if necessary kmp knuthmorrispratt all knuthmorrisprattkmp s kmp finds for s in kn hm rr tt not there true 1 construct the failure array 2 step through text searching for pattern if this is a prefix in our pattern just go back far enough to continue calculates the new index we should go to if we fail a comparison param pattern return test 1 test 2 test 3 test 4 test 5 doctests test 6 the knuth morris pratt algorithm for finding a pattern within a piece of text with complexity o n m 1 preprocess pattern to identify any suffixes that are identical to prefixes this tells us where to continue from if we get a mismatch between a character in our pattern and the text 2 step through the text one character at a time and compare it to a character in the pattern updating our location within the pattern if necessary kmp knuth_morris_pratt all knuth_morris_pratt kmp s kmp find s for s in kn h_m rr tt not there true 1 construct the failure array 2 step through text searching for pattern index into text pattern if this is a prefix in our pattern just go back far enough to continue calculates the new index we should go to if we fail a comparison param pattern return test 1 test 2 test 3 test 4 test 5 doctests test 6
from __future__ import annotations def knuth_morris_pratt(text: str, pattern: str) -> int: failure = get_failure_array(pattern) i, j = 0, 0 while i < len(text): if pattern[j] == text[i]: if j == (len(pattern) - 1): return i - j j += 1 elif j > 0: j = failure[j - 1] continue i += 1 return -1 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 if __name__ == "__main__": import doctest doctest.testmod() pattern = "abc1abc12" text1 = "alskfjaldsabc1abc1abc12k23adsfabcabc" text2 = "alskfjaldsk23adsfabcabc" assert knuth_morris_pratt(text1, pattern) assert knuth_morris_pratt(text2, pattern) pattern = "ABABX" text = "ABABZABABYABABX" assert knuth_morris_pratt(text, pattern) pattern = "AAAB" text = "ABAAAAAB" assert knuth_morris_pratt(text, pattern) pattern = "abcdabcy" text = "abcxabcdabxabcdabcdabcy" assert knuth_morris_pratt(text, pattern) kmp = "knuth_morris_pratt" assert all( knuth_morris_pratt(kmp, s) == kmp.find(s) for s in ("kn", "h_m", "rr", "tt", "not there") ) pattern = "aabaabaaa" assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
implementation of the levenshtein distance in python param firstword the first word to measure the difference param secondword the second word to measure the difference return the levenshtein distance between the two words examples levenshteindistanceplanet planetary 3 levenshteindistance test 4 levenshteindistancebook back 2 levenshteindistancebook book 0 levenshteindistancetest 4 levenshteindistance 0 levenshteindistanceorchestration container 10 the longer word should come first calculate insertions deletions and substitutions get the minimum to append to the current row store the previous row returns the last element distance compute the levenshtein distance between two words strings the function is optimized for efficiency by modifying rows in place param firstword the first word to measure the difference param secondword the second word to measure the difference return the levenshtein distance between the two words examples levenshteindistanceoptimizedplanet planetary 3 levenshteindistanceoptimized test 4 levenshteindistanceoptimizedbook back 2 levenshteindistanceoptimizedbook book 0 levenshteindistanceoptimizedtest 4 levenshteindistanceoptimized 0 levenshteindistanceoptimizedorchestration container 10 benchmark the levenshtein distance function param str the name of the function being benchmarked param func the function to be benchmarked get user input for words calculate and print levenshtein distances benchmark the levenshtein distance functions implementation of the levenshtein distance in python param first_word the first word to measure the difference param second_word the second word to measure the difference return the levenshtein distance between the two words examples levenshtein_distance planet planetary 3 levenshtein_distance test 4 levenshtein_distance book back 2 levenshtein_distance book book 0 levenshtein_distance test 4 levenshtein_distance 0 levenshtein_distance orchestration container 10 the longer word should come first calculate insertions deletions and substitutions get the minimum to append to the current row store the previous row returns the last element distance compute the levenshtein distance between two words strings the function is optimized for efficiency by modifying rows in place param first_word the first word to measure the difference param second_word the second word to measure the difference return the levenshtein distance between the two words examples levenshtein_distance_optimized planet planetary 3 levenshtein_distance_optimized test 4 levenshtein_distance_optimized book back 2 levenshtein_distance_optimized book book 0 levenshtein_distance_optimized test 4 levenshtein_distance_optimized 0 levenshtein_distance_optimized orchestration container 10 benchmark the levenshtein distance function param str the name of the function being benchmarked param func the function to be benchmarked get user input for words calculate and print levenshtein distances benchmark the levenshtein distance functions
from collections.abc import Callable def levenshtein_distance(first_word: str, second_word: str) -> int: 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): insertions = previous_row[j + 1] + 1 deletions = current_row[j] + 1 substitutions = previous_row[j] + (c1 != c2) current_row.append(min(insertions, deletions, substitutions)) previous_row = current_row return previous_row[-1] def levenshtein_distance_optimized(first_word: str, second_word: str) -> int: if len(first_word) < len(second_word): return levenshtein_distance_optimized(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] + [0] * len(second_word) for j, c2 in enumerate(second_word): insertions = previous_row[j + 1] + 1 deletions = current_row[j] + 1 substitutions = previous_row[j] + (c1 != c2) current_row[j + 1] = min(insertions, deletions, substitutions) previous_row = current_row return previous_row[-1] def benchmark_levenshtein_distance(func: Callable) -> None: from timeit import timeit stmt = f"{func.__name__}('sitting', 'kitten')" setup = f"from __main__ import {func.__name__}" number = 25_000 result = timeit(stmt=stmt, setup=setup, number=number) print(f"{func.__name__:<30} finished {number:,} runs in {result:.5f} seconds") if __name__ == "__main__": first_word = input("Enter the first word for Levenshtein distance:\n").strip() second_word = input("Enter the second word for Levenshtein distance:\n").strip() print(f"{levenshtein_distance(first_word, second_word) = }") print(f"{levenshtein_distance_optimized(first_word, second_word) = }") benchmark_levenshtein_distance(levenshtein_distance) benchmark_levenshtein_distance(levenshtein_distance_optimized)
will convert the entire string to lowercase letters lowerwow wow lowerhellzo hellzo lowerwhat what lowerwh32 wh32 lowerwhat what converting to ascii value obtaining the integer representation and checking to see if the character is a capital letter if it is a capital letter it is shifted by 32 making it a lowercase letter will convert the entire string to lowercase letters lower wow wow lower hellzo hellzo lower what what lower wh 32 wh 32 lower what what converting to ascii value obtaining the integer representation and checking to see if the character is a capital letter if it is a capital letter it is shifted by 32 making it a lowercase letter
def lower(word: str) -> str: return "".join(chr(ord(char) + 32) if "A" <= char <= "Z" else char for char in word) if __name__ == "__main__": from doctest import testmod testmod()
palindromicstring abbbaba abbba palindromicstring ababa ababa manachers algorithm which finds longest palindromic substring in linear time 1 first this convert inputstringxyx into newstringxyx where odd positions are actual input characters 2 for each character in newstring it find corresponding length and store the length and l r to store previously calculated info please look the explanation for details 3 return corresponding outputstring by removing all if inputstring is aba than newinputstring become aba append each character in newstring for range0 length1 append last character we will store the starting and ending of previous furthest ending palindromic substring lengthi shows the length of palindromic substring with center i for each character in newstring find corresponding palindromic string 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 update maxlength and start position create that string a0 a1 a2 a3 a4 a5 a6 consider the string for which we are calculating the longest palindromic substring is shown above where are some characters in between and right now we are calculating the length of palindromic substring with center at a5 with following conditions i we have stored the length of palindromic substring which has center at a3 starts at l ends at r and it is the furthest ending till now and it has ending after a6 ii a2 and a4 are equally distant from a3 so chara2 chara4 iii a0 and a6 are equally distant from a3 so chara0 chara6 iv a1 is corresponding equal character of a5 in palindrome with center a3 remember that in below derivation of a4a6 now for a5 we will calculate the length of palindromic substring with center as a5 but can we use previously calculated information in some way yes look the above string we know that a5 is inside the palindrome with center a3 and previously we have calculated that a0a2 palindrome of center a1 a2a4 palindrome of center a3 a0a6 palindrome of center a3 so a4a6 so we can say that palindrome at center a5 is at least as long as palindrome at center a1 but this only holds if a0 and a6 are inside the limits of palindrome centered at a3 so finally lenofpalindromeata5 minlenofpalindromeata1 ra5 where a3 lies from l to r and we have to keep updating that and if the a5 lies outside of l r boundary we calculate length of palindrome with bruteforce and update l r it gives the linear time complexity just like zfunction palindromic_string abbbaba abbba palindromic_string ababa ababa manacher s algorithm which finds longest palindromic substring in linear time 1 first this convert input_string xyx into new_string x y x where odd positions are actual input characters 2 for each character in new_string it find corresponding length and store the length and l r to store previously calculated info please look the explanation for details 3 return corresponding output_string by removing all if input_string is aba than new_input_string become a b a append each character in new_string for range 0 length 1 append last character we will store the starting and ending of previous furthest ending palindromic substring length i shows the length of palindromic substring with center i for each character in new_string find corresponding palindromic string 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 noqa e741 update max_length and start position create that string a0 a1 a2 a3 a4 a5 a6 consider the string for which we are calculating the longest palindromic substring is shown above where are some characters in between and right now we are calculating the length of palindromic substring with center at a5 with following conditions i we have stored the length of palindromic substring which has center at a3 starts at l ends at r and it is the furthest ending till now and it has ending after a6 ii a2 and a4 are equally distant from a3 so char a2 char a4 iii a0 and a6 are equally distant from a3 so char a0 char a6 iv a1 is corresponding equal character of a5 in palindrome with center a3 remember that in below derivation of a4 a6 now for a5 we will calculate the length of palindromic substring with center as a5 but can we use previously calculated information in some way yes look the above string we know that a5 is inside the palindrome with center a3 and previously we have calculated that a0 a2 palindrome of center a1 a2 a4 palindrome of center a3 a0 a6 palindrome of center a3 so a4 a6 so we can say that palindrome at center a5 is at least as long as palindrome at center a1 but this only holds if a0 and a6 are inside the limits of palindrome centered at a3 so finally len_of_palindrome__at a5 min len_of_palindrome_at a1 r a5 where a3 lies from l to r and we have to keep updating that and if the a5 lies outside of l r boundary we calculate length of palindrome with bruteforce and update l r it gives the linear time complexity just like z function
def palindromic_string(input_string: str) -> str: max_length = 0 new_input_string = "" output_string = "" for i in input_string[: len(input_string) - 1]: new_input_string += i + "|" new_input_string += input_string[-1] l, r = 0, 0 length = [1 for i in range(len(new_input_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 if j + k - 1 > r: l = j - k + 1 r = j + k - 1 if max_length < length[j]: max_length = length[j] start = j 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 if __name__ == "__main__": import doctest doctest.testmod()
algorithm for calculating the most costefficient sequence for converting one string into another the only allowed operations are cost to copy a character is copycost cost to replace a character is replacecost cost to delete a character is deletecost cost to insert a character is insertcost
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 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] in {"C", "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 if __name__ == "__main__": _, operations = compute_transform_tables("Python", "Algorithms", -1, 1, 2, 2) m = len(operations) n = len(operations[0]) sequence = assemble_transformation(operations, m - 1, n - 1) string = list("Python") i = 0 cost = 0 with open("min_cost.txt", "w") as file: for op in sequence: print("".join(string)) if op[0] == "C": file.write("%-16s" % "Copy %c" % op[1]) file.write("\t\t\t" + "".join(string)) file.write("\r\n") cost -= 1 elif op[0] == "R": string[i] = op[2] file.write("%-16s" % ("Replace %c" % op[1] + " with " + str(op[2]))) file.write("\t\t" + "".join(string)) file.write("\r\n") cost += 1 elif op[0] == "D": string.pop(i) file.write("%-16s" % "Delete %c" % op[1]) file.write("\t\t\t" + "".join(string)) file.write("\r\n") cost += 2 else: string.insert(i, op[1]) file.write("%-16s" % "Insert %c" % op[1]) file.write("\t\t\t" + "".join(string)) file.write("\r\n") cost += 2 i += 1 print("".join(string)) print("Cost: ", cost) file.write("\r\nMinimum cost: " + str(cost))
https en wikipedia orgwikistringsearchingalgorithmnac3afvestringsearch this algorithm tries to find the pattern from every position of the mainstring if pattern is found from position i it add it to the answer and does the same for position i1 complexity onm nlength of main string mlength of pattern string naivepatternsearchabaaabcdbbabcddebcabc abc 4 10 18 naivepatternsearchabc abaaabcdbbabcddebcabc naivepatternsearch abc naivepatternsearchtest test 0 naivepatternsearchabcdegftest test 7 naive_pattern_search abaaabcdbbabcddebcabc abc 4 10 18 naive_pattern_search abc abaaabcdbbabcddebcabc naive_pattern_search abc naive_pattern_search test test 0 naive_pattern_search abcdegftest test 7
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 if __name__ == "__main__": assert naive_pattern_search("ABCDEFG", "DE") == [3] print(naive_pattern_search("ABAAABCDBBABCDDEBCABC", "ABC"))
https en wikipedia orgwikingram create ngrams from a sentence createngrami am a sentence 2 i a am m a a s se en nt te en nc ce createngrami am an nlper 2 i a am m a an n n nl lp pe er createngramthis is short 50 create ngrams from a sentence create_ngram i am a sentence 2 i a am m a a s se en nt te en nc ce create_ngram i am an nlper 2 i a am m a an n n nl lp pe er create_ngram this is short 50
def create_ngram(sentence: str, ngram_size: int) -> list[str]: return [sentence[i : i + ngram_size] for i in range(len(sentence) - ngram_size + 1)] if __name__ == "__main__": from doctest import testmod testmod()
algorithms to determine if a string is palindrome ensure our test data is valid return true if s is a palindrome otherwise return false allispalindromekey is value for key value in testdata items true return true if s is a palindrome otherwise return false allispalindrometraversalkey is value for key value in testdata items true 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 ini1 where n is length of string return true if s is a palindrome otherwise return false allispalindromerecursivekey is value for key value in testdata items true return true if s is a palindrome otherwise return false allispalindromeslicekey is value for key value in testdata items true finished 500 000 runs in 0 46793 seconds finished 500 000 runs in 0 85234 seconds finished 500 000 runs in 1 32028 seconds finished 500 000 runs in 2 08679 seconds algorithms to determine if a string is palindrome a man a plan a canal panama ensure our test data is valid return true if s is a palindrome otherwise return false all is_palindrome key is value for key value in test_data items true return true if s is a palindrome otherwise return false all is_palindrome_traversal key is value for key value in test_data items true 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 true if s is a palindrome otherwise return false all is_palindrome_recursive key is value for key value in test_data items true return true if s is a palindrome otherwise return false all is_palindrome_slice key is value for key value in test_data items true finished 500 000 runs in 0 46793 seconds finished 500 000 runs in 0 85234 seconds finished 500 000 runs in 1 32028 seconds finished 500 000 runs in 2 08679 seconds
from timeit import timeit test_data = { "MALAYALAM": True, "String": False, "rotor": True, "level": True, "A": True, "BB": True, "ABC": False, "amanaplanacanalpanama": True, } assert all((key == key[::-1]) is value for key, value in test_data.items()) def is_palindrome(s: str) -> bool: start_i = 0 end_i = len(s) - 1 while start_i < end_i: if s[start_i] == s[end_i]: start_i += 1 end_i -= 1 else: return False return True def is_palindrome_traversal(s: str) -> bool: end = len(s) // 2 n = len(s) return all(s[i] == s[n - i - 1] for i in range(end)) def is_palindrome_recursive(s: str) -> bool: if len(s) <= 2: return True if s[0] == s[len(s) - 1]: return is_palindrome_recursive(s[1:-1]) else: return False def is_palindrome_slice(s: str) -> bool: return s == s[::-1] def benchmark_function(name: str) -> None: stmt = f"all({name}(key) is value for key, value in test_data.items())" setup = f"from __main__ import test_data, {name}" number = 500000 result = timeit(stmt=stmt, setup=setup, number=number) print(f"{name:<35} finished {number:,} runs in {result:.5f} seconds") if __name__ == "__main__": for key, value in test_data.items(): assert is_palindrome(key) is is_palindrome_recursive(key) assert is_palindrome(key) is is_palindrome_slice(key) print(f"{key:21} {value}") print("a man a plan a canal panama") benchmark_function("is_palindrome_slice") benchmark_function("is_palindrome") benchmark_function("is_palindrome_recursive") benchmark_function("is_palindrome_traversal")
compute the piglatin of a given string https en wikipedia orgwikipiglatin usage examples piglatinpig igpay piglatinlatin atinlay piglatinbanana ananabay piglatinfriends iendsfray piglatinsmile ilesmay piglatinstring ingstray piglatineat eatway piglatinomelet omeletway piglatinare areway piglatin piglatinnone compute the piglatin of a given string https en wikipedia org wiki pig_latin usage examples pig_latin pig igpay pig_latin latin atinlay pig_latin banana ananabay pig_latin friends iendsfray pig_latin smile ilesmay pig_latin string ingstray pig_latin eat eatway pig_latin omelet omeletway pig_latin are areway pig_latin pig_latin none noqa b007
def pig_latin(word: str) -> str: if not (word or "").strip(): return "" word = word.lower() if word[0] in "aeiou": return f"{word}way" for i, char in enumerate(word): if char in "aeiou": break return f"{word[i:]}{word[:i]}ay" if __name__ == "__main__": print(f"{pig_latin('friends') = }") word = input("Enter a word: ") print(f"{pig_latin(word) = }")
https cpalgorithms comstringprefixfunction html prefix function knuthmorrispratt algorithm different algorithm than knuthmorrispratt pattern finding e x finding longest prefix which is also suffix time complexity on where n is the length of the string for the given string this function computes value for each indexi which represents the longest coincidence of prefix and suffix for given substring inputstr0 i for the value of the first element the algorithm always returns 0 prefixfunctionaabcdaabc 0 1 0 0 0 1 2 3 4 prefixfunctionasdasdad 0 0 0 1 2 3 4 0 list for the result values use last results for better performance dynamic programming prefixfunction use case finding longest prefix which is suffix as well longestprefixaabcdaabc 4 longestprefixasdasdad 4 longestprefixabcab 2 just returning maximum value of the array gives us answer for the given string this function computes value for each index i which represents the longest coincidence of prefix and suffix for given substring input_str 0 i for the value of the first element the algorithm always returns 0 prefix_function aabcdaabc 0 1 0 0 0 1 2 3 4 prefix_function asdasdad 0 0 0 1 2 3 4 0 list for the result values use last results for better performance dynamic programming prefix function use case finding longest prefix which is suffix as well longest_prefix aabcdaabc 4 longest_prefix asdasdad 4 longest_prefix abcab 2 just returning maximum value of the array gives us answer
def prefix_function(input_string: str) -> list: prefix_result = [0] * len(input_string) for i in range(1, len(input_string)): 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 def longest_prefix(input_str: str) -> int: return max(prefix_function(input_str)) if __name__ == "__main__": import doctest doctest.testmod()
numbers of alphabet which we call base modulus to hash a string the rabinkarp algorithm for finding a pattern within a piece of text with complexity onm most efficient when it is used with multiple patterns as it is able to check if any of a set of patterns match a section of text in o1 given the precomputed hashes this will be the simple version which only assumes one pattern is being searched for but it s not hard to modify 1 calculate pattern hash 2 step through the text one character at a time passing a window with the same length as the pattern calculating the hash of the text within the window compare it with the hash of the pattern only testing equality if the hashes match calculating the hash of pattern and substring of text calculate the https en wikipedia orgwikirollinghash testrabinkarp success test 1 test 2 test 3 test 4 test 5 numbers of alphabet which we call base modulus to hash a string the rabin karp algorithm for finding a pattern within a piece of text with complexity o nm most efficient when it is used with multiple patterns as it is able to check if any of a set of patterns match a section of text in o 1 given the precomputed hashes this will be the simple version which only assumes one pattern is being searched for but it s not hard to modify 1 calculate pattern hash 2 step through the text one character at a time passing a window with the same length as the pattern calculating the hash of the text within the window compare it with the hash of the pattern only testing equality if the hashes match calculating the hash of pattern and substring of text calculate the https en wikipedia org wiki rolling_hash test_rabin_karp success test 1 test 2 test 3 test 4 test 5
alphabet_size = 256 modulus = 1000003 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 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(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 text_hash = ( (text_hash - ord(text[i]) * modulus_power) * alphabet_size + ord(text[i + p_len]) ) % modulus return False def test_rabin_karp() -> None: pattern = "abc1abc12" text1 = "alskfjaldsabc1abc1abc12k23adsfabcabc" text2 = "alskfjaldsk23adsfabcabc" assert rabin_karp(pattern, text1) assert not rabin_karp(pattern, text2) pattern = "ABABX" text = "ABABZABABYABABX" assert rabin_karp(pattern, text) pattern = "AAAB" text = "ABAAAAAB" assert rabin_karp(pattern, text) pattern = "abcdabcy" text = "abcxabcdabxabcdabcdabcy" assert rabin_karp(pattern, text) pattern = "Lü" text = "Lüsai" assert rabin_karp(pattern, text) pattern = "Lue" assert not rabin_karp(pattern, text) print("Success.") if __name__ == "__main__": test_rabin_karp()
remove duplicates from sentence removeduplicatespython is great and java is also great java python also and great is removeduplicatespython is great and java is also great java python also and great is remove duplicates from sentence remove_duplicates python is great and java is also great java python also and great is remove_duplicates python is great and java is also great java python also and great is
def remove_duplicates(sentence: str) -> str: return " ".join(sorted(set(sentence.split()))) if __name__ == "__main__": import doctest doctest.testmod()
reverse all words that are longer than the given length of characters in a sentence if unspecified length is taken as 0 reverselettershey wollef sroirraw 3 hey fellow warriors reverselettersnohtyp is nohtyp 2 python is python reverseletters1 12 123 1234 54321 654321 0 1 21 321 4321 12345 123456 reverselettersracecar racecar reverse all words that are longer than the given length of characters in a sentence if unspecified length is taken as 0 reverse_letters hey wollef sroirraw 3 hey fellow warriors reverse_letters nohtyp is nohtyp 2 python is python reverse_letters 1 12 123 1234 54321 654321 0 1 21 321 4321 12345 123456 reverse_letters racecar racecar
def reverse_letters(sentence: str, length: int = 0) -> str: return " ".join( "".join(word[::-1]) if len(word) > length else word for word in sentence.split() ) if __name__ == "__main__": import doctest doctest.testmod() print(reverse_letters("Hey wollef sroirraw"))
reverses words in a given string reversewordsi love python python love i reversewordsi love python python love i reverses words in a given string reverse_words i love python python love i reverse_words i love python python love i
def reverse_words(input_str: str) -> str: return " ".join(input_str.split()[::-1]) if __name__ == "__main__": import doctest doctest.testmod()
transforms a snakecase given string to camelcase or pascalcase if indicated defaults to not use pascal snaketocamelcasesomerandomstring somerandomstring snaketocamelcasesomerandomstring usepascaltrue somerandomstring snaketocamelcasesomerandomstringwithnumbers123 somerandomstringwithnumbers123 snaketocamelcasesomerandomstringwithnumbers123 usepascaltrue somerandomstringwithnumbers123 snaketocamelcase123 traceback most recent call last valueerror expected string as input found class int snaketocamelcasesomestring usepascaltrue traceback most recent call last valueerror expected boolean as usepascal parameter found class str transforms a snake_case given string to camelcase or pascalcase if indicated defaults to not use pascal snake_to_camel_case some_random_string somerandomstring snake_to_camel_case some_random_string use_pascal true somerandomstring snake_to_camel_case some_random_string_with_numbers_123 somerandomstringwithnumbers123 snake_to_camel_case some_random_string_with_numbers_123 use_pascal true somerandomstringwithnumbers123 snake_to_camel_case 123 traceback most recent call last valueerror expected string as input found class int snake_to_camel_case some_string use_pascal true traceback most recent call last valueerror expected boolean as use_pascal parameter found class str
def snake_to_camel_case(input_str: str, use_pascal: bool = False) -> str: if not isinstance(input_str, str): msg = f"Expected string as input, found {type(input_str)}" raise ValueError(msg) if not isinstance(use_pascal, bool): msg = f"Expected boolean as use_pascal parameter, found {type(use_pascal)}" raise ValueError(msg) 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]) if __name__ == "__main__": from doctest import testmod testmod()
will split the string up into all the values separated by the separator defaults to spaces splitapplebananacherryorange separator apple banana cherry orange splithello there hello there split112263 separator 11 22 63 split12 43 39 separator 12 43 39 will split the string up into all the values separated by the separator defaults to spaces split apple banana cherry orange separator apple banana cherry orange split hello there hello there split 11 22 63 separator 11 22 63 split 12 43 39 separator 12 43 39
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 if __name__ == "__main__": from doctest import testmod testmod()
general info https en wikipedia orgwikinamingconventionprogrammingpythonandruby pascal case an upper camel case https en wikipedia orgwikicamelcase camel case https en wikipedia orgwikicamelcase kebab case can be found in general info https en wikipedia orgwikinamingconventionprogrammingpythonandruby snake case https en wikipedia orgwikisnakecase assistant functions splitinputone two 31235three4four one two 31235three4four tosimplecaseone two 31235three4four onetwo31235three4four tosimplecasethis should be combined thisshouldbecombined tosimplecasethe first letters are capitalized then string is merged thefirstlettersarecapitalizedthenstringismerged tosimplecasespecial characters are ignored specialcharactersareignored returns the string concatenated with the delimiter we provide parameters text the string on which we want to perform operation upper boolean value to determine whether we want capitalized result or not separator the delimiter with which we want to concatenate words examples tocomplexcaseone two 31235three4four true onetwo31235three4four tocomplexcaseone two 31235three4four false onetwo31235three4four main content topascalcaseone two 31235three4four onetwo31235three4four tocamelcaseone two 31235three4four onetwo31235three4four tosnakecaseone two 31235three4four true onetwo31235three4four tosnakecaseone two 31235three4four false onetwo31235three4four tokebabcaseone two 31235three4four true onetwo31235three4four tokebabcaseone two 31235three4four false onetwo31235three4four general info https en wikipedia org wiki naming_convention_ programming python_and_ruby pascal case an upper camel case https en wikipedia org wiki camel_case camel case https en wikipedia org wiki camel_case kebab case can be found in general info https en wikipedia org wiki naming_convention_ programming python_and_ruby snake case https en wikipedia org wiki snake_case assistant functions split_input one two 31235three4four one two 31235three4four to_simple_case one two 31235three4four onetwo31235three4four to_simple_case this should be combined thisshouldbecombined to_simple_case the first letters are capitalized then string is merged thefirstlettersarecapitalizedthenstringismerged to_simple_case special characters are ignored specialcharactersareignored returns the string concatenated with the delimiter we provide parameters text the string on which we want to perform operation upper boolean value to determine whether we want capitalized result or not separator the delimiter with which we want to concatenate words examples to_complex_case one two 31235three4four true _ one_two_31235three4four to_complex_case one two 31235three4four false one two 31235three4four main content to_pascal_case one two 31235three4four onetwo31235three4four to_camel_case one two 31235three4four onetwo31235three4four to_snake_case one two 31235three4four true one_two_31235three4four to_snake_case one two 31235three4four false one_two_31235three4four to_kebab_case one two 31235three4four true one two 31235three4four to_kebab_case one two 31235three4four false one two 31235three4four
import re def split_input(str_: str) -> list: return [char.split() for char in re.split(r"[^ a-z A-Z 0-9 \s]", str_)] def to_simple_case(str_: str) -> str: string_split = split_input(str_) return "".join( ["".join([char.capitalize() for char in sub_str]) for sub_str in string_split] ) def to_complex_case(text: str, upper: bool, separator: str) -> str: try: string_split = split_input(text) if upper: res_str = "".join( [ separator.join([char.upper() for char in sub_str]) for sub_str in string_split ] ) else: res_str = "".join( [ separator.join([char.lower() for char in sub_str]) for sub_str in string_split ] ) return res_str except IndexError: return "not valid string" def to_pascal_case(text: str) -> str: return to_simple_case(text) def to_camel_case(text: str) -> str: try: res_str = to_simple_case(text) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def to_snake_case(text: str, upper: bool) -> str: return to_complex_case(text, upper, "_") def to_kebab_case(text: str, upper: bool) -> str: return to_complex_case(text, upper, "-") if __name__ == "__main__": __import__("doctest").testmod()
remove leading and trailing characters whitespace by default from a string args userstring str the input string to be stripped characters str optional optional characters to be removed default is whitespace returns str the stripped string examples strip hello hello strip world world strip123hello123 123 hello strip remove leading and trailing characters whitespace by default from a string args user_string str the input string to be stripped characters str optional optional characters to be removed default is whitespace returns str the stripped string examples strip hello hello strip world world strip 123hello123 123 hello strip
def strip(user_string: str, characters: str = " \t\n\r") -> str: start = 0 end = len(user_string) while start < end and user_string[start] in characters: start += 1 while end > start and user_string[end - 1] in characters: end -= 1 return user_string[start:end]
will format the string such that each line has exactly maxwidth characters and is fully left and right justified and return the list of justified text example 1 string this is an example of text justification maxwidth 16 output this is an example of text justification textjustificationthis is an example of text justification 16 this is an example of text justification example 2 string two roads diverged in a yellow wood maxwidth 16 output two roads diverged in a yellow wood textjustificationtwo roads diverged in a yellow wood 16 two roads diverged in a yellow wood time complexity omn space complexity omn converting string into list of strings split by a space if there is only word in line just insert overallspacescount for the remainder of line numspacesbetweenwordslisti tells you to insert numspacesbetweenwordslisti spaces after word on linei distribute spaces via round robin to the left words add the word add the spaces to insert just add the last word to the sentence join the aligned words list to form a justified line keep adding words until we can fill out maxwidth width sum of length of all words without overallspacescount lenword length of current word lenline number of overallspacescount to insert between words justify the line and add it to result reset new line and new width will format the string such that each line has exactly max_width characters and is fully left and right justified and return the list of justified text example 1 string this is an example of text justification max_width 16 output this is an example of text justification text_justification this is an example of text justification 16 this is an example of text justification example 2 string two roads diverged in a yellow wood max_width 16 output two roads diverged in a yellow wood text_justification two roads diverged in a yellow wood 16 two roads diverged in a yellow wood time complexity o m n space complexity o m n converting string into list of strings split by a space if there is only word in line just insert overall_spaces_count for the remainder of line num_spaces_between_words_list i tells you to insert num_spaces_between_words_list i spaces after word on line i distribute spaces via round robin to the left words add the word add the spaces to insert just add the last word to the sentence join the aligned words list to form a justified line keep adding words until we can fill out max_width width sum of length of all words without overall_spaces_count len word length of current word len line number of overall_spaces_count to insert between words justify the line and add it to result reset new line and new width
def text_justification(word: str, max_width: int) -> list: words = word.split() def justify(line: list, width: int, max_width: int) -> str: overall_spaces_count = max_width - width words_count = len(line) if len(line) == 1: return line[0] + " " * overall_spaces_count else: spaces_to_insert_between_words = words_count - 1 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 ) 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): aligned_words_list.append(line[i]) aligned_words_list.append(num_spaces_between_words_list[i] * " ") aligned_words_list.append(line[-1]) return "".join(aligned_words_list) answer = [] line: list[str] = [] width = 0 for word in words: if width + len(word) + len(line) <= max_width: line.append(word) width += len(word) else: answer.append(justify(line, width, max_width)) line, width = [word], len(word) remaining_spaces = max_width - width - len(line) answer.append(" ".join(line) + (remaining_spaces + 1) * " ") return answer if __name__ == "__main__": from doctest import testmod testmod()
converts a string to capitalized case preserving the input as is totitlecaseaakash aakash totitlecaseaakash aakash totitlecaseaakash aakash totitlecaseaakash aakash convert the first character to uppercase if it s lowercase convert the remaining characters to lowercase if they are uppercase converts a string to title case preserving the input as is sentencetotitlecaseaakash giri aakash giri sentencetotitlecaseaakash giri aakash giri sentencetotitlecaseaakash giri aakash giri sentencetotitlecaseaakash giri aakash giri converts a string to capitalized case preserving the input as is to_title_case aakash aakash to_title_case aakash aakash to_title_case aakash aakash to_title_case aakash aakash convert the first character to uppercase if it s lowercase convert the remaining characters to lowercase if they are uppercase converts a string to title case preserving the input as is sentence_to_title_case aakash giri aakash giri sentence_to_title_case aakash giri aakash giri sentence_to_title_case aakash giri aakash giri sentence_to_title_case aakash giri aakash giri
def to_title_case(word: str) -> str: if "a" <= word[0] <= "z": word = chr(ord(word[0]) - 32) + word[1:] for i in range(1, len(word)): if "A" <= word[i] <= "Z": word = word[:i] + chr(ord(word[i]) + 32) + word[i + 1 :] return word def sentence_to_title_case(input_str: str) -> str: return " ".join(to_title_case(word) for word in input_str.split()) if __name__ == "__main__": from doctest import testmod testmod()
finds the top k most frequent words from the provided word list this implementation aims to show how to solve the problem using the heap class already present in this repository computing order statistics is in fact a typical usage of heaps this is mostly shown for educational purposes since the problem can be solved in a few lines using collections counter from the python standard library from collections import counter def topkfrequentwordswords kvalue return x0 for x in counterwords mostcommonkvalue wordcount a 1 eqwordcount b 1 true wordcount a 1 eqwordcount a 1 true wordcount a 1 eqwordcount a 2 false wordcount a 1 eqwordcount b 2 false wordcount a 1 eq1 notimplemented wordcount a 1 ltwordcount b 1 false wordcount a 1 ltwordcount a 1 false wordcount a 1 ltwordcount a 2 true wordcount a 1 ltwordcount b 2 true wordcount a 2 ltwordcount a 1 false wordcount a 2 ltwordcount b 1 false wordcount a 1 lt1 notimplemented returns the kvalue most frequently occurring words in nonincreasing order of occurrence in this context a word is defined as an element in the provided list in case kvalue is greater than the number of distinct words a value of k equal to the number of distinct words will be considered instead topkfrequentwords a b c a c c 3 c a b topkfrequentwords a b c a c c 2 c a topkfrequentwords a b c a c c 1 c topkfrequentwords a b c a c c 0 topkfrequentwords 1 topkfrequentwords a a 2 a wordcount a 1 __eq__ wordcount b 1 true wordcount a 1 __eq__ wordcount a 1 true wordcount a 1 __eq__ wordcount a 2 false wordcount a 1 __eq__ wordcount b 2 false wordcount a 1 __eq__ 1 notimplemented wordcount a 1 __lt__ wordcount b 1 false wordcount a 1 __lt__ wordcount a 1 false wordcount a 1 __lt__ wordcount a 2 true wordcount a 1 __lt__ wordcount b 2 true wordcount a 2 __lt__ wordcount a 1 false wordcount a 2 __lt__ wordcount b 1 false wordcount a 1 __lt__ 1 notimplemented returns the k_value most frequently occurring words in non increasing order of occurrence in this context a word is defined as an element in the provided list in case k_value is greater than the number of distinct words a value of k equal to the number of distinct words will be considered instead top_k_frequent_words a b c a c c 3 c a b top_k_frequent_words a b c a c c 2 c a top_k_frequent_words a b c a c c 1 c top_k_frequent_words a b c a c c 0 top_k_frequent_words 1 top_k_frequent_words a a 2 a
from collections import Counter from functools import total_ordering from data_structures.heap.heap import Heap @total_ordering class WordCount: def __init__(self, word: str, count: int) -> None: self.word = word self.count = count def __eq__(self, other: object) -> bool: if not isinstance(other, WordCount): return NotImplemented return self.count == other.count def __lt__(self, other: object) -> bool: if not isinstance(other, WordCount): return NotImplemented return self.count < other.count def top_k_frequent_words(words: list[str], k_value: int) -> list[str]: heap: Heap[WordCount] = Heap() count_by_word = Counter(words) heap.build_max_heap( [WordCount(word, count) for word, count in count_by_word.items()] ) return [heap.extract_max().word for _ in range(min(k_value, len(count_by_word)))] if __name__ == "__main__": import doctest doctest.testmod()
convert an entire string to ascii uppercase letters by looking for lowercase ascii letters and subtracting 32 from their integer representation to get the uppercase letter upperwow wow upperhello hello upperwhat what upperwh32 wh32 convert an entire string to ascii uppercase letters by looking for lowercase ascii letters and subtracting 32 from their integer representation to get the uppercase letter upper wow wow upper hello hello upper what what upper wh 32 wh 32
def upper(word: str) -> str: return "".join(chr(ord(char) - 32) if "a" <= char <= "z" else char for char in word) if __name__ == "__main__": from doctest import testmod testmod()
returns a so called wave of a given string wave cat cat cat cat wave one one one one wave book book book book book returns a so called wave of a given string wave cat cat cat cat wave one one one one wave book book book book book
def wave(txt: str) -> list: return [ txt[:a] + txt[a].upper() + txt[a + 1 :] for a in range(len(txt)) if txt[a].isalpha() ] if __name__ == "__main__": __import__("doctest").testmod()
implementation of regular expression matching with support for and matches any single character matches zero or more of the preceding element the matching should cover the entire input string not partial uses bottomup dynamic programming solution for matching the input string with a given pattern runtime oleninputstringlenpattern arguments inputstring str any string which should be compared with the pattern pattern str the string that represents a pattern and may contain for single character matches and for zero or more of preceding character matches note the pattern cannot start with a because there should be at least one character before returns a boolean denoting whether the given string follows the pattern examples matchpatternaab cab true matchpatterndabc abc false matchpatternaaa aa false matchpatternaaa a a true matchpatternaaab aa false matchpatternaaab true matchpatterna bbbb false matchpattern bbbb false matchpatterna false matchpattern true dp is a 2d matrix where dpij denotes whether prefix string of length i of inputstring matches with prefix string of length j of given pattern dp stands for dynamic programming since string of zero length match pattern of zero length since pattern of zero length will never match with string of nonzero length since string of zero length will match with pattern where there is at least one alternatively now using bottomup approach to find for all remaining lengths inputing the strings inputstring inputinput a string pattern inputinput a pattern using function to check whether given string matches the given pattern uses bottom up dynamic programming solution for matching the input string with a given pattern runtime o len input_string len pattern arguments input_string str any string which should be compared with the pattern pattern str the string that represents a pattern and may contain for single character matches and for zero or more of preceding character matches note the pattern cannot start with a because there should be at least one character before returns a boolean denoting whether the given string follows the pattern examples match_pattern aab c a b true match_pattern dabc abc false match_pattern aaa aa false match_pattern aaa a a true match_pattern aaab aa false match_pattern aaab true match_pattern a bbbb false match_pattern bbbb false match_pattern a false match_pattern true 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 since string of zero length match pattern of zero length since pattern of zero length will never match with string of non zero length since string of zero length will match with pattern where there is at least one alternatively now using bottom up approach to find for all remaining lengths inputing the strings input_string input input a string pattern input input a pattern using function to check whether given string matches the given pattern
def match_pattern(input_string: str, pattern: str) -> bool: len_string = len(input_string) + 1 len_pattern = len(pattern) + 1 dp = [[0 for i in range(len_pattern)] for j in range(len_string)] dp[0][0] = 1 for i in range(1, len_string): dp[i][0] = 0 for j in range(1, len_pattern): dp[0][j] = dp[0][j - 2] if pattern[j - 1] == "*" else 0 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]) if __name__ == "__main__": import doctest doctest.testmod() input_string = "aab" pattern = "c*a*b" if match_pattern(input_string, pattern): print(f"{input_string} matches the given pattern {pattern}") else: print(f"{input_string} does not match with the given pattern {pattern}")
sarathkaul on 171119 modified by arkadip bhattacharyadarkmatter18 on 20042020 from collections import counter sentence a b a b c b d b d e f e g e h e i e j e 0 occurencedict wordoccurrencesentence alloccurencedictword count for word count in countersentence split items true dictwordoccurrencetwo spaces two 1 spaces 1 creating a dictionary containing count of each word sarathkaul on 17 11 19 modified by arkadip bhattacharya darkmatter18 on 20 04 2020 from collections import counter sentence a b a b c b d b d e f e g e h e i e j e 0 occurence_dict word_occurrence sentence all occurence_dict word count for word count in counter sentence split items true dict word_occurrence two spaces two 1 spaces 1 creating a dictionary containing count of each word
from collections import defaultdict def word_occurrence(sentence: str) -> dict: occurrence: defaultdict[str, int] = defaultdict(int) for word in sentence.split(): occurrence[word] += 1 return occurrence if __name__ == "__main__": for word, count in word_occurrence("INPUT STRING").items(): print(f"{word}: {count}")
returns numerical pattern of character appearances in given word getwordpattern getwordpattern 0 getwordpatternpattern 0 1 2 2 3 4 5 getwordpatternword pattern 0 1 2 3 4 5 6 7 7 8 2 9 getwordpatternget word pattern 0 1 2 3 4 5 6 7 3 8 9 2 2 1 6 10 getwordpattern traceback most recent call last typeerror getwordpattern missing 1 required positional argument word getwordpattern1 traceback most recent call last attributeerror int object has no attribute upper getwordpattern1 1 traceback most recent call last attributeerror float object has no attribute upper getwordpattern traceback most recent call last attributeerror list object has no attribute upper done 9 581 word patterns found in 0 58 seconds returns numerical pattern of character appearances in given word get_word_pattern get_word_pattern 0 get_word_pattern pattern 0 1 2 2 3 4 5 get_word_pattern word pattern 0 1 2 3 4 5 6 7 7 8 2 9 get_word_pattern get word pattern 0 1 2 3 4 5 6 7 3 8 9 2 2 1 6 10 get_word_pattern traceback most recent call last typeerror get_word_pattern missing 1 required positional argument word get_word_pattern 1 traceback most recent call last attributeerror int object has no attribute upper get_word_pattern 1 1 traceback most recent call last attributeerror float object has no attribute upper get_word_pattern traceback most recent call last attributeerror list object has no attribute upper done 9 581 word patterns found in 0 58 seconds
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) if __name__ == "__main__": import pprint import time start_time = time.time() with open("dictionary.txt") as in_file: word_list = in_file.read().splitlines() all_patterns: dict = {} for word in word_list: pattern = get_word_pattern(word) if pattern in all_patterns: all_patterns[pattern].append(word) else: all_patterns[pattern] = [word] with open("word_patterns.txt", "w") as out_file: out_file.write(pprint.pformat(all_patterns)) total_time = round(time.time() - start_time, 2) print(f"Done! {len(all_patterns):,} word patterns found in {total_time} seconds.")
https cpalgorithms comstringzfunction html zfunction or z algorithm efficient algorithm for pattern occurrence in a string time complexity on where n is the length of the string for the given string this function computes value for each index which represents the maximal length substring starting from the index and is the same as the prefix of the same size e x for string abab for second index value would be 2 for the value of the first element the algorithm always returns 0 zfunctionabracadabra 0 0 0 1 0 1 0 4 0 0 1 zfunctionaaaa 0 3 2 1 zfunctionzxxzxxz 0 0 0 4 0 0 1 initialize interval s left pointer and right pointer case when current index is inside the interval if new index s result gives us more right interval we ve to update leftpointer and rightpointer check if we have to move forward to the next characters or not example of using zfunction for pattern occurrence given function returns the number of times pattern appears in inputstr as a substring findpatternabr abracadabra 2 findpatterna aaaa 4 findpatternxz zxxzxxz 2 concatenate pattern and inputstr and call zfunction with concatenated string if value is greater then length of the pattern string that means this index is starting position of substring which is equal to pattern string for the given string this function computes value for each index which represents the maximal length substring starting from the index and is the same as the prefix of the same size e x for string abab for second index value would be 2 for the value of the first element the algorithm always returns 0 z_function abracadabra 0 0 0 1 0 1 0 4 0 0 1 z_function aaaa 0 3 2 1 z_function zxxzxxz 0 0 0 4 0 0 1 initialize interval s left pointer and right pointer case when current index is inside the interval if new index s result gives us more right interval we ve to update left_pointer and right_pointer check if we have to move forward to the next characters or not example of using z function for pattern occurrence given function returns the number of times pattern appears in input_str as a substring find_pattern abr abracadabra 2 find_pattern a aaaa 4 find_pattern xz zxxzxxz 2 concatenate pattern and input_str and call z_function with concatenated string if value is greater then length of the pattern string that means this index is starting position of substring which is equal to pattern string
def z_function(input_str: str) -> list[int]: z_result = [0 for i in range(len(input_str))] left_pointer, right_pointer = 0, 0 for i in range(1, len(input_str)): if i <= right_pointer: min_edge = min(right_pointer - i + 1, z_result[i - left_pointer]) z_result[i] = min_edge while go_next(i, z_result, input_str): z_result[i] += 1 if i + z_result[i] - 1 > right_pointer: left_pointer, right_pointer = i, i + z_result[i] - 1 return z_result def go_next(i: int, z_result: list[int], s: str) -> bool: return i + z_result[i] < len(s) and s[z_result[i]] == s[i + z_result[i]] def find_pattern(pattern: str, input_str: str) -> int: answer = 0 z_result = z_function(pattern + input_str) for val in z_result: if val >= len(pattern): answer += 1 return answer if __name__ == "__main__": import doctest doctest.testmod()
get co2 emission data from the uk carbonintensity api emission in the last half hour emissions in a specific date range emission in the last half hour emissions in a specific date range
from datetime import date import requests BASE_URL = "https://api.carbonintensity.org.uk/intensity" def fetch_last_half_hour() -> str: last_half_hour = requests.get(BASE_URL).json()["data"][0] return last_half_hour["intensity"]["actual"] def fetch_from_to(start, end) -> list: return requests.get(f"{BASE_URL}/{start}/{end}").json()["data"] if __name__ == "__main__": for entry in fetch_from_to(start=date(2020, 10, 1), end=date(2020, 10, 3)): print("from {from} to {to}: {intensity[actual]}".format(**entry)) print(f"{fetch_last_half_hour() = }")
res raiseforstatus res raise_for_status only for knowing the class
import sys import webbrowser import requests from bs4 import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": print("Googling.....") url = "https://www.google.com/search?q=" + " ".join(sys.argv[1:]) res = requests.get(url, headers={"UserAgent": UserAgent().random}) with open("project1a.html", "wb") as out_file: for data in res.iter_content(10000): out_file.write(data) soup = BeautifulSoup(res.text, "html.parser") links = list(soup.select(".eZt8xd"))[:5] print(len(links)) for link in links: if link.text == "Maps": webbrowser.open(link.get("href")) else: webbrowser.open(f"https://google.com{link.get('href')}")
get the citation from google scholar using title and year of publication and volume and pages of journal return the citation number return the citation number
import requests from bs4 import BeautifulSoup def get_citation(base_url: str, params: dict) -> str: soup = BeautifulSoup(requests.get(base_url, params=params).content, "html.parser") div = soup.find("div", attrs={"class": "gs_ri"}) anchors = div.find("div", attrs={"class": "gs_fl"}).find_all("a") return anchors[2].get_text() if __name__ == "__main__": params = { "title": ( "Precisely geometry controlled microsupercapacitors for ultrahigh areal " "capacitance, volumetric capacitance, and energy density" ), "journal": "Chem. Mater.", "volume": 30, "pages": "3979-3990", "year": 2018, "hl": "en", } print(get_citation("https://scholar.google.com/scholar_lookup", params=params))
search for the symbol at https finance yahoo comlookup search for the symbol at https finance yahoo com lookup
import requests from bs4 import BeautifulSoup def stock_price(symbol: str = "AAPL") -> str: url = f"https://finance.yahoo.com/quote/{symbol}?p={symbol}" yahoo_finance_source = requests.get(url, headers={"USER-AGENT": "Mozilla/5.0"}).text soup = BeautifulSoup(yahoo_finance_source, "html.parser") specific_fin_streamer_tag = soup.find("fin-streamer", {"data-test": "qsp-price"}) if specific_fin_streamer_tag: text = specific_fin_streamer_tag.get_text() return text return "No <fin-streamer> tag with the specified data-test attribute found." if __name__ == "__main__": for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split(): print(f"Current {symbol:<4} stock price is {stock_price(symbol):>8}")
put your api keys here define the url for the apis with placeholders currentweatherlocation traceback most recent call last valueerror no api keys provided or no valid data returned put your api key s here define the url for the apis with placeholders current_weather location traceback most recent call last valueerror no api keys provided or no valid data returned
import requests OPENWEATHERMAP_API_KEY = "" WEATHERSTACK_API_KEY = "" OPENWEATHERMAP_URL_BASE = "https://api.openweathermap.org/data/2.5/weather" WEATHERSTACK_URL_BASE = "http://api.weatherstack.com/current" def current_weather(location: str) -> list[dict]: weather_data = [] if OPENWEATHERMAP_API_KEY: params_openweathermap = {"q": location, "appid": OPENWEATHERMAP_API_KEY} response_openweathermap = requests.get( OPENWEATHERMAP_URL_BASE, params=params_openweathermap ) weather_data.append({"OpenWeatherMap": response_openweathermap.json()}) if WEATHERSTACK_API_KEY: params_weatherstack = {"query": location, "access_key": WEATHERSTACK_API_KEY} response_weatherstack = requests.get( WEATHERSTACK_URL_BASE, params=params_weatherstack ) weather_data.append({"Weatherstack": response_weatherstack.json()}) if not weather_data: raise ValueError("No API keys provided or no valid data returned.") return weather_data if __name__ == "__main__": from pprint import pprint location = "to be determined..." while location: location = input("Enter a location (city name or latitude,longitude): ").strip() if location: try: weather_data = current_weather(location) for forecast in weather_data: pprint(forecast) except ValueError as e: print(repr(e)) location = ""
searches google using the provided query term and downloads the images in a folder args query the image search term to be provided by the user defaults to dhaka imagenumbers description defaults to 5 returns the number of images successfully downloaded comment out slow 4 20s call doctests downloadimagesfromgooglequery 5 downloadimagesfromgooglequerypotato 5 searches google using the provided query term and downloads the images in a folder args query the image search term to be provided by the user defaults to dhaka image_numbers description defaults to 5 returns the number of images successfully downloaded comment out slow 4 20s call doctests download_images_from_google_query 5 download_images_from_google_query potato 5 prevent abuse noqa s310
import json import os import re import sys import urllib.request import requests from bs4 import BeautifulSoup headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" " (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582" } def download_images_from_google_query(query: str = "dhaka", max_images: int = 5) -> int: max_images = min(max_images, 50) params = { "q": query, "tbm": "isch", "hl": "en", "ijn": "0", } html = requests.get("https://www.google.com/search", params=params, headers=headers) soup = BeautifulSoup(html.text, "html.parser") matched_images_data = "".join( re.findall(r"AF_initDataCallback\(([^<]+)\);", str(soup.select("script"))) ) matched_images_data_fix = json.dumps(matched_images_data) matched_images_data_json = json.loads(matched_images_data_fix) matched_google_image_data = re.findall( r"\[\"GRID_STATE0\",null,\[\[1,\[0,\".*?\",(.*),\"All\",", matched_images_data_json, ) if not matched_google_image_data: return 0 removed_matched_google_images_thumbnails = re.sub( r"\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]", "", str(matched_google_image_data), ) matched_google_full_resolution_images = re.findall( r"(?:'|,),\[\"(https:|http.*?)\",\d+,\d+\]", removed_matched_google_images_thumbnails, ) for index, fixed_full_res_image in enumerate(matched_google_full_resolution_images): if index >= max_images: return index original_size_img_not_fixed = bytes(fixed_full_res_image, "ascii").decode( "unicode-escape" ) original_size_img = bytes(original_size_img_not_fixed, "ascii").decode( "unicode-escape" ) opener = urllib.request.build_opener() opener.addheaders = [ ( "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" " (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582", ) ] urllib.request.install_opener(opener) path_name = f"query_{query.replace(' ', '_')}" if not os.path.exists(path_name): os.makedirs(path_name) urllib.request.urlretrieve( original_size_img, f"{path_name}/original_size_img_{index}.jpg" ) return index if __name__ == "__main__": try: image_count = download_images_from_google_query(sys.argv[1]) print(f"{image_count} images were downloaded to disk.") except IndexError: print("Please provide a search term.") raise
summary take an url and return list of anime after scraping the site typesearchscraperdemonslayer class list args animename str name of anime raises e raises exception on failure returns list list of animes concat the name to form the search url is the response ok parse with soup get list of anime for each anime insert to list the name and url summary take an url and return list of episodes after scraping the site for an url typesearchanimeepisodelistanimekimetsunoyaiba class list args episodeendpoint str endpoint of episode raises e description returns list list of episodes with this id get the episode list summary get click url and download url from episode url typegetanimeepisodewatchkimetsunoyaiba1 class list args episodeendpoint str endpoint of episode raises e description returns list list of download and watch url summary take an url and return list of anime after scraping the site type search_scraper demon_slayer class list args anime_name str name of anime raises e raises exception on failure returns list list of animes concat the name to form the search url request the url is the response ok parse with soup get list of anime for each anime insert to list the name and url summary take an url and return list of episodes after scraping the site for an url type search_anime_episode_list anime kimetsu no yaiba class list args episode_endpoint str endpoint of episode raises e description returns list list of episodes with this id get the episode list summary get click url and download url from episode url type get_anime_episode watch kimetsu no yaiba 1 class list args episode_endpoint str endpoint of episode raises e description returns list list of download and watch url
import requests from bs4 import BeautifulSoup, NavigableString, Tag from fake_useragent import UserAgent BASE_URL = "https://ww1.gogoanime2.org" def search_scraper(anime_name: str) -> list: search_url = f"{BASE_URL}/search/{anime_name}" response = requests.get( search_url, headers={"UserAgent": UserAgent().chrome} ) response.raise_for_status() soup = BeautifulSoup(response.text, "html.parser") anime_ul = soup.find("ul", {"class": "items"}) if anime_ul is None or isinstance(anime_ul, NavigableString): msg = f"Could not find and anime with name {anime_name}" raise ValueError(msg) anime_li = anime_ul.children anime_list = [] for anime in anime_li: if isinstance(anime, Tag): anime_url = anime.find("a") if anime_url is None or isinstance(anime_url, NavigableString): continue anime_title = anime.find("a") if anime_title is None or isinstance(anime_title, NavigableString): continue anime_list.append({"title": anime_title["title"], "url": anime_url["href"]}) return anime_list def search_anime_episode_list(episode_endpoint: str) -> list: request_url = f"{BASE_URL}{episode_endpoint}" response = requests.get(url=request_url, headers={"UserAgent": UserAgent().chrome}) response.raise_for_status() soup = BeautifulSoup(response.text, "html.parser") episode_page_ul = soup.find("ul", {"id": "episode_related"}) if episode_page_ul is None or isinstance(episode_page_ul, NavigableString): msg = f"Could not find any anime eposiodes with name {anime_name}" raise ValueError(msg) episode_page_li = episode_page_ul.children episode_list = [] for episode in episode_page_li: if isinstance(episode, Tag): url = episode.find("a") if url is None or isinstance(url, NavigableString): continue title = episode.find("div", {"class": "name"}) if title is None or isinstance(title, NavigableString): continue episode_list.append( {"title": title.text.replace(" ", ""), "url": url["href"]} ) return episode_list def get_anime_episode(episode_endpoint: str) -> list: episode_page_url = f"{BASE_URL}{episode_endpoint}" response = requests.get( url=episode_page_url, headers={"User-Agent": UserAgent().chrome} ) response.raise_for_status() soup = BeautifulSoup(response.text, "html.parser") url = soup.find("iframe", {"id": "playerframe"}) if url is None or isinstance(url, NavigableString): msg = f"Could not find url and download url from {episode_endpoint}" raise RuntimeError(msg) episode_url = url["src"] if not isinstance(episode_url, str): msg = f"Could not find url and download url from {episode_endpoint}" raise RuntimeError(msg) download_url = episode_url.replace("/embed/", "/playlist/") + ".m3u8" return [f"{BASE_URL}{episode_url}", f"{BASE_URL}{download_url}"] if __name__ == "__main__": anime_name = input("Enter anime name: ").strip() anime_list = search_scraper(anime_name) print("\n") if len(anime_list) == 0: print("No anime found with this name") else: print(f"Found {len(anime_list)} results: ") for i, anime in enumerate(anime_list): anime_title = anime["title"] print(f"{i+1}. {anime_title}") anime_choice = int(input("\nPlease choose from the following list: ").strip()) chosen_anime = anime_list[anime_choice - 1] print(f"You chose {chosen_anime['title']}. Searching for episodes...") episode_list = search_anime_episode_list(chosen_anime["url"]) if len(episode_list) == 0: print("No episode found for this anime") else: print(f"Found {len(episode_list)} results: ") for i, episode in enumerate(episode_list): print(f"{i+1}. {episode['title']}") episode_choice = int(input("\nChoose an episode by serial no: ").strip()) chosen_episode = episode_list[episode_choice - 1] print(f"You chose {chosen_episode['title']}. Searching...") episode_url, download_url = get_anime_episode(chosen_episode["url"]) print(f"\nTo watch, ctrl+click on {episode_url}.") print(f"To download, ctrl+click on {download_url}.")
sarathkaul on 121119 fetching a list of articles in json format each article in the list is a dict sarathkaul on 12 11 19 fetching a list of articles in json format each article in the list is a dict
import requests _NEWS_API = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" def fetch_bbc_news(bbc_news_api_key: str) -> None: bbc_news_page = requests.get(_NEWS_API + bbc_news_api_key).json() for i, article in enumerate(bbc_news_page["articles"], 1): print(f"{i}.) {article['title']}") if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key="<Your BBC News API key goes here>")
usrbinenv python3 sarathkaul on 141119 updated by lawric1 on 241120 authentication will be made via access token to generate your personal access token visit https github comsettingstokens note never hardcode any credential information in the code always use an environment file to store the private information and use the os module to get the information during runtime create a env file in the root directory and write these two lines in that file with your token usrbinenv bash export usertoken https docs github comenfreeproteamlatestrestreferenceusersgettheauthenticateduser https github comsettingstokens fetch github info of a user using the requests module usr bin env python3 sarathkaul on 14 11 19 updated by lawric1 on 24 11 20 authentication will be made via access token to generate your personal access token visit https github com settings tokens note never hardcode any credential information in the code always use an environment file to store the private information and use the os module to get the information during runtime create a env file in the root directory and write these two lines in that file with your token usr bin env bash export user_token https docs github com en free pro team latest rest reference users get the authenticated user https github com settings tokens fetch github info of a user using the requests module pragma no cover
from __future__ import annotations import os from typing import Any import requests BASE_URL = "https://api.github.com" AUTHENTICATED_USER_ENDPOINT = BASE_URL + "/user" USER_TOKEN = os.environ.get("USER_TOKEN", "") def fetch_github_info(auth_token: str) -> dict[Any, Any]: headers = { "Authorization": f"token {auth_token}", "Accept": "application/vnd.github.v3+json", } return requests.get(AUTHENTICATED_USER_ENDPOINT, headers=headers).json() if __name__ == "__main__": if USER_TOKEN: for key, value in fetch_github_info(USER_TOKEN).items(): print(f"{key}: {value}") else: raise ValueError("'USER_TOKEN' field cannot be empty.")
scraping jobs given job title and location from indeed website this attribute finds out all the specifics listed in a job this attribute finds out all the specifics listed in a job
from __future__ import annotations from collections.abc import Generator import requests from bs4 import BeautifulSoup url = "https://www.indeed.co.in/jobs?q=mobile+app+development&l=" def fetch_jobs(location: str = "mumbai") -> Generator[tuple[str, str], None, None]: soup = BeautifulSoup(requests.get(url + location).content, "html.parser") for job in soup.find_all("div", attrs={"data-tn-component": "organicJob"}): job_title = job.find("a", attrs={"data-tn-element": "jobTitle"}).text.strip() company_name = job.find("span", {"class": "company"}).text.strip() yield job_title, company_name if __name__ == "__main__": for i, job in enumerate(fetch_jobs("Bangalore"), 1): print(f"Job {i:>2} is {job[0]} at {job[1]}")
this file fetches quotes from the zenquotes api it does not require any api key as it uses free tier for more details and premium features visit https zenquotes io response object has all the info with the quote to retrieve the actual quote access the response json object as below response json is a list of json object response json0 q actual quote response json0 a name response json0 h in html format response object has all the info with the quote to retrieve the actual quote access the response json object as below response json is a list of json object response json 0 q actual quote response json 0 a name response json 0 h in html format
import pprint import requests API_ENDPOINT_URL = "https://zenquotes.io/api" def quote_of_the_day() -> list: return requests.get(API_ENDPOINT_URL + "/today").json() def random_quotes() -> list: return requests.get(API_ENDPOINT_URL + "/random").json() if __name__ == "__main__": response = random_quotes() pprint.pprint(response)
scrape the price and pharmacy name for a prescription drug from rx site after providing the drug name and zipcode summary this function will take input of drug name and zipcode then request to the baseurl site get the page data and scrape it to the generate the list of lowest prices for the prescription drug args drugname str drug name zipcodestr zip code returns list list of pharmacy name and price fetchpharmacyandpricelistnone none fetchpharmacyandpricelistnone 30303 fetchpharmacyandpricelisteliquis none has user provided both inputs is the response ok scrape the data using bs4 this list will store the name and price fetch all the grids that contains the items get the pharmacy price get price of the drug enter a drug name and a zip code summary this function will take input of drug name and zipcode then request to the base_url site get the page data and scrape it to the generate the list of lowest prices for the prescription drug args drug_name str drug name zip_code str zip code returns list list of pharmacy name and price fetch_pharmacy_and_price_list none none fetch_pharmacy_and_price_list none 30303 fetch_pharmacy_and_price_list eliquis none has user provided both inputs is the response ok scrape the data using bs4 this list will store the name and price fetch all the grids that contains the items get the pharmacy price get price of the drug enter a drug name and a zip code
from urllib.error import HTTPError from bs4 import BeautifulSoup from requests import exceptions, get BASE_URL = "https://www.wellrx.com/prescriptions/{0}/{1}/?freshSearch=true" def fetch_pharmacy_and_price_list(drug_name: str, zip_code: str) -> list | None: try: if not drug_name or not zip_code: return None request_url = BASE_URL.format(drug_name, zip_code) response = get(request_url) response.raise_for_status() soup = BeautifulSoup(response.text, "html.parser") pharmacy_price_list = [] grid_list = soup.find_all("div", {"class": "grid-x pharmCard"}) if grid_list and len(grid_list) > 0: for grid in grid_list: pharmacy_name = grid.find("p", {"class": "list-title"}).text price = grid.find("span", {"p", "price price-large"}).text pharmacy_price_list.append( { "pharmacy_name": pharmacy_name, "price": price, } ) return pharmacy_price_list except (HTTPError, exceptions.RequestException, ValueError): return None if __name__ == "__main__": drug_name = input("Enter drug name: ").strip() zip_code = input("Enter zip code: ").strip() pharmacy_price_list: list | None = fetch_pharmacy_and_price_list( drug_name, zip_code ) if pharmacy_price_list: print(f"\nSearch results for {drug_name} at location {zip_code}:") for pharmacy_price in pharmacy_price_list: name = pharmacy_price["pharmacy_name"] price = pharmacy_price["price"] print(f"Pharmacy: {name} Price: {price}") else: print(f"No results found for {drug_name}")
this file provides a function which will take a product name as input from the user and fetch from amazon information about products of this name or category the product information will include title url price ratings and the discount available take a product name or category as input and return product information from amazon including title url price ratings and the discount available initialize a pandas dataframe with the column titles loop through each entry and store them in the dataframe take a product name or category as input and return product information from amazon including title url price ratings and the discount available initialize a pandas dataframe with the column titles loop through each entry and store them in the dataframe
from itertools import zip_longest import requests from bs4 import BeautifulSoup from pandas import DataFrame def get_amazon_product_data(product: str = "laptop") -> DataFrame: url = f"https://www.amazon.in/laptop/s?k={product}" header = { "User-Agent": ( "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36" "(KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36" ), "Accept-Language": "en-US, en;q=0.5", } soup = BeautifulSoup(requests.get(url, headers=header).text, features="lxml") data_frame = DataFrame( columns=[ "Product Title", "Product Link", "Current Price of the product", "Product Rating", "MRP of the product", "Discount", ] ) for item, _ in zip_longest( soup.find_all( "div", attrs={"class": "s-result-item", "data-component-type": "s-search-result"}, ), soup.find_all("div", attrs={"class": "a-row a-size-base a-color-base"}), ): try: product_title = item.h2.text product_link = "https://www.amazon.in/" + item.h2.a["href"] product_price = item.find("span", attrs={"class": "a-offscreen"}).text try: product_rating = item.find("span", attrs={"class": "a-icon-alt"}).text except AttributeError: product_rating = "Not available" try: product_mrp = ( "₹" + item.find( "span", attrs={"class": "a-price a-text-price"} ).text.split("₹")[1] ) except AttributeError: product_mrp = "" try: discount = float( ( ( float(product_mrp.strip("₹").replace(",", "")) - float(product_price.strip("₹").replace(",", "")) ) / float(product_mrp.strip("₹").replace(",", "")) ) * 100 ) except ValueError: discount = float("nan") except AttributeError: continue data_frame.loc[str(len(data_frame.index))] = [ product_title, product_link, product_price, product_rating, product_mrp, discount, ] data_frame.loc[ data_frame["Current Price of the product"] > data_frame["MRP of the product"], "MRP of the product", ] = " " data_frame.loc[ data_frame["Current Price of the product"] > data_frame["MRP of the product"], "Discount", ] = " " data_frame.index += 1 return data_frame if __name__ == "__main__": product = "headphones" get_amazon_product_data(product).to_csv(f"Amazon Product Data for {product}.csv")
function to get geolocation data for an ip address construct the url for the ip geolocation api send a get request to the api check if the http request was successful parse the response as json check if city region and country information is available handle networkrelated exceptions handle json parsing errors prompt the user to enter an ip address get the geolocation data and print it function to get geolocation data for an ip address construct the url for the ip geolocation api send a get request to the api check if the http request was successful parse the response as json check if city region and country information is available handle network related exceptions handle json parsing errors prompt the user to enter an ip address get the geolocation data and print it
import requests def get_ip_geolocation(ip_address: str) -> str: try: url = f"https://ipinfo.io/{ip_address}/json" response = requests.get(url) response.raise_for_status() data = response.json() if "city" in data and "region" in data and "country" in data: location = f"Location: {data['city']}, {data['region']}, {data['country']}" else: location = "Location data not found." return location except requests.exceptions.RequestException as e: return f"Request error: {e}" except ValueError as e: return f"JSON parsing error: {e}" if __name__ == "__main__": ip_address = input("Enter an IP address: ") location = get_ip_geolocation(ip_address) print(location)
caution you may get a json decoding error this works for some of us but fails for others calculates age from given unix time format returns age as string from datetime import datetime utc yearssincecreate datetime nowtzutc year 2022 intcalculateage657244800000 yearssincecreate 73 intcalculateage46915200000 yearssincecreate 51 convert date from milliseconds to seconds handle timestamp before epoch get top 10 realtime billionaires using forbes api returns list of top 10 realtime billionaires data display forbes real time billionaires in a rich table args forbesbillionaires list forbes top 10 real time billionaires calculates age from given unix time format returns age as string from datetime import datetime utc years_since_create datetime now tz utc year 2022 int calculate_age 657244800000 years_since_create 73 int calculate_age 46915200000 years_since_create 51 convert date from milliseconds to seconds handle timestamp before epoch get top 10 realtime billionaires using forbes api returns list of top 10 realtime billionaires data display forbes real time billionaires in a rich table args forbes_billionaires list forbes top 10 real time billionaires
from datetime import UTC, datetime, timedelta import requests from rich import box from rich import console as rich_console from rich import table as rich_table LIMIT = 10 TODAY = datetime.now() API_URL = ( "https://www.forbes.com/forbesapi/person/rtb/0/position/true.json" "?fields=personName,gender,source,countryOfCitizenship,birthDate,finalWorth" f"&limit={LIMIT}" ) def calculate_age(unix_date: float) -> str: unix_date /= 1000 if unix_date < 0: epoch = datetime.fromtimestamp(0, tz=UTC) seconds_since_epoch = (datetime.now(tz=UTC) - epoch).seconds birthdate = ( epoch - timedelta(seconds=abs(unix_date) - seconds_since_epoch) ).date() else: birthdate = datetime.fromtimestamp(unix_date, tz=UTC).date() return str( TODAY.year - birthdate.year - ((TODAY.month, TODAY.day) < (birthdate.month, birthdate.day)) ) def get_forbes_real_time_billionaires() -> list[dict[str, str]]: response_json = requests.get(API_URL).json() return [ { "Name": person["personName"], "Source": person["source"], "Country": person["countryOfCitizenship"], "Gender": person["gender"], "Worth ($)": f"{person['finalWorth'] / 1000:.1f} Billion", "Age": calculate_age(person["birthDate"]), } for person in response_json["personList"]["personsLists"] ] def display_billionaires(forbes_billionaires: list[dict[str, str]]) -> None: table = rich_table.Table( title=f"Forbes Top {LIMIT} Real Time Billionaires at {TODAY:%Y-%m-%d %H:%M}", style="green", highlight=True, box=box.SQUARE, ) for key in forbes_billionaires[0]: table.add_column(key) for billionaire in forbes_billionaires: table.add_row(*billionaire.values()) rich_console.Console().print(table) if __name__ == "__main__": display_billionaires(get_forbes_real_time_billionaires())
get the top maxstories posts from hackernews https news ycombinator com get the top max_stories posts from hackernews https news ycombinator com
from __future__ import annotations import requests def get_hackernews_story(story_id: str) -> dict: url = f"https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty" return requests.get(url).json() def hackernews_top_stories(max_stories: int = 10) -> list[dict]: url = "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty" story_ids = requests.get(url).json()[:max_stories] return [get_hackernews_story(story_id) for story_id in story_ids] def hackernews_top_stories_as_markdown(max_stories: int = 10) -> str: stories = hackernews_top_stories(max_stories) return "\n".join("* [{title}]({url})".format(**story) for story in stories) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
twitter api credentials ize twitter initialize tweepy initialize a list to hold all the tweepy tweets make initial request for most recent tweets 200 is the maximum allowed count save most recent tweets save the id of the oldest tweet less one keep grabbing tweets until there are no tweets left to grab all subsequent requests use the maxid param to prevent duplicates save most recent tweets update the id of the oldest tweet less one transform the tweepy tweets into a 2d array that will populate the csv write the csv pass in the username of the account you want to download twitter api credentials ize twitter initialize tweepy initialize a list to hold all the tweepy tweets make initial request for most recent tweets 200 is the maximum allowed count save most recent tweets save the id of the oldest tweet less one keep grabbing tweets until there are no tweets left to grab all subsequent requests use the max_id param to prevent duplicates save most recent tweets update the id of the oldest tweet less one transform the tweepy tweets into a 2d array that will populate the csv write the csv pass in the username of the account you want to download
import csv import tweepy consumer_key = "" consumer_secret = "" access_key = "" access_secret = "" def get_all_tweets(screen_name: str) -> None: auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_key, access_secret) api = tweepy.API(auth) alltweets = [] new_tweets = api.user_timeline(screen_name=screen_name, count=200) alltweets.extend(new_tweets) oldest = alltweets[-1].id - 1 while len(new_tweets) > 0: print(f"getting tweets before {oldest}") new_tweets = api.user_timeline( screen_name=screen_name, count=200, max_id=oldest ) alltweets.extend(new_tweets) oldest = alltweets[-1].id - 1 print(f"...{len(alltweets)} tweets downloaded so far") outtweets = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] with open(f"new_{screen_name}_tweets.csv", "w") as f: writer = csv.writer(f) writer.writerow(["id", "created_at", "text"]) writer.writerows(outtweets) if __name__ == "__main__": get_all_tweets("FirePing32")
usrbinenv python3 can be fetched from https developers giphy comdashboard get a list of urls of gifs based on a given query usr bin env python3 can be fetched from https developers giphy com dashboard get a list of urls of gifs based on a given query
import requests giphy_api_key = "YOUR API KEY" def get_gifs(query: str, api_key: str = giphy_api_key) -> list: formatted_query = "+".join(query.split()) url = f"https://api.giphy.com/v1/gifs/search?q={formatted_query}&api_key={api_key}" gifs = requests.get(url).json()["data"] return [gif["url"] for gif in gifs] if __name__ == "__main__": print("\n".join(get_gifs("space ship")))
usrbinenv python3 may raise json decoder jsondecodeerror class instagram crawl instagram user information usage doctest failing on github actions instagramuser instagramusergithub instagramuser isverified true instagramuser biography built for developers return a dict of user information a self running doctest testinstagramuser usr bin env python3 may raise json decoder jsondecodeerror class instagram crawl instagram user information usage doctest failing on github actions instagram_user instagramuser github instagram_user is_verified true instagram_user biography built for developers return a dict of user information a self running doctest test_instagram_user test failing on github actions
from __future__ import annotations import json import requests from bs4 import BeautifulSoup from fake_useragent import UserAgent headers = {"UserAgent": UserAgent().random} def extract_user_profile(script) -> dict: data = script.contents[0] info = json.loads(data[data.find('{"config"') : -1]) return info["entry_data"]["ProfilePage"][0]["graphql"]["user"] class InstagramUser: def __init__(self, username): self.url = f"https://www.instagram.com/{username}/" self.user_data = self.get_json() def get_json(self) -> dict: html = requests.get(self.url, headers=headers).text scripts = BeautifulSoup(html, "html.parser").find_all("script") try: return extract_user_profile(scripts[4]) except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3]) def __repr__(self) -> str: return f"{self.__class__.__name__}('{self.username}')" def __str__(self) -> str: return f"{self.fullname} ({self.username}) is {self.biography}" @property def username(self) -> str: return self.user_data["username"] @property def fullname(self) -> str: return self.user_data["full_name"] @property def biography(self) -> str: return self.user_data["biography"] @property def email(self) -> str: return self.user_data["business_email"] @property def website(self) -> str: return self.user_data["external_url"] @property def number_of_followers(self) -> int: return self.user_data["edge_followed_by"]["count"] @property def number_of_followings(self) -> int: return self.user_data["edge_follow"]["count"] @property def number_of_posts(self) -> int: return self.user_data["edge_owner_to_timeline_media"]["count"] @property def profile_picture_url(self) -> str: return self.user_data["profile_pic_url_hd"] @property def is_verified(self) -> bool: return self.user_data["is_verified"] @property def is_private(self) -> bool: return self.user_data["is_private"] def test_instagram_user(username: str = "github") -> None: import os if os.environ.get("CI"): return instagram_user = InstagramUser(username) assert instagram_user.user_data assert isinstance(instagram_user.user_data, dict) assert instagram_user.username == username if username != "github": return assert instagram_user.fullname == "GitHub" assert instagram_user.biography == "Built for developers." assert instagram_user.number_of_posts > 150 assert instagram_user.number_of_followers > 120000 assert instagram_user.number_of_followings > 15 assert instagram_user.email == "[email protected]" assert instagram_user.website == "https://github.com/readme" assert instagram_user.profile_picture_url.startswith("https://instagram.") assert instagram_user.is_verified is True assert instagram_user.is_private is False if __name__ == "__main__": import doctest doctest.testmod() instagram_user = InstagramUser("github") print(instagram_user) print(f"{instagram_user.number_of_posts = }") print(f"{instagram_user.number_of_followers = }") print(f"{instagram_user.number_of_followings = }") print(f"{instagram_user.email = }") print(f"{instagram_user.website = }") print(f"{instagram_user.profile_picture_url = }") print(f"{instagram_user.is_verified = }") print(f"{instagram_user.is_private = }")
download an image from a given url by scraping the og image meta tag parameters url the url to scrape returns a message indicating the result of the operation download an image from a given url by scraping the og image meta tag parameters url the url to scrape returns a message indicating the result of the operation
from datetime import datetime import requests from bs4 import BeautifulSoup def download_image(url: str) -> str: try: response = requests.get(url) response.raise_for_status() except requests.exceptions.RequestException as e: return f"An error occurred during the HTTP request to {url}: {e!r}" soup = BeautifulSoup(response.text, "html.parser") image_meta_tag = soup.find("meta", {"property": "og:image"}) if not image_meta_tag: return "No meta tag with property 'og:image' was found." image_url = image_meta_tag.get("content") if not image_url: return f"Image URL not found in meta tag {image_meta_tag}." try: image_data = requests.get(image_url).content except requests.exceptions.RequestException as e: return f"An error occurred during the HTTP request to {image_url}: {e!r}" if not image_data: return f"Failed to download the image from {image_url}." file_name = f"{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg" with open(file_name, "wb") as out_file: out_file.write(image_data) return f"Image downloaded and saved in the file {file_name}" if __name__ == "__main__": url = input("Enter image URL: ").strip() or "https://www.instagram.com" print(f"download_image({url}): {download_image(url)}")
get the apodastronomical picture of the day data get your api key from https api nasa gov get the data of a particular query from nasa archives get the apod astronomical picture of the day data get your api key from https api nasa gov get the data of a particular query from nasa archives
import shutil import requests def get_apod_data(api_key: str, download: bool = False, path: str = ".") -> dict: url = "https://api.nasa.gov/planetary/apod" return requests.get(url, params={"api_key": api_key}).json() def save_apod(api_key: str, path: str = ".") -> dict: apod_data = get_apod_data(api_key) img_url = apod_data["url"] img_name = img_url.split("/")[-1] response = requests.get(img_url, stream=True) with open(f"{path}/{img_name}", "wb+") as img_file: shutil.copyfileobj(response.raw, img_file) del response return apod_data def get_archive_data(query: str) -> dict: url = "https://images-api.nasa.gov/search" return requests.get(url, params={"q": query}).json() if __name__ == "__main__": print(save_apod("YOUR API KEY")) apollo_2011_items = get_archive_data("apollo 2011")["collection"]["items"] print(apollo_2011_items[0]["data"][0]["description"])
saves the image of anime character returns the title description and image title of a random anime character saves the image of anime character returns the title description and image title of a random anime character
import os import requests from bs4 import BeautifulSoup from fake_useragent import UserAgent headers = {"UserAgent": UserAgent().random} URL = "https://www.mywaifulist.moe/random" def save_image(image_url: str, image_title: str) -> None: image = requests.get(image_url, headers=headers) with open(image_title, "wb") as file: file.write(image.content) def random_anime_character() -> tuple[str, str, str]: soup = BeautifulSoup(requests.get(URL, headers=headers).text, "html.parser") title = soup.find("meta", attrs={"property": "og:title"}).attrs["content"] image_url = soup.find("meta", attrs={"property": "og:image"}).attrs["content"] description = soup.find("p", id="description").get_text() _, image_extension = os.path.splitext(os.path.basename(image_url)) image_title = title.strip().replace(" ", "_") image_title = f"{image_title}{image_extension}" save_image(image_url, image_title) return (title, description, image_title) if __name__ == "__main__": title, desc, image_title = random_anime_character() print(f"{title}\n\n{desc}\n\nImage saved : {image_title}")