Lecture Notes on 17 Mar 2014 * Let us take stock of where we are: * Binary Conversions: decimal, binary, octal, hexadecimal * Characterset - ASCII and Unicode * Defining Variables - places in memory * Implicit Types - int, float, str, bool * Operators - Arithmetic: + - * / // % ** - Comparison: < <= > >= == != - Logical: not, and or - Bitwise: ~ & | ^ - Shift: << >> * Conditionals: if-else, if-elif-else * Conditional expression: result = b if a > value else c * Loops: while, for * Use while with sentinel value or loop counter * Use for with range function * break, continue and use of boolean flags * Define functions * Formatted output win = round (7 / 10, 2) print ('Probability of winning if you switch = %0.2f' % (win)) * Project Euler - Problem 3: Largest Prime Factor - Problem 4: Largest Palindrome Product # reverse a number def rev_num (n): r_num = 0 while (n > 0): r_num = r_num * 10 + n % 10 n = n // 10 return r_num # determine if a number is palindromic def is_palindromic (n): return (n == rev_num(n)) # determine if a number is prime def is_prime (n): limit = int (n ** 0.5) + 1 for div in range (2, limit): if (n % div == 0): return False return True def main(): # find largest prime factor of 600851475143 num = 600851475143 limit = int (num ** 0.5) + 1 if (limit % 2 == 0): limit += 1 for divisor in range (3, limit, 2): if (num % divisor == 0): factor = num // divisor if (is_prime(divisor)): print (divisor) elif (is_prime(factor)): print (factor) # find largest palindrome of the product of two 3-digit numbers max_palin = 0 num_1 = 0 num_2 = 0 for i in range (100, 1000): for j in range (100, 1000): product = i * j if (is_palindromic (product)): if (product > max_palin): max_palin = product num_1 = i num_2 = j print ('Largest palindrome = ', max_palin, 'product of', num_1, 'and', num_2) main()