数学推导
![](https://i-blog.csdnimg.cn/blog_migrate/a823c5da385f77b9f8cd1c1398519149.jpeg)
求和公式
![S=\frac{10^{^{n+1}}-9n-10}{81}](https://latex.csdn.net/eq?S%3D%5Cfrac%7B10%5E%7B%5E%7Bn+1%7D%7D-9n-10%7D%7B81%7D)
完整代码
def parse_str_number(str_):
def remove_font_sign(ifm_, minus_number_, str__):
if isinstance(str__, str) and isinstance(minus_number_, int) and isinstance(str__, str):
cast_str_ = str(str__)
while cast_str_[0] == '+' or ifm_:
cast_str_ = cast_str_[1:len(cast_str_)]
if ifm_:
minus_number_ += 1
ifm_ = cast_str_[0] == '-'
return {'minus_number_': minus_number_, 'str__': cast_str_}
return None
if isinstance(str_, str):
cast_str = str(str_)
if not cast_str:
return None
minus_number = 0
if cast_str == "-" or cast_str == "+":
return None
removed = remove_font_sign(cast_str[0] == '-', minus_number, cast_str)
minus_number = removed.get('minus_number_')
cast_str = removed.get('str__')
while cast_str[0] == '(' and cast_str[len(cast_str) - 1] == ')':
cast_str = cast_str[1:len(cast_str) - 1]
removed = remove_font_sign(cast_str[0] == '-', minus_number, cast_str)
minus_number = removed.get('minus_number_')
cast_str = removed.get('str__')
if ((cast_str[0] == '(' and cast_str[len(cast_str) - 1] != ')') or
(cast_str[0] != '(' and cast_str[len(cast_str) - 1] == ')')):
return None
removed = remove_font_sign(cast_str[0] == '-', minus_number, cast_str)
minus_number = removed.get('minus_number_')
cast_str = removed.get('str__')
if cast_str[0] == '.':
cast_str = "0" + cast_str
split_number = cast_str.split('.', 3)
if len(split_number) > 2:
return None
for each_part in split_number:
if not each_part.isdigit():
return None
if minus_number % 2 == 1:
cast_str = "-" + cast_str
return cast_str
return None
def head_float_int_part(float_str):
if not isinstance(float_str, str):
return None
return float_str.split(".")[0]
def assert_float(num_str: str | int):
if not isinstance(num_str, str):
return False
int_part = head_float_int_part(num_str)
float_num_str = float(num_str)
if float_num_str != math.floor(float_num_str):
print("您输入了浮点数", num_str, "将按整数", int(int_part), "运算")
return int_part
def main():
input_contexts = []
info_s = ["Enter a[1, 9]:", "Enter n:"]
logic = [lambda n: n in range(1, 10), lambda n: n > 0]
for i in range(len(info_s)):
input_contexts.append("")
ic = ""
while (not ic) or (ic and not logic[i](int(ic))):
ic = parse_str_number(input(info_s[i]))
if ic:
input_contexts[i] = assert_float(ic)
break
ic = head_float_int_part(ic)
digit = input_contexts[0]
times = int(input_contexts[1])
print((10 ** (times + 1) - 9 * times - 10) // 81 * int(digit))
if __name__ == "__main__":
main()
运行结果
![](https://i-blog.csdnimg.cn/blog_migrate/137472120eb4d9c40d3fd664ff918815.png)