I am a beginner at programing and I'm trying to figure out how list methods work. I wrote a tiny string scrambler and decoder for exercise purposes.
import random
sliced = []
keyholder = []
scrambled = []
decoded = []
def string_slicer(string):
i = 0
while i < len(string):
sliced.append(string[i])
i += 1
def string_scrambler(string):
string = string_slicer(string)
a = 0
while len(scrambled) != len(sliced):
value = len(sliced) - 1
key = random.randint(0,value)
if key in keyholder:
continue
else:
scrambled.append(sliced[key])
keyholder.append(key)
continue
def string_decoder():
x = 0
for item in keyholder:
decoded.insert(keyholder[x], scrambled[x])
x += 1
string_scrambler('merhaba')
string_decoder()
print sliced
print keyholder
print scrambled
print decoded
When i'm testing it the string_scrambler() works fine but the string_decoder() gives random results. Here are some examples:
C:\Python27\Exercises>python scrambler.py
['m', 'e', 'r', 'h', 'a', 'b', 'a']
[2, 6, 0, 1, 3, 5, 4]
['r', 'a', 'm', 'e', 'h', 'b', 'a']
['m', 'e', 'r', 'h', 'a', 'a', 'b']
C:\Python27\Exercises>python scrambler.py
['m', 'e', 'r', 'h', 'a', 'b', 'a']
[4, 5, 1, 0, 3, 2, 6]
['a', 'b', 'e', 'm', 'h', 'r', 'a']
['m', 'a', 'r', 'e', 'h', 'b', 'a']
C:\Python27\Exercises>python scrambler.py
['m', 'e', 'r', 'h', 'a', 'b', 'a']
[1, 4, 5, 2, 3, 0, 6]
['e', 'a', 'b', 'r', 'h', 'm', 'a']
['m', 'e', 'a', 'r', 'h', 'b', 'a']
I think trying to add some items in an empty list with .insert method may cause this problem. But i can't figure out exactly why.