def makeDict(text : str, k : int) -> Dict[str,List[str]]:
i = 0
Dict = {}
while i < len(text):
if (i+k) < len(text):
# the following if statement is used to determine if the k-long characters are already in the dictionary
if (text[i:i+k] in Dict):
Dict[text[i:i+k]] = Dict[text[i:i+k]] + text[i+k]
elif (text[i:i+k] not in Dict): # this will ensure that every set of k characters is added to the dictionary
Dict[text[i:i+k]] = text[i+k]
elif (i+k) >= len(text): # this will stop the "string out of range" error
pass
i += 1
print(Dict)
def randomWriter(tex : str, k : int, outputLen : int) -> str:
#makeDict(text,k)
newStr = ""
rChoice = r.choice(list(Dict.keys()))
newStr = newStr + rChoice
x = 0
while x < len(text):
#print(newStr) # delete this later, used to track progression
CharSet = newStr[x:x+k] # used to gather the last k characters in the new string
if (CharSet in Dict):
rChoice = r.choice(Dict[str(CharSet)]) # determines next character based off the last ones in the new string
else:
rChoice = r.choice(list(Dict.keys()))
rChoice = " " + rChoice
newStr = newStr + rChoice
x += 1
return newStr
The above code takes a string, creates a dictionary, and then randomly generates a new string based on the dictionary. My problem is that when I have the two functions combined (with all the code in makeDict()) it works perfectly fine, but when separated into two functions (as shown above) I get TypeError: descriptor 'keys' of 'dict' object needs an argument I just need help understanding why this is happening and how to fix it.
Aucun commentaire:
Enregistrer un commentaire