Test :
- DRY : Don’t Repeat Yourself.
- The use of function :
- To reduce the amount of code.
- To make fixing the debug easier.
- To make easier to read.
Try :
-
Use function to act as pow(a, b) = a**b
1
2
3
4
5
6
7
8def power(x, y):
result = 1
for i in range(y):
result *= x
return result
print(power(3,5)) -
Greatest Common Divisor (gcd)
gcd(x, y) = gcd(y, x mod y)
Euclidean algorithm (辗转相除法)
for example :
| 168 | 63 | | |
| ——– | —– | —- | ——– |
| 168 | 63 | 42 | 余数0 |
| 63 | 42 | 21 | gcd = 21 |
| 263+ 42 | 42+21 | 242 | |1
2
3
4
5
6
7
8
9
10
11def gcd(x, y):
while y:
t = x%y
x = y
y = t
return x
x = int(input('Pls input an integer x:'))
y = int(input('Pls input an integer y:'))
print(gcd(x,y)) -
Turn decimal system to binary system.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16def DectoBin(dec):
temp = [ ]
result = ' '
while dec:
quo = dec % 2
dec = dec // 2
temp.append(quo)
while temp:
result += str(temp.pop())
return result
Dec = int(input('Pls input an integer:'))
print('Bin =', DectoBin(Dec))
近期评论