random.choice (dict.keys ())) работает, когда две функции объединены, но при отдельном запуске .keys вызывает ошибку - PullRequest
0 голосов
/ 05 августа 2020
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

Приведенный выше код принимает строку, создает словарь, а затем случайным образом генерирует новую строку на основе словаря. Моя проблема в том, что когда у меня объединены две функции (со всем кодом в makeDict ()), он работает отлично, но когда я разделен на две функции (как показано выше), я получаю TypeError: descriptor 'keys' of 'dict' object needs an argument Мне просто нужна помощь, чтобы понять, почему это происходит и как это исправить.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...