Как реорганизовать эту функцию, чтобы уменьшить проблему когнитивной сложности для использования нескольких операторов if-elif-else в python?
Мой вопрос о том, как реорганизовать условия if-elif-else в приведенном ниже коде.
Часть кода была изменена из-за новой реализации. Здесь V, X, Y - числа. Этот код предназначен для генерации случайных строк.
def get_uid(type, key):
if type == 'orange_fruit':
if key == 'juice':
uid = 'zofj' + uuidV().hex[:X]
elif key == 'salad':
uid = 'zofs' + uuidV().hex[:X]
else:
uid = 'zofx' + uuidV().hex[:X]
return uid
elif type == 'grape':
if key == 'juice':
uid = 'zzgj' + uuidV().hex[:X]
elif key == 'salad':
uid = 'zzgs' + uuidV().hex[:X]
else:
uid = 'zzgx' + uuidV().hex[:X]
return uid
elif type == 'kiwi_healthy':
if key == 'juice':
uid = 'zkij' + uuidV().hex[:X]
elif key == 'salad':
uid = 'zkis' + uuidV().hex[:X]
else:
uid = 'zkix' + uuidV().hex[:X]
return uid
elif type == 'anar_tasty':
if key == 'juice':
uid = 'zatj' + uuidV().hex[:X]
elif key == 'salad':
uid = 'zats' + uuidV().hex[:X]
else:
uid = 'yx' + uuidV().hex[:X]
return uid
elif type == 'apple':
if key == 'juice':
uid = 'zppj' + uuidV().hex[:X]
elif key == 'salad':
uid = 'zpps' + uuidV().hex[:X]
else:
uid = 'zppx' + uuidV().hex[:X]
return uid
elif type == 'cherry':
if key == 'juice':
uid = 'zchj' + uuidV().hex[:X]
elif key == 'salad':
uid = 'zchs' + uuidV().hex[:X]
else:
uid = 'zchx' + uuidV().hex[:X]
return uid
return uuidV().hex[:Y]
Заранее спасибо.
2 ответа
Ну а по простоте...
def get_uid(my_env, my_type):
i = my_env[-1]
t = type[0:2]
uid = f'z{t}t{i}z' + uuid4().hex[:6]
return uid
Кстати, я не могу понять условие для последнего оператора возврата. Вы можете назначить None для my_env и my_type, и если кто-то None вернет его:
def get_uid(my_env=None, my_type=None):
if my_env == None or my_type == None:
return uuid4().hex[:18]
else:
i = my_env[-1]
t = type[0:2]
uid = f'z{t}t{i}z' + uuid4().hex[:6]
return uid
Я предполагаю, что вы по ошибке поставили 3 в zkit3z. здесь должен быть zkitnz. Если я прав, то следующий код выполняет те же функции
def get_uid(type, env):
if type in ["apple", "grape", "kiwi"]:
if env in ["test1", "test2"]:
uid = "z"+ type[:2]+ "t"+ env[-1]+"z" + uuid4().hex[:x]
else:
uid = "z" + type[:2] + "tnz" + uuid4().hex[:x]
return uid
return uuid4().hex[:xx]
если 3 должно быть в zkit3z, то должен выполняться следующий код
def get_uid(type, env):
if type in ["apple", "grape", "kiwi"]:
if env in ["test1", "test2"]:
uid = "z"+ type[:2]+ "t"+ env[-1]+"z" + uuid4().hex[:x]
else:
if type != "kiwi":
uid = "z" + type[:2] + "tnz" + uuid4().hex[:x]
else:
uid = "z" + type[:2] + "t3z" + uuid4().hex[:x]
return uid
return uuid4().hex[:xx]