我正在研究python中处理有理数的问题,它有一个简化它的方法.例如12/8
给出3/2
.我已经完成了这个问题,并得到了正确的答案,但我已经找到了分子和分母的gcd.可能有人帮助使用一些内置的特殊python功能或函数,模块或python独有的任何东西,就像你说的"Pythonic方式!"
是否有这样的方法或任何测试案例应该包括在内以涵盖所有可能性?
这是我的代码:
class RationalNumber:
def __init__(self, n, d=1):
self.n=n
self.d=d
'''def gcd(self, a, b): // I have taken out gcd by two methods: recursion and while loop
if b>a:
t=a
a=b
b=t
while a%b != 0:
r=a%b
a=b
b=r
return b
'''
def gcd(self, a, b):
if a%b==0:
return b
else:
return self.gcd(b, a%b)
def simplify(self):
x=self.gcd(self.n, self.d)
self.n=self.n/x
self.d=self.d/x
return RationalNumber(self.n, self.d)
def __str__(self):
print "%s/%s"%(self.n, self.d)
r1 = RationalNumber(12,8)
print r1.simplify()
Run Code Online (Sandbox Code Playgroud)
当我运行程序时,它会给出答案并给出错误:
Traceback …
Run Code Online (Sandbox Code Playgroud) 我有一个看起来像这样的矢量:
vector<int> A = {0, 1, 1, 0, 0, 1, 0, 1};
Run Code Online (Sandbox Code Playgroud)
我想从非零值中选择一个随机索引A
.使用这个例子A
,我想从数组中随机选择一个元素{1,2,5,7}
.
目前我通过创建另一个数组来做到这一点
vector<int> b;
for(int i=0;i<A.size();i++)
if(A[i])
b.push_back(i);
Run Code Online (Sandbox Code Playgroud)
一旦b
创建,我使用这个答案找到索引:
有没有更像STL(或C++ 11)的方法,也许是一个不创建中间数组的方法?在这个例子A
中很小,但在我的生产代码中,这个选择过程是在内循环中,A是非静态的,数千个元素是长的.
问题是编写一个程序,该程序从终端输入一个键入的整数,并以英语提取并显示整数的每个数字.所以,如果用户输入932,程序应该显示'九三二'..
我的算法是首先反转数字,使932变为239.现在我使用mod运算符和print来提取最后一位数字.接下来我将数字除以10,然后我再次提取最后一位数字,依此类推......
是否有其他算法(更短,更有效)?
可以提取整数的最后一位数.是否可以提取第一个数字等等?
我不是一个非常有经验的程序员,但我只是用Python编写这个来尝试查找e
,使用的定义e
是1/0的总和!+ 1/1!+ 1/2!等等...
我遇到的问题是def factorial
不输出整数.我意识到它不会给它如何写,但我不知道我怎么能做到.total
是我想要输出的int def factorial
.
e = 0
def factorial(m):
n = m - 1
total = 1
if n > 0:
total = m
while n > 0:
total = total * n
n = n - 1
for w in range(0,100):
s = factorial(w)
e = e + ( 1 / s )
print(e)
Run Code Online (Sandbox Code Playgroud) 我有一个正则表达式,在标签中搜索"href"属性,但它目前效果不佳:
<a[^>]* href="([^"]*)"
Run Code Online (Sandbox Code Playgroud)
它从中发现:
<a href="http://something" title="Development of the Python language and website">Core Development</a>
Run Code Online (Sandbox Code Playgroud)
这一行:
<a href="http://something"
Run Code Online (Sandbox Code Playgroud)
但我只需要找到:
http://something
Run Code Online (Sandbox Code Playgroud)