Python
/
Applications
- 1 Language 9
-
Hello World
-
Variables
-
Functions
-
Conditional
-
Operators
-
While
-
Turtle
-
Script Mode
-
Debugging
- 2 Strings 6
-
Slice
-
Raw Strings
-
Regex
-
Validation
-
Config
-
Escape
- 3 Collections 5
-
Lists
-
Dictionaries
-
Efficiency
-
Tuples
-
References
- 4 Functions 5
-
Recursion
-
Factorial
-
Modulus
-
Reassignment
-
Approximate
- 5 Storage 8
-
Files
-
Databases
-
Pipes
-
With open
-
Shelve
-
Zip
-
Csv
-
Json
- 6 Class 4
-
Definition
-
Attributes
-
Functional
-
Methods
- 7 Goodies 5
-
Conditional Expression
-
List Comprehension
-
Generator
-
Named Tuple
-
Modules
- 8 Applications 5
-
Pythagora
-
Palindrome
-
Binary Search
-
Conway Game
-
Coin Flip
- 9 Scheduler 4
-
Time
-
Multithreading
-
Subprocess
-
Logging
- 10 Packages 2
-
Clipboard
-
Ocr
/
Pythagora
➟
➟
Last update: 09-12-2021
Pythagora (A)
p104 ! The goal of incremental development is to avoid long debugging. By Pythagorean Theorem, the distance betwee 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 github Applications