# Determining primality by using a simple trial division test. # # This approach tests whether n is a multiple of an integer i # between 2 and √n. If it is a multiple of any of these integers # then it is not a prime. import math import time def isPrime(n): for i in range(2, int(math.sqrt(n))): if n % i == 0: return False return True def withTimer(n): start = time.time() prime = isPrime(n) elapsed = time.time() - start print("{0} {1} time:{2}").format(prime, n, elapsed) # Primality of 2 to 13 digit known primes withTimer(13) withTimer(715827883) withTimer(2932031007403) # test non primes withTimer(52) withTimer(5820384023) withTimer(2059384726303) # my output: # True 13 time:0.0 # True 715827883 time:0.00300002098083 # True 2932031007403 time:0.521000146866 # False 52 time:0.0 # False 5820384023 time:0.000999927520752 # False 2059384726303 time:0.029000043869
A python example based blog that shows how to accomplish python goals and how to correct python errors.
Tuesday, May 24, 2011
Python - Determine Primality of a number
Thursday, March 3, 2011
Python - rock paper scissors game from the command line
# Here is a command line Rock Paper Scissor game. # As you can see by my output I am not so good. ;) import random class RockPaperScissors(): """ Play Rock Paper Scissors with Python CLI! """ def __init__(self): # setup the random chooser for the computer self.rand = random.Random() self.cScore = 0 # computer score self.hScore = 0 # human score def getComputerMove(self): return self.rand.randrange(1,4) def getHumanMove(self): while True: choice = input("Make your move: rock (1), paper (2), scissors(3): ") choice = choice.strip() if choice == "1" or choice == "rock": return 1 if choice == "2" or choice == "paper": return 2 if choice == "3" or choice == "scissors": return 3 print("I didn't understand your choice. Please try again") def decideWinner(self, c, h): """ rock breaks scissors paper covers rock scissors cuts paper """ if (c, h) == (1, 3): print("rock breaks scissors") print("computer wins") self.cScore+=1 elif (h, c) == (1, 3): print("rock breaks scissors") print("you win") self.hScore+=1 elif (c, h) == (2, 1): print("paper covers rock") print("computer wins") self.cScore+=1 elif (h, c) == (2, 1): print("paper covers rock") print("you win") self.hScore+=1 elif (c, h) == (3, 2): print("scissors cuts paper") print("computer wins") self.cScore+=1 elif (h, c) == (3, 2): print("scissors cuts paper") print("you win") self.hScore+=1 else: print("Tie!") def showScore(self): print("Score:") print("Computer: ", self.cScore, " You: ", self.hScore) def playAgain(self): yn = input("Play Again? (y/n): ") yn = yn.strip() yn = yn.lower() if yn == "n" or yn == "no": return False return True def gameLoop(self): while True: print() print() computerMove = self.getComputerMove() humanMove = self.getHumanMove() print() print("you chose: ", humanMove, " computer chose: ", computerMove) self.decideWinner(computerMove, humanMove) print() self.showScore() if self.playAgain() == False: return if __name__ == '__main__': rps = RockPaperScissors() rps.gameLoop() ## my output: ## Make your move: rock (1), paper (2), scissors(3): 2 ## ## you chose: 2 computer chose: 3 ## scissors cuts paper ## computer wins ## ## Score: ## Computer: 1 You: 0 ## Play Again? (y/n): y ## ## ## Make your move: rock (1), paper (2), scissors(3): 1 ## ## you chose: 1 computer chose: 1 ## Tie! ## ## Score: ## Computer: 1 You: 0 ## Play Again? (y/n): y ## ## ## Make your move: rock (1), paper (2), scissors(3): 3 ## ## you chose: 3 computer chose: 1 ## rock breaks scissors ## computer wins ## ## Score: ## Computer: 2 You: 0
Python - Compute the factorial of N with recursion (among others)
# Calculating the factorial of a number # is a good way to practice recursion. Below # are examples of both recursive and iterative # approaches to calculating a factorial. Of course # python has its own builtin math module that # can also take care of factorials. import math # A recursive function to calculate the # factorial of N def recursiveFactorial(n): if n == 1: return n return n * recursiveFactorial(n - 1) # Iterative calculation of the factorial # of N def iterativeFactorial(n): result = 1 while n > 1: result *= n n = n-1 return result # Builtin python math.factorial of N def pythonLib(n): return math.factorial(n) print("Iterative factorial of 5: ", iterativeFactorial(5)) print("Recursive factorial of 5: ", recursiveFactorial(5)) print("math.factorial of 5: ", pythonLib(5)) print("Iterative factorial of 10: ", iterativeFactorial(10)) print("Recursive factorial of 10: ", recursiveFactorial(10)) print("math.factorial of 10: ", pythonLib(10)) print("Iterative factorial of 15: ", iterativeFactorial(15)) print("Recursive factorial of 15: ", recursiveFactorial(15)) print("math.factorial of 15: ", pythonLib(15)) # my results: # Iterative factorial of 5: 120 # Recursive factorial of 5: 120 # math.factorial of 5: 120 # Iterative factorial of 10: 3628800 # Recursive factorial of 10: 3628800 # math.factorial of 10: 3628800 # Iterative factorial of 15: 1307674368000 # Recursive factorial of 15: 1307674368000 # math.factorial of 15: 1307674368000
Tuesday, February 8, 2011
Python - working with fractions
# Add, Subract, Multiply or Divide Fractions with python # use the built in python Fraction module from fractions import Fraction print("Enter two fractions.") # Get the two fractions a = Fraction(input("Enter the first fraction: ")) b = Fraction(input("Enter the second fraction: ")) print("Add: ", a + b) print("Subtract: ", a - b) print("Multiply: ", a * b) print("Divide: ", a / b) # my output: ## Enter two fractions. ## Enter the first fraction: 1/2 ## Enter the second fraction: 2/5 ## Add: 9/10 ## Subtract: 1/10 ## Multiply: 1/5 ## Divide: 5/4
Thursday, February 3, 2011
Python - Roman Numeral to Number Generator
# Convert a roman numeral to a number. # # If you are interested in roman numerals check out my other post # python script that takes a number and generates a roman numeral # # For a life time of knowledge checkout: # http://en.wikipedia.org/wiki/Roman_numerals # def ConvertRomanNumeralToNumber(roman_numeral): number_result = 0 roman_numerals = { 1:"I", 4:"IV", 5:"V", 9:"IX", 10:"X", 40:"XL", 50:"L", 90:"XC", 100:"C", 400:"CD", 500:"D", 900:"CM", 1000:"M"} # Iterate through the roman numerals. But you see here that I sort them to # get the largest string size first: "CD" comes before "I" for numeral_value in sorted(roman_numerals, key=lambda roman: len(roman_numerals[roman]), reverse=True): keep_converting = True while keep_converting: if roman_numeral.find(roman_numerals[numeral_value]) != -1: number_result += numeral_value roman_numeral = roman_numeral.replace(roman_numerals[numeral_value], "", 1) else: keep_converting = False return number_result print(ConvertRomanNumeralToNumber("MCDXLIV")) print(ConvertRomanNumeralToNumber("MMMDCCCLXXXVIII")) print(ConvertRomanNumeralToNumber("MMMCMXCIX")) # my output: # 1444 # 3888 # 3999
Python - Roman Numeral Generator
# Convert a number to a roman numeral. # # If you are interested in roman numerals check out my other post to convert roman numerals back to numbers # python script that takes roman numerals and generates numbers. # # To increase your life time of knowledge read up on roman numerals: # http://en.wikipedia.org/wiki/Roman_numerals def ConvertNumberToRomanNumeral(number): roman_numeral_result = "" # Roman numeral dict. Place approved roman numeral key:value pairs # in the dict and they will be used. roman_numerals = { 1:"I", 4:"IV", 5:"V", 9:"IX", 10:"X", 40:"XL", 50:"L", 90:"XC", 100:"C", 400:"CD", 500:"D", 900:"CM", 1000:"M"} # Iterate from highest to lowest through the roman numerals. for numeral_value in sorted(roman_numerals.keys(), reverse=True): # Continue replacing large roman numerals while the number is # high enough. while (number >= numeral_value): # Build the Roman Numeral string. roman_numeral_result += roman_numerals[numeral_value] # Decrease the working number by the roman numeral value just # added to the roman numeral result. number -= numeral_value return roman_numeral_result print(ConvertNumberToRomanNumeral(1444)) print(ConvertNumberToRomanNumeral(3888)) print(ConvertNumberToRomanNumeral(3999)) # my output: # MCDXLIV # MMMDCCCLXXXVIII # MMMCMXCIX
Subscribe to:
Posts (Atom)