输入用逗号分隔的多个数,输出最小绝对值python
时间: 2024-09-10 21:07:44 浏览: 62
python小白实验练习题实验二题目
要实现输入用逗号分隔的多个数并输出最小绝对值的Python程序,你可以按照以下步骤操作:
**方法一:逐个元素求绝对值并比较**
```python
def min_abs_value(numbers):
# Split the input string by comma and convert to a list of floats
num_list = [float(num.strip()) for num in input().split(",")]
# Initialize min_abs with a large number (正无穷)
min_abs = float('inf')
# Iterate over the numbers, calculate their absolute values, and update min_abs if necessary
for num in num_list:
abs_num = abs(num)
if abs_num < min_abs:
min_abs = abs_num
return min_abs
# 示例输入: "-1, 3, 1"
min_val = min_abs_value("-1, 3, 1")
print(min_val) # 输出: 1.0
```
**方法二:使用内置`sorted`函数结合`abs`函数**
```python
def min_abs_value_bis(numbers):
# Convert the input string to a list of floats after splitting by comma
num_list = [float(num.strip()) for num in input().split(",")]
# Return the smallest absolute value from the sorted list
return min(sorted([abs(num) for num in num_list]))
# 示例输入同上
min_val_bis = min_abs_value_bis("-1, 3, 1")
print(min_val_bis) # 输出: 1.0
```
阅读全文