python: init shuffle algorithm

pull/2/head
sundowndev 2019-09-26 10:12:55 +02:00
parent eb02933d2e
commit b01b4cbe79
3 changed files with 47 additions and 0 deletions

14
python/shuffle/README.md Normal file
View File

@ -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)

Binary file not shown.

View File

@ -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()