我想在马尼姆的数列上添加我自己的数字,现在我所能做的就是给出一个数字范围,但我想添加像PI, squareroot,虚数这样的数字,就像我自己的数字列表,而不是由函数生成的范围。正确的做法是什么?请帮助。
这是我的代码:
class NumbersClass(Scene):
def construct(self):
num_line = NumberLine(x_range=[-3, 3, 0.5],
unit_size=2,
color=ORANGE,
include_numbers=True,
decimal_number_config={
"num_decimal_places": 1},
)
self.play(DrawBorderThenFill(num_line), run_time=2)
self.wait(duration=1)
我知道你的问题是在输入上工作。因此,您可以将它们作为字符串输入,并将其转换为特定类型,如:
import math
def get_sqrt(input_number: str) -> float:
"""Return square root of input_number if in the form "sqrt(number)" (e.g. sqrt(2))"""
value = float(input_number[input_number.find("(") + 1 : input_number.find(")")])
return math.sqrt(value)
def get_pi(input_number: str) -> float:
"""Return pi value if input_number in the form "pi" """
return math.pi
def get_division(input_number: str) -> float:
"""Return division value if input_number in the form "a/b" (e.g. 2/5)"""
value = float(input_number.split("/")[0]) / float(input_number.split("/")[1])
return value
def get_complex(input_number: str) -> complex:
"""Return complex value of input_number in the form "a+bj" (e.g. 1+2j)"""
return complex(input_number)
def get_correct_number(input_number: str):
str_patterns = {"sqrt": get_sqrt, "pi": get_pi, "/": get_division, "j": get_complex}
for str_pattern, func in str_patterns.items():
if str_pattern in input_number:
return func(input_number)
return float(input_number)
if __name__ == "__main__":
# If you want to fill your list of values
my_own_list = ["sqrt(2)", "pi", "1/2", "0", "4", "-4"]
my_values = []
print("Number -> Type")
for input_number in my_own_list:
number = get_correct_number(input_number)
print(number, "->", type(number))
my_values.append(number)
print("nList of converted values: ")
print(my_values)
# If you want to input values manually
dont_stop = True
my_values = []
print("nManual inputn")
while dont_stop:
input_number = input("Enter your number: ")
if input_number:
number = get_correct_number(input_number)
print("Number -> Type")
print(number, "->", type(number))
my_values.append(number)
else:
dont_stop = False
print("nList of converted values: ")
print(my_values)
这里有一个终端输入/输出的例子:
Number -> Type
1.4142135623730951 -> <class 'float'>
3.141592653589793 -> <class 'float'>
0.5 -> <class 'float'>
0.0 -> <class 'float'>
4.0 -> <class 'float'>
-4.0 -> <class 'float'>
List of converted values:
[1.4142135623730951, 3.141592653589793, 0.5, 0.0, 4.0, -4.0]
Manual input
Enter your number: 1
Number -> Type
1.0 -> <class 'float'>
Enter your number: 1/4
Number -> Type
0.25 -> <class 'float'>
Enter your number: sqrt(3)
Number -> Type
1.7320508075688772 -> <class 'float'>
Enter your number: 3+5j
Number -> Type
(3+5j) -> <class 'complex'>
Enter your number:
List of converted values:
[1.0, 0.25, 1.7320508075688772, (3+5j)]
我希望这对你有帮助!
注。:我没有使用任何正则表达式来评估空间(例如:'2+ 5j'后面加空格会导致异常),两者都没有试图覆盖常见的raise异常。