From 68b980b5ee224387f29f25c281bf81f715536991 Mon Sep 17 00:00:00 2001 From: beingadityak Date: Tue, 2 Oct 2018 11:07:24 +0530 Subject: [PATCH 1/3] Adding Anagram Search --- strings/anagram_search.py | 42 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 strings/anagram_search.py diff --git a/strings/anagram_search.py b/strings/anagram_search.py new file mode 100644 index 0000000..3f4a297 --- /dev/null +++ b/strings/anagram_search.py @@ -0,0 +1,42 @@ +""" +Pythonic Implementation of Anagram search +""" + +__author__ = "Aditya Krishnakumar" + +import collections + +# remove whitespaces +def remove_whitespace(string): + return ''.join(string.split()) + +""" + Checks if two strings are anagrams of each other, ignoring any whitespace. + + First remove any whitespace and lower all characters of both strings. + Then create dictionaries of the counts of every character in each string. + As well as keep a set of all characters used in both strings. + Check to ensure every unique character are used in both strings the + same number of times. +""" + +def is_anagram(string1, string2): + charCount1 = collections.Counter(remove_whitespace(string1.lower())) + charCount2 = collections.Counter(remove_whitespace(string2.lower())) + + allChars = set(charCount1.keys()) + allChars = allChars.union(charCount2.keys()) + + for c in allChars: + if (charCount1[c] != charCount2[c]): + return False + + return True + +# Dry runs + +assert is_anagram("anagram", "not a gram") == False +assert is_anagram("anagram", "na a marg") == True +assert is_anagram("William Shakespeare", "I am \t a weakish speller") == True +assert is_anagram("Madam Curie", "Radium came") == True +assert is_anagram("notagram", "notaflam") == False \ No newline at end of file From d3d6613cf9c4762b0479d2c8ca59a8e0fe0768c4 Mon Sep 17 00:00:00 2001 From: beingadityak Date: Tue, 2 Oct 2018 14:27:05 +0530 Subject: [PATCH 2/3] Adding 4 String algorithms --- strings/anagram_search.py | 4 ++- strings/morse_code.py | 69 +++++++++++++++++++++++++++++++++++++ strings/password_checker.py | 29 ++++++++++++++++ strings/rabin_karp.py | 46 +++++++++++++++++++++++++ 4 files changed, 147 insertions(+), 1 deletion(-) create mode 100644 strings/morse_code.py create mode 100644 strings/password_checker.py create mode 100644 strings/rabin_karp.py diff --git a/strings/anagram_search.py b/strings/anagram_search.py index 3f4a297..fb902d2 100644 --- a/strings/anagram_search.py +++ b/strings/anagram_search.py @@ -1,3 +1,5 @@ +#!/usr/bin/env python3 + """ Pythonic Implementation of Anagram search """ @@ -39,4 +41,4 @@ def is_anagram(string1, string2): assert is_anagram("anagram", "na a marg") == True assert is_anagram("William Shakespeare", "I am \t a weakish speller") == True assert is_anagram("Madam Curie", "Radium came") == True -assert is_anagram("notagram", "notaflam") == False \ No newline at end of file +assert is_anagramg("notagram", "notaflam") == False \ No newline at end of file diff --git a/strings/morse_code.py b/strings/morse_code.py new file mode 100644 index 0000000..4a48462 --- /dev/null +++ b/strings/morse_code.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python +""" +Pythonic Implementation of Morse Code encoding +""" + +__author__ = "Aditya Krishnakumar" + + +# The alphabet dictionary for morse codes +morseAlphabet = { + "A": ".-", + "B": "-...", + "C": "-.-.", + "D": "-..", + "E": ".", + "F": "..-.", + "G": "--.", + "H": "....", + "I": "..", + "J": ".---", + "K": "-.-", + "L": ".-..", + "M": "--", + "N": "-.", + "O": "---", + "P": ".--.", + "Q": "--.-", + "R": ".-.", + "S": "...", + "T": "-", + "U": "..-", + "V": "...-", + "W": ".--", + "X": "-..-", + "Y": "-.--", + "Z": "--..", + "1": ".----", + "2": "..---", + "3": "...--", + "4": "....-", + "5": ".....", + "6": "-....", + "7": "--...", + "8": "---..", + "9": "----.", + "0": "-----" +} + +# Lambda function for decoding the code to alphabet +inverseAlphabet = reduce(lambda a, b: dict(a.items() + b.items()), + [{ + morseAlphabet[k]: k + } for k in morseAlphabet.keys()], {}) + + +def encode(_text): + return ' '.join([morseAlphabet[_c.upper()] for _c in _text[:]]) + + +def decode(_text): + return ''.join([inverseAlphabet[_c] for _c in _text.split(' ')]) + +# Dry runner +def test(): + print decode(encode("TEST")) == "TEST" + + +if __name__ == "__main__": + test() \ No newline at end of file diff --git a/strings/password_checker.py b/strings/password_checker.py new file mode 100644 index 0000000..8743ea5 --- /dev/null +++ b/strings/password_checker.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python3 + +import re, pyperclip + +password = pyperclip.paste() + +eightLettersRegex = re.compile(r'\S{8,}') +oneUppercaseRegex = re.compile(r'[A-Z]') +oneNumberRegex = re.compile(r'\d') + +check = { + eightLettersRegex: 'Your password must be 8 letters', + oneUppercaseRegex: 'Your password must have at least one uppercase Letter.', + oneNumberRegex: 'Your password must have at least one number.' +} + +print('Analyzing your password.') + +count = 1 +for regex, msg in check.items(): + mo = regex.search(password) + if mo == None: + print(msg) + break + if count == len(check): + print('Good! Your password is strong enough!') + count += 1 + +print('End.') \ No newline at end of file diff --git a/strings/rabin_karp.py b/strings/rabin_karp.py new file mode 100644 index 0000000..721e890 --- /dev/null +++ b/strings/rabin_karp.py @@ -0,0 +1,46 @@ +#!/usr/local/bin/env python3 + +# Rabin Karp Algorithm in python using hash values +# d is the number of characters in input alphabet +d = 2560 + + +def search(pat, txt, q): + M = len(pat) + N = len(txt) + i = 0 + j = 0 + + p = 0 + t = 0 + h = 1 + + for i in range(M - 1): + h = (h * d) % q + + for i in range(M): + p = (d * p + ord(pat[i])) % q + t = (d * t + ord(txt[i])) % q + + for i in range(N - M + 1): + if p == t: + for j in range(M): + if txt[i + j] != pat[j]: + break + + j += 1 + if j == M: + print("Pattern found at index " + str(i)) + + if i < N - M: + t = (d * (t - ord(txt[i]) * h) + ord(txt[i + M])) % q + if t < 0: + t = t + q + + +# Driver program to test the above function +txt = "ALL WORLDS IS A STAGE AND ALL OF US ARE A PART OF THE PLAY" +pat = "ALL" + +q = 101 # A prime number +search(pat, txt, q) \ No newline at end of file From 0bd27e83fd9552996170e48e8bc0675fe417aada Mon Sep 17 00:00:00 2001 From: beingadityak Date: Tue, 2 Oct 2018 14:50:26 +0530 Subject: [PATCH 3/3] Adding 3 Greedy Algorithms in Python --- greedy/coin_change.py | 37 +++++++++++++++++++++ greedy/dijkstra_algo.py | 37 +++++++++++++++++++++ greedy/fractional_knapsack.py | 61 +++++++++++++++++++++++++++++++++++ 3 files changed, 135 insertions(+) create mode 100644 greedy/coin_change.py create mode 100644 greedy/dijkstra_algo.py create mode 100644 greedy/fractional_knapsack.py diff --git a/greedy/coin_change.py b/greedy/coin_change.py new file mode 100644 index 0000000..996ff92 --- /dev/null +++ b/greedy/coin_change.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python3 + +""" +Coin Change implementation in Python (Greedy Method) +""" + +__author__ = "Aditya Krishnakumar" + +def minimum_coins(value, denominations): + result = [] + # Assuming denominations is sorted in descendig order + for cur_denom in denominations: + while cur_denom <= value: + result.append(cur_denom) + value = value - cur_denom + + return result + +# Testing +def test(): + scenarios = [[100, [50, 25, 10, 5, 1], [50, 50]], + [101, [50, 25, 10, 5, 1], [50, 50, 1]], + [77, [50, 25, 10, 5, 1], [50, 25, 1, 1]], + [38, [50, 25, 10, 5, 1], [25, 10, 1, 1, 1]], + [17, [50, 25, 10, 5, 1], [10, 5, 1, 1]], + [3, [50, 25, 10, 5, 1], [1, 1, 1]], + [191, [100, 50, 25, 10, 5, 1], [100, 50, 25, 10, 5, 1]]] + + for scenario in scenarios: + actual = minimum_coins(scenario[0], scenario[1]) + if actual != scenario[2]: + message = "Test Failed: Value: {}, Denominations: {}, Expected Result: {}, Actual Result: {}".format(scenario[0], scenario[1], scenario[2], actual) + print message + + return None + +test() \ No newline at end of file diff --git a/greedy/dijkstra_algo.py b/greedy/dijkstra_algo.py new file mode 100644 index 0000000..3faac0f --- /dev/null +++ b/greedy/dijkstra_algo.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python3 + +""" +Dijkstra's Algorithm implementation in Python +""" + +__author__ = "Aditya Krishnakumar" + +def dijkstra(graph, source): + + vertices, edges = graph + dist = dict() + previous = dict() + + for vertex in vertices: + dist[vertex] = float("inf") + previous[vertex] = None + + dist[source] = 0 + Q = set(vertices) + + while len(Q) > 0: + u = minimum_distance(dist, Q) + print('Currently considering', u, 'with a distance of', dist[u]) + Q.remove(u) + + if dist[u] == float('inf'): + break + + n = get_neighbours(graph, u) + for vertex in n: + alt = dist[u] + dist_between(graph, u, vertex) + if alt < dist[vertex]: + dist[vertex] = alt + previous[vertex] = u + + return previous \ No newline at end of file diff --git a/greedy/fractional_knapsack.py b/greedy/fractional_knapsack.py new file mode 100644 index 0000000..c0e7f5b --- /dev/null +++ b/greedy/fractional_knapsack.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 + +""" +Implementation of Fractional Knapsack Algorithm in Python +""" + +__author__ = "Aditya Krishnakumar" + +# Item class with weight and values +class Item: + + # intialize weight and values + def __init__(self, weight=0, value=0): + + self.weight = weight + self.value = value + + return + + +def fractional_knapsack(items, W): + + # Sorting items by value /weight + sorted(items, key = lambda item: float(item.value)/float(item.weight)) + + finalValue = 0.0 + currentWeight = 0 + + + for item in items: + + if currentWeight + item.weight <= W : + # If adding Item won't overflow, add it completely + finalValue += item.value + currentWeight += item.weight + + else: + #If we can't add current Item, add a fraction of it + remaining = W - currentWeight + finalValue += item.value*(float(remaining)/float(item.weight)) + break + + return finalValue + +def main(): + + W = 50 + + items = [ + Item(10, 60), + Item(20, 100), + Item(30, 120) + ] + + print("Maximum value we can obtain -{}".format(fractional_knapsack(items, W))) + + return + +if __name__ == "__main__": + + main() pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy