Monday, December 16, 2013

Python - bubble sort or was that sift sort


# Here is an implementation of bubble sort
# or as some call it sift sort, settle sort,
# whatever you want to call it, here it is:
def siftSort(originalList):
    size = len(originalList)
    sifted = False
    while not sifted:
        sifted = True
        for i in range(0, len(originalList)):
             pos = i
             if (i>=size-1):
                break;
             if originalList[pos] > originalList[pos+1]:
                sifted = False;
                originalList[pos+1], originalList[pos] = originalList[pos], originalList[pos+1]

    return originalList



if (__name__ == '__main__'):
    # my 'random' list that needs sorting
    myList = [987,9999,25,61,0,14,61,1234,99,986]
    print("the original list: {0}".format(myList))
    print("the sorted list: {0}".format(siftSort(myList)))


# output:
# the original list: [987, 9999, 25, 61, 0, 14, 61, 1234, 99, 986]
# the sorted list: [0, 14, 25, 61, 61, 99, 986, 987, 1234, 9999]

Tuesday, May 24, 2011

Python - Determine Primality of a number

 
# 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 
 
 
 

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