Python
/
Applications
- 1 Language 9
-
Hello World S
-
Variables S
-
Functions S
-
Conditional A S
-
Operators S
-
While S
-
Turtle S
-
Script Mode S
-
Debugging S
- 2 Strings 7
-
Slice S
-
Raw Strings S
-
Regex A S
-
Validation S
-
Config S
-
Security S
-
Encrypt A S
- 3 Collections 5
-
Lists S
-
Dictionaries S
-
Efficiency S
-
Tuples S
-
References S
- 4 Functions 5
-
Recursion S
-
Factorial S
-
Modulus S
-
Reassignment S
-
Approximate S
- 5 Storage 8
-
Files S
-
Databases S
-
Pipes S
-
With open S
-
Shelve A S
-
Zip S
-
Csv S
-
Json S
- 6 Class 4
-
Definition S
-
Attributes S
-
Functional S
-
Methods S
- 7 Goodies 5
-
Conditional Expression S
-
List Comprehension A S
-
Generator S
-
Named Tuple S
-
Modules S
- 8 Applications 5
-
Pythagora A S
-
Palindrome A S
-
Binary Search A S
-
Conway Game A S
-
Coin Flip A S
- 9 Scheduler 4
-
Time S
-
Multithreading A S
-
Subprocess S
-
Logging S
- 10 Packages 6
-
Clipboard A S
-
Ocr A S
-
Socket S
-
Image S
-
Virtualenv S
-
Jupyter S
S
R
Q
Python Applications Pythagora
Incremental development, avoid long debugging Pythagorean Theorem, two points distance def distance(x1, y1, x2, y2): return 0.0
Pythagora (A)
p104 The goal of incremental development is to avoid long debugging. By Pythagorean Theorem, the distance between two points is: \[d = \sqrt{(x2-x1)^2 + (y2-y1)^2} \]First step
The first step will be to define the function, with wrong answer but syntactically correct.
# Incremental development - Pythagorean Theorem
#
# d = square( (x2-x1)^2 + (y2-y1)^2 )
# First: Define the function, with wrong answer but syntactically correct
def distance(x1, y1, x2, y2):
return 0.0
assert distance(1, 2, 4, 6) == 0.0
Second
The next step is to find the differences x2-x1, y2-y1
# Incremental development - Pythagorean Theorem
#
# d = square( (x2-x1)^2 + (y2-y1)^2 )
#
# Second: Find the differences x2-x1, y2-y1
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
return 0.0
assert distance(1, 2, 4, 6) == 0.0
Third
Then we compute the sum of squares.
# Incremental development - Pythagorean Theorem
#
# d = square( (x2-x1)^2 + (y2-y1)^2 )
#
# Third: Compute the sum of squares
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
sum = dx**2 + dy**2
return 0.0
assert distance(1, 2, 4, 6) == 0.0
Forth
Finally, you can use math.sqrt() to compute the result.
# Incremental development - Pythagorean Theorem
#
# d = square( (x2-x1)^2 + (y2-y1)^2 )
#
# Third: Use math.sqrt() to compute the result
import math
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
sum = dx**2 + dy**2
return math.sqrt(sum)
d = distance(1, 2, 4, 6)
assert distance(1, 2, 4, 6) == 5.0
➥ Questions
Last update: 63 days ago