diff --git a/FaceRecognition.py b/FaceRecognition.py new file mode 100644 index 0000000..e26fcc2 --- /dev/null +++ b/FaceRecognition.py @@ -0,0 +1,39 @@ +##Face Recognition With Python + +#Install openCV with "import cv2" inb python command line + + +# Get user supplied values +imagePath = sys.argv[1] +cascPath = sys.argv[2] + +# Create the haar cascade +faceCascade = cv2.CascadeClassifier(cascPath) + + +# Read the image +image = cv2.imread(imagePath) +gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) + + +# Detect faces in the image +faces = faceCascade.detectMultiScale( + gray, + scaleFactor=1.1, + minNeighbors=5, + minSize=(30, 30), + flags = cv2.cv.CV_HAAR_SCALE_IMAGE +) + + +print "Found {0} faces!".format(len(faces)) + +# Draw a rectangle around the faces +for (x, y, w, h) in faces: + cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2) + + +cv2.imshow("Faces found" ,image) +cv2.waitKey(0) + +python face_detect.py abba.png haarcascade_frontalface_default.xml diff --git a/dice-roller/dice.py b/dice-roller/dice.py new file mode 100644 index 0000000..8dd95a9 --- /dev/null +++ b/dice-roller/dice.py @@ -0,0 +1,82 @@ +"""Dice roller for any number of dice and sides""" +# random int generator +from random import randint + +def main(): + """main function""" + pass + +if __name__ == "__main__": + main() + +def dice_input(): + """Get the number of dice.""" + global dice + # input for dice number variable + dice = int(raw_input('How many dice would you like to roll? ')) + # Validate for positive integers + dice_int = False + while not dice_int: + if dice <= 0: + print "Error! Please enter a positive number of dice." + dice_input() + else: + dice_int = True + print "Ok, I will roll %s dice." % (dice) + return + + +def sides_input(): + """Get the number of sides""" + global sides + sides = int(raw_input('How many sides does each dice have? ')) + # Validate for positive integers + sides_int = False + while not sides_int: + if sides <= 0: + print "Error! Please enter a positive number of sides." + sides_input() + else: + sides_int = True + return + + +def roll_dice(): + """Loop through number of dice, randomly generate numbers""" + print "Ok, rolling %s dice with %s sides." % (dice, sides) + roll = 0 + for roll in range(0, dice): + print "[%s]" % (randint(1, sides)) + + again = raw_input('Would you like to roll, make a change, or end r/c/e? ') + + if again == 'r': + roll_dice() + elif again == 'e': + print "Ok, thanks!" + return + elif again == 'c': + change() + else: + print "Please respond with r, c, or e" + roll_dice() + + +def change(): + """Change number of dice or sides""" + which = raw_input('Change dice or sides d/s? ') + if which == 'd': + dice_input() + roll_dice() + else: + if which == 's': + sides_input() + roll_dice() + else: + print 'Please input only d or s' + change() + + +dice_input() +sides_input() +roll_dice() diff --git a/random_password.py b/random_password.py new file mode 100644 index 0000000..3880d55 --- /dev/null +++ b/random_password.py @@ -0,0 +1,32 @@ +''' +The password generator will take the length of password (always greater than 3) and output a random password containing at least: + 1. An Aphabet( either lowercase or uppercase) + 2. A number. + + 3. A special character. + +The postion of all these characters will also be random i.e. the number might be the first to come. +Constraints: +The length of password is at least 3 and maximum will be 100. + +''' +from random import choice,sample + +l=0 +while l<3 or l>100 or int(l)!=l: + l=int(input('Enter password length (an integer between 3 and 100)\n')) + +num=list(range(48,58)) +char=list(range(65,91))+list(range(97,123)) +spec=list(range(33,39))+list(range(60,65))+list(range(91,96))+list(range(123,126)) +all=num+char+spec + +passw=[choice(num),choice(char),choice(spec)] + +while len(passw)2 and len(s)<20] + return dict((w,1) for w in words) + + +def sampletrain(cl): + cl.train('Nobody owns the water.', 'good') + cl.train('the quick rabbit jumps fences','good') + cl.train('buy pharmaceuticals now', 'bad') + cl.train('make quick money at online casino', 'bad') + cl.train('the quick brown fox jumps.', 'good') + + +class classifier: + def __init__(self, getfeatures, filename=None): + #Counts of feature/category combinations + self.fc = {} + #Counts of docs in each category + self.cc={} + self.getfeatures = getfeatures + + #Increase the count of a feature-category pair + def incf(self, f, cat): + self.fc.setdefault(f, {}) + self.fc[f].setdefault(cat, 0) + self.fc[f][cat]+=1 + + #Increase the count of a category + def incc(self, cat): + self.cc.setdefault(cat, 0) + self.cc[cat]+=1 + + #The number of times a feature has appeared in a category + def fcount(self, f, cat): + if f in self.fc and cat in self.fc[f]: + return float(self.fc[f][cat]) + return 0.0 + + #The number of items in a category + def catcount(self, cat): + if cat in self.cc: + return float(self.cc[cat]) + return 0 + + #The total number of items + def totalcount(self): + return sum(self.cc.values()) + + #List of all categories + def categories(self): + return self.cc.keys() + + def train(self, item, cat): + features= self.getfeatures(item) + #Increment the count for every feature with this category + for f in features: + self.incf(f, cat) + + #Increment the count for this category + self.incc(cat) + + def fprob(self, f, cat): + if self.catcount(cat)==0: return 0 + return self.fcount(f, cat)/self.catcount(cat) + + def weightedprob(self,f,cat,prf,weight=1.0,ap=0.5): + # Calculate current probability + basicprob = prf(f,cat) + # Count the number of times this feature has appeared in + # all categories + totals=sum([self.fcount(f,c) for c in self.categories()]) + # Calculate the weighted average + bp=((weight*ap)+(totals*basicprob))/(weight+totals) + return bp + +class naivebayes(classifier): + def __init__(self, getfeatures): + classifier.__init__(self, getfeatures) + self.thresholds={} + + def docprob(self, item, cat): + features = self.getfeatures(item) + #Multiply the probabilities of all features together + p = 1 + for f in features : p *= self.weightedprob(f, cat, self.fprob) + return p + + def prob(self, item, cat): + catprob = self.catcount(cat)/self.totalcount() + docprob = self.docprob(item, cat) + return docprob*catprob + + def setthreshold(self, cat, t): + self.thresholds[cat]=t + + def getthreshold(self, cat): + if not cat in self.thresholds: return 1.0 + return self.thresholds[cat] + + def classify(self, item, default=None): + probs = {} + #Find the category with the highest probability + max = 0.0 + for cat in self.categories(): + probs[cat] = self.prob(item, cat) + if probs[cat]>max: + max=probs[cat] + best=cat + + #Make sure the probability exceeds threshold* next best + for cat in probs: + if cat == best: continue + if probs[cat] * self.getthreshold(best)>probs[best]: + return default + return best diff --git a/spellCheck.py b/spellCheck.py new file mode 100644 index 0000000..a02346c --- /dev/null +++ b/spellCheck.py @@ -0,0 +1,40 @@ +import re +from collections import Counter + +def words(text): return re.findall(r'\w+', text.lower()) + +WORDS = Counter(words(open('words.txt').read())) + +def P(word, N=sum(WORDS.values())): + "Probability of `word`." + #print(WORDS[word]) + return WORDS[word] / N + +def correction(word): + "Most probable spelling correction for word." + #print(candidates(word)) + return max(candidates(word), key=P) + +def candidates(word): + "Generate possible spelling corrections for word." + return (known([word]) or known(edits1(word)) or known(edits2(word)) or [word]) + +def known(words): + "The subset of `words` that appear in the dictionary of WORDS." + return set(w for w in words if w in WORDS) + +def edits1(word): + "All edits that are one edit away from `word`." + letters = 'abcdefghijklmnopqrstuvwxyz' + splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] + deletes = [L + R[1:] for L, R in splits if R] + transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1] + replaces = [L + c + R[1:] for L, R in splits if R for c in letters] + inserts = [L + c + R for L, R in splits for c in letters] + return set(deletes + transposes + replaces + inserts) + +def edits2(word): + "All edits that are two edits away from `word`." + return (e2 for e1 in edits1(word) for e2 in edits1(e1)) + +print("correction for 'pythob' = ", correction("pythob")) #prints 'python'