import random cityList = [] usedcityList = [] intermediatedict = [] userCityInput = '' counter = 0 with open('citylist.txt','r') as fileCL: textCityList = fileCL.readlines() for textCL in textCityList: textCL = textCL.strip() cityList.append(textCL) def checkforamatch(arguserCityInput): for xcityList in cityList: if xcityList == arguserCityInput: global counter counter += 1 for xusedcityList in usedcityList: if xusedcityList == xcityList: counter = 0 return 1 counter = 0 usedcityList.append(arguserCityInput) return 0 if counter > 0: return -1 def lastleter(arguserCityInput): return arguserCityInput[-1:] def findword(letter): for xcityList in cityList: if letter == xcityList[0]: intermediatedict.append(xcityList) randomWord = random.randrange(0,(len(intermediatedict)-1)) for xusedcityList in usedcityList: if xusedcityList == cityList[randomWord]: findword(letter) else: intermediatedict.clear() usedcityList.append(cityList[randomWord]) return cityList[randomWord] while True: print('Введите город:') userCityInput = input() result = checkforamatch(userCityInput) if result == 1: print('\nГород уже был использован в Игре.') if result == 0: resultlast = lastleter(userCityInput) resultlast = findword(resultlast) print(resultlast) if result == -1: print('\nТакого города не существет.')
Решил реализовать игру города, вопрос такой, почему в функции findword не добавляется слово в промежуточный список intermediatedict?
Анонимный пользователь Изменен статус публикации
Вся проблема была в регистре букв, если кому интересно, и первую функцию можно реализовать без счетчика.
можно сделать короче
def recursive_input_city(city_dict: dict, city_last='', player=0) -> None: city = input('Player_{} Введите город: '.format(int(player))).strip().lower() # ввод города if city: # выход if city_last and city[0] != city_last[-1]: print('Город должен начинатся с последней буквы предыдущего {}"{}" -> "{}"{}'.format( city_last[:-1], city_last[-1], city[0], city[1:])) else: check = city_dict.get(city) # проверка города на существование if check: # город найден city_last = city city_dict[city] = False # пометить город использованным player = not player # сменить игрока elif check is None: print('Такого города не существет.') else: print('Город уже был использован в Игре.') recursive_input_city(city_dict, city_last, player) # рекурсия if __name__ == '__main__': with open('citylist.txt') as file: lines = filter(bool, map(str.strip, file)) # исключить пустые строки cities = {}.fromkeys(map(str.lower, lines), True) # {'aqwea': True, 'aasda': True, } recursive_input_city(cities) # старт
out:
Player_0 Введите город: qwe Такого города не существет. Player_0 Введите город: aqwea Player_1 Введите город: aqwea Город уже был использован в Игре. Player_1 Введите город: basdb Город должен наченаися с последней буквы предыдущего aqwe"a" -> "b"asdb Player_1 Введите город: aasda Player_0 Введите город: azxca Player_1 Введите город: