将一个整数转换为包含一个整数的列表



前传。
你知道fizz-buzz task吗?我使用它进行异常训练和pytest测试。我想:为什么只有两个参数?只需稍加修改,我就可以使用分隔符列表和消息列表。通常情况下,函数取number_for_checklist_of_dividerlist_of_messages。在现实生活中肯定有很多问题,但现在我们忽略了它。如果用户只取一个除数该怎么办?整数。
转换为列表!

divider = 3
if type(divider) == int:
tempo = []
tempo.append(divider)
divider = tempo
print(divider)

这是良好的实践吗?如何做得更优雅?或者如何在没有隐式类型转换的情况下解决问题?


这是该功能的完整实现。在未来,它将被转化为阶级。但在未来。

def perfect_oz_checker(num_for_check, dividers_array, message_array=['Fizz', 'Buzz', 'Juzz']) -> str:
"""
Check the number and if it multiplies one of dividers return message like “Fizz”...
Function takes:
:param num_for_check: expected positive integer
:param dividers_array: expected integer or array of integers
:param message_array:  expected array of strings whose length is equal 
to the length of the array of divisors
:return: string
"""
result_of_checking = ''
if type(dividers_array) not in [int, list]:
raise TypeError('You must use integer or list of integers')
'''We need more Error handlers definitely'''
if type(dividers_array) == int:
tempo = []
tempo.append(dividers_array)
dividers_array = tempo
for i in range(len(dividers_array)):
result_of_checking += message_array[i] * (not num_for_check % dividers_array[i])
if result_of_checking == '':
result_of_checking = str(num_for_check)
return result_of_checking

主要问题解答:
dividers_array = [dividers_array]
感谢@Barmar


代码再完善一步

def perfect_oz_checker(num_for_check, dividers_array, message_array=['Fizz', 'Buzz', 'Juzz']) -> str:
"""
Check the number and if it multiplies one of dividers return message like “Fizz”...
Function takes:
:param num_for_check: expected positive integer
:param dividers_array: expected integer or array of integers
:param message_array:  expected array of strings whose length is equal 
to the length of the array of divisors
:return: string
"""
result_of_checking = ''
if not isinstance(dividers_array, (int, list)):
raise TypeError('You must use integer or list of integers')
'''We need more Error handlers definitely'''

'''I love Python'''
if type(dividers_array) == int:
dividers_array = [dividers_array]

for i in range(len(dividers_array)):
result_of_checking += message_array[i] * (not num_for_check % dividers_array[i])
if result_of_checking == '':
result_of_checking = str(num_for_check)
return result_of_checking

最新更新