Positional arguments of variable size
Let's practice positional arguments of variable size. Your task is to define the function sort_types(). It takes a variable number of positional arguments and checks if each argument is a number or a string. The checked item is inserted afterwards either in the nums or strings list. Eventually, the function returns a tuple containing these lists.
Use the Python's built-in isinstance() function to check if an object is of a certain type (e.g. isinstance(1, int) returns True) or one of the types (e.g. isinstance(5.65, (int, str)) returns False).
Types to use in this task are int, float, and str.
本练习是课程的一部分
Practicing Coding Interview Questions in Python
练习说明
- Define the function with an arbitrary number of arguments.
- Check if
argis a number and add it tonumsif necessary. - Check if
argis a string and add it tostringsif necessary.
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Define the function with an arbitrary number of arguments
def sort_types(____):
nums, strings = [], []
for arg in args:
# Check if 'arg' is a number and add it to 'nums'
if ____:
nums.____
# Check if 'arg' is a string and add it to 'strings'
elif ____:
strings.____
return (nums, strings)
print(sort_types(1.57, 'car', 'hat', 4, 5, 'tree', 0.89))