python: init shuffle algorithm
parent
eb02933d2e
commit
b01b4cbe79
|
@ -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.
|
@ -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()
|
Loading…
Reference in New Issue