还是不太适应发博客……出去浪了一天就什么都不记得了囧rz
今天来更新第三篇。感觉都不知道应该写些什么了,于是就写几个弱弱的小函数开心一下吧~
首先是经典的辗转相除法:
def gcd(x, y):
if(x%y == 0):
return y
return gcd(y, x%y)
x = int(input("Please input a num\n>"))
y = int(input("Please input another num\n>"))
g = gcd(x,y)
print("最大公约数" + str(g))
print("最小公倍数" + str(x*y//g))
在这里提出一个提示。由于当年写下这段代码的时候对python还不怎么了解,但是写了这么多以后了解应该单独设立main函数,如下:
def gcd(x, y):
if(x%y == 0):
return y
return gcd(y, x%y)
def main():
x = int(input("Please input a num\n>"))
y = int(input("Please input another num\n>"))
g = gcd(x,y)
print("最大公约数" + str(g))
print("最小公倍数" + str(x*y//g))
if __name__ == '__main__':
main()
希望和我一样的新手注意一下这个小问题。
一下的代码可能存在这样的问题,就懒得改了Orz
下面是计算斐波那契数列:
Fibonacci = []
def getFibonacci(n):
if len(Fibonacci) <= n:
temp = getFibonacci(n-1) + getFibonacci(n-2)
Fibonacci.append(temp)
return Fibonacci[n]
if __name__ == '__main__':
Fibonacci.append(0)
Fibonacci.append(1)
Fibonacci.append(1)
num = int(input("Please input an number:\n>"))
print(str(getFibonacci(num)))
话说在现阶段以笔者的水平模拟一个数组还是蛮蛋疼的囧rz
判断是否是质数:
def isPrime(n):
if n == 2:
return True
elif n < 2:
return False
for i in range(2, n):
if n/i == n//i:
return False
return True
if __name__ == '__main__':
num = int(input("Please enter a number:\n>"))
print("Your number is " + str(num))
print(str(isPrime(num)))
以及求因数:
def getFactors(n):
factors = []
for i in range(1,n+1):
if n/i == n//i:
factors.append(i)
return factors
if __name__ == '__main__':
num = int(input("Please enter a number:\n>"))
print(getFactors(num))
无话
格式化输出美元金额(四舍五入,加逗号):
class moneyFmt:
def __init__(self, data = '0'):
try:
self.money = float(data)
if self.money < 0:
self.minus_sigh = True
self.money *= (-1)
else:
self.minus_sigh = False
#approximate
self.money = (int(self.money*100))/100
except TypeError:
print("Initialize Error")
self.money = 0
def update(self, data):
try:
temp = float(data)
self.money = temp
except TypeError:
print("Update error!")
def __str__(self):
#approximate
#self.money = (int(self.money*100))/100
f = self.money - int(self.money)
inte = []
money_copy = int(self.money)
while money_copy != 0:
inte.append(money_copy % 1000)
money_copy //= 1000
inte[0] += f
string = '$'
if self.minus_sigh:
string += '-'
flag = False
while (len(inte) > 0):
if(flag):
string += ','
string += str(inte.pop())
flag = True
if string[-3] != '.':
string += '0'
return string
def __nonzero__(self):
if self.money == 0:
return False
return True
def display(self):
print(str(self))
def main():
while True:
s = input("Please enter a number:\n>>>")
S = moneyFmt(s)
S.display()
if __name__ == '__main__':
main()
首先笔者在这段代码中没有写退出的判断,干脆一个异常拉倒,这样是不对滴~#但还是懒得改了Orz
还有就是这段代码笔者都觉得臃肿,有什么更好的改进办法欢迎指点~~~
就这样慢慢更下去吧,希望能够记录笔者的进步(~ ̄▽ ̄)~*