Simple Programs Flashcards
Week 2 of Intro to computer science and programming using Python
1
Q
Strings
A
- A sequence of case sensitive characters
- Can compare strings with ==, etc.
- len() is a function to retrieve the lenght of the string
- square brackets used to perform indexing
2
Q
More on strings
A
- Can slice strings using [start:stop:step]
- Strings are “immutable” - cannot be modified
3
Q
Approximate solutions
A
- can’t guarantee exact answer
- start with exhaustive enumeration
- take small steps to generate guesses in order
- check to see if close enough
4
Q
Approximate solutions - continued
A
- Good enough solution
- Start with a guess and increment by some small value
- Use small epsilon
(decreasing increment size -> slower program)
(increasing epsilon -> less accurate answer)
5
Q
Bisection search
A
- Radically reduces computation time - being smart about generating guesses is important.
- Works well on problems with ‘ordering’ property, value of function being solved varies monotonically with input value.
6
Q
Floats
A
- Floats approximate real numbers
- Internally computers represents numbers in binary
7
Q
Decimal number
A
302 = 310n2 + 010n1 + 2*10n0
8
Q
Binary number
A
10011 = 12n4 + 02n3 + 02n2 + 12n1 + 1*2n0
9
Q
Convert decimal integer to binary
A
- take remainder relative to 2 (x%2) of number, that gives us the last binary bit
- divide x by 2 (x//2), all the bits get shifted right
- keep doing successive divisions, now remainder gets next bit and so on
- then convert to binary form
10
Q
Fractions
A
Multiple by a power of 2 big enough to convert into a whole number. Can convert to binary and then divide by the same power of 2.
- 0.375 * (2**3 = 3 (decimal)
- convert 3 to binary (now 11)
- divide by 2**3 (shift right) to get 0.011 (binary)
11
Q
Implications
A
- if no integer p such that x*(2**p) is a whole number, then internal representation is always approximation
- Suggest testing equality of floats is not exact
Use abs(x-y) < some small number, rather than x == y - print(0.1) returns 0.1 because Python designers set it up this way to automatically round.
12
Q
Newton-Raphson - definition
A
General approximation algorithm to find roots of polynomial in one variable
13
Q
Newton-Raphson
A
- Simple case cxn2 + k
- First derivative 2cx
- So if polynomial is xn2 + k, then derivative is 2x
- Newton-Raphson says given a guess g for root, a better guess is: g-(gn2 -k)/2g
14
Q
Good Programming
A
- more code not necessarily a good thing
- measure good programmers by the amount of functionality
- Mechanism to achieve decomposition and abstraction
15
Q
Decomposition
A
Break problems into different, self-contained, pieces