python递归解决高斯1+2+3....+10
本帖最后由 shiyouroc 于 2022-1-27 21:54 编辑{:5_99:} 上学的时候我们会学到高斯的1+2+3...100的问题。今天,我用python递归解决这个问题,顺便教会大家递归。看完的发回复。支持一下,淘个贴。
def f(x):
if x > 0:
return x+f(x-1)
else:
return 0
print(f(100))
{:5_91:}
求回复。{:5_105:} 你是认真的吗?
$ cat main.py
#!/usr/bin/env python
#coding=utf-8
def f(x):
if x<0:
return x+f(x-1)
else:
return 0
print(f (100))
$ ./main.py
File "/tmp/./main.py", line 5
if x<0:
^
SyntaxError: invalid character '<' (U+FF1C)
$ vim main.py
$ cat main.py
#!/usr/bin/env python
#coding=utf-8
def f(x):
if x<0:
return x+f(x-1)
else:
return 0
print(f (100))
$ ./main.py
File "/tmp/./main.py", line 6
return x+f(x-1)
^
SyntaxError: invalid character '(' (U+FF08)
$ vim main.py
$ cat main.py
#!/usr/bin/env python
#coding=utf-8
def f(x):
if x<0:
return x+f(x-1)
else:
return 0
print(f (100))
$ ./main.py
File "/tmp/./main.py", line 6
return x+f(x-1)
^
SyntaxError: invalid decimal literal
$ vim main.py
$ cat main.py
#!/usr/bin/env python
#coding=utf-8
def f(x):
if x<0:
return x+f(x-1)
else:
return 0
print(f (100))
$ ./main.py
File "/tmp/./main.py", line 10
print(f (100))
^
SyntaxError: invalid character '(' (U+FF08)
$ vim main.py
$ cat main.py
#!/usr/bin/env python
#coding=utf-8
def f(x):
if x<0:
return x+f(x-1)
else:
return 0
print(f (100))
$ ./main.py
File "/tmp/./main.py", line 10
print(f (100))
^
SyntaxError: invalid character '(' (U+FF08)
$ vim main.py
$ cat main.py
#!/usr/bin/env python
#coding=utf-8
def f(x):
if x<0:
return x+f(x-1)
else:
return 0
print(f (100))
$ ./main.py
File "/tmp/./main.py", line 10
print(f (100))
^
SyntaxError: invalid decimal literal
$ vim main.py
$ cat main.py
#!/usr/bin/env python
#coding=utf-8
def f(x):
if x<0:
return x+f(x-1)
else:
return 0
print(f (100))
$ ./main.py
File "/tmp/./main.py", line 10
print(f (100))
^
SyntaxError: invalid character ')' (U+FF09)
$ vim main.py
$ cat main.py
#!/usr/bin/env python
#coding=utf-8
def f(x):
if x<0:
return x+f(x-1)
else:
return 0
print(f (100))
$ ./main.py
0
$ ./main.py
0
$ ./main.py
0
$ 额 $ cat main.py
#!/usr/bin/env python
#coding=utf-8
def f(x):
if x>0:
return x+f(x-1)
else:
return 0
print(f (100))
$ ./main.py
5050
$ 人造人 发表于 2022-1-27 18:44
你是认真的吗?
等一下 $ cat main.py
#!/usr/bin/env python
#coding=utf-8
def f(x):
if x <= 0: return 0
return x + f(x - 1)
print(f(100))
$ ./main.py
5050
$ def f(x):
if x > 0:
return x+f(x-1)
else:
return 0
print(f(100)) 现在修复完成 感谢楼主分享,这题目好有趣,我想试试 C++ 语言的:
C++#include <iostream>
int main()
{
auto f = [](int x) {return (1 + x) * (x / 2); };
std::cout << f(100) << std::endl;
return 0;
} {:5_95:} {:5_91:}
页:
[1]