diff --git a/python/shuffle/README.md b/python/shuffle/README.md new file mode 100644 index 0000000..4b0a532 --- /dev/null +++ b/python/shuffle/README.md @@ -0,0 +1,14 @@ +*How to shuffle the characters in a string in JavaScript ?* + +e.g. Given "ABCDEFG", return something like "GEFBDCA". + +```js +print(shuffle("the quick brown fox jumps over the lazy dog")); +//-> "veolrm hth ke opynug tusbxq ocrad ofeizwj" + +print(shuffle("the quick brown fox jumps over the lazy dog")); +//-> "o dt hutpe u iqrxj yaenbwoolhsvmkcger ozf " +``` + +- Best performance case: O(n) +- Worst performance case: O(n log n) diff --git a/python/shuffle/__pycache__/solution.cpython-36.pyc b/python/shuffle/__pycache__/solution.cpython-36.pyc new file mode 100644 index 0000000..01b318f Binary files /dev/null and b/python/shuffle/__pycache__/solution.cpython-36.pyc differ diff --git a/python/shuffle/solution.py b/python/shuffle/solution.py new file mode 100644 index 0000000..f3bbe38 --- /dev/null +++ b/python/shuffle/solution.py @@ -0,0 +1,33 @@ +#!/usr/bin/python3 + +import math +import random +import unittest + +def shuffle(n): + arr = list(n) + + for i in range(0, len(arr)): + j = math.floor(random.random() * (1 + i)) + tmp = arr[i] + arr[i] = arr[j] + arr[j] = tmp + + return ''.join(arr) + +class TestStringMethods(unittest.TestCase): + + def test_shuffle(self): + string = 'my passphrase to shuffle' + self.assertNotEqual(shuffle(string), string) + + def test_shuffle2(self): + string = 'a' + self.assertEqual(shuffle(string), string) + + def test_shuffle3(self): + string = 'a b' + self.assertIn(shuffle(string), ['a b', 'b a', ' ba', 'ba ', 'ab ', ' ab']) + +if __name__ == '__main__': + unittest.main()