From 1f1daaf1c75adbe43126e53ef1eba718ecb67029 Mon Sep 17 00:00:00 2001 From: Harshit Agarwal <43147421+9harshit@users.noreply.github.com> Date: Mon, 4 Apr 2022 00:36:32 -0300 Subject: [PATCH] feat: add strings/ngram algorithm (#6074) * feat: added ngram algorithm * fix(test): use `math.isclose` to match floating point numbers approximately Co-authored-by: Christian Clauss Co-authored-by: Dhruv Manilawala --- arithmetic_analysis/in_static_equilibrium.py | 14 +++++++++--- strings/ngram.py | 23 ++++++++++++++++++++ 2 files changed, 34 insertions(+), 3 deletions(-) create mode 100644 strings/ngram.py diff --git a/arithmetic_analysis/in_static_equilibrium.py b/arithmetic_analysis/in_static_equilibrium.py index 2ac3e7213..ed0d1eb98 100644 --- a/arithmetic_analysis/in_static_equilibrium.py +++ b/arithmetic_analysis/in_static_equilibrium.py @@ -12,8 +12,12 @@ def polar_force( """ Resolves force along rectangular components. (force, angle) => (force_x, force_y) - >>> polar_force(10, 45) - [7.071067811865477, 7.0710678118654755] + >>> import math + >>> force = polar_force(10, 45) + >>> math.isclose(force[0], 7.071067811865477) + True + >>> math.isclose(force[1], 7.0710678118654755) + True >>> polar_force(10, 3.14, radian_mode=True) [-9.999987317275396, 0.01592652916486828] """ @@ -50,7 +54,11 @@ def in_static_equilibrium( if __name__ == "__main__": # Test to check if it works forces = array( - [polar_force(718.4, 180 - 30), polar_force(879.54, 45), polar_force(100, -90)] + [ + polar_force(718.4, 180 - 30), + polar_force(879.54, 45), + polar_force(100, -90), + ] ) location = array([[0, 0], [0, 0], [0, 0]]) diff --git a/strings/ngram.py b/strings/ngram.py new file mode 100644 index 000000000..0b13e34a4 --- /dev/null +++ b/strings/ngram.py @@ -0,0 +1,23 @@ +""" +https://en.wikipedia.org/wiki/N-gram +""" + + +def create_ngram(sentence: str, ngram_size: int) -> list[str]: + """ + 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) + [] + """ + return [sentence[i : i + ngram_size] for i in range(len(sentence) - ngram_size + 1)] + + +if __name__ == "__main__": + from doctest import testmod + + testmod()