diff --git a/jingdai/Py100-2017q1 b/jingdai/Py100-2017q1 new file mode 160000 index 0000000..d71163e --- /dev/null +++ b/jingdai/Py100-2017q1 @@ -0,0 +1 @@ +Subproject commit d71163e42a8a899da131bf3adfb806c15b95401d diff --git a/jingdai/RegularExpression.py b/jingdai/RegularExpression.py new file mode 100644 index 0000000..3dde688 --- /dev/null +++ b/jingdai/RegularExpression.py @@ -0,0 +1,27 @@ +import re + +string='please help me to find numbers like ABC-123-4567#, YBN-345-8970*' + +regex=re.compile(r'\w\w\w-\d\d\d-\d\d\d\d\S') + +result= regex.search(string) + +print(result.group()) + +# try group the pattern individually + +regex=re.compile(r'(\w\w\w)-(\d\d\d)-(\d\d\d\d\S)') # r for raw_string + +result= regex.search(string) + +print(result.group(3)) + +print(result.groups()) # return a tuple + +# search function only returns first occurrence , how to return all occurrence? + +regex=re.compile(r'\w\w\w-\d\d\d-\d\d\d\d\S') +results= regex.findall(string) +print(results) + + diff --git a/jingdai/Regular_Expression.ipynb b/jingdai/Regular_Expression.ipynb new file mode 100644 index 0000000..413ba37 --- /dev/null +++ b/jingdai/Regular_Expression.ipynb @@ -0,0 +1,230 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "import re" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "string='please help me to find numbers like ABC-123-4567#, YBN-345-8970*'" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "regex=re.compile(r'\\w\\w\\w-\\d\\d\\d-\\d\\d\\d\\d\\S')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\\w for letter, \\d for number, \\S for any characters that is not a space, tab or newline; r for raw_string" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "result= regex.search(string)" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "ABC-123-4567#\n" + ] + } + ], + "source": [ + "print(result.group())" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# try group the pattern individually" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "regex=re.compile(r'(\\w\\w\\w)-(\\d\\d\\d)-(\\d\\d\\d\\d\\S)') # r for raw_string" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "result= regex.search(string)" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "4567#\n" + ] + } + ], + "source": [ + "print(result.group(3))" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "('ABC', '123', '4567#')\n" + ] + } + ], + "source": [ + "print(result.groups()) # return a tuple" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#search function only returns first occurrence , how to return all occurrence?" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "regex=re.compile(r'\\w\\w\\w-\\d\\d\\d-\\d\\d\\d\\d\\S')" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "results= regex.findall(string)" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['ABC-123-4567#', 'YBN-345-8970*']\n" + ] + } + ], + "source": [ + "print(results)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "note: .findall() returns a list" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.4.3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/jingdai/Untitled.ipynb b/jingdai/Untitled.ipynb new file mode 100644 index 0000000..98b6cda --- /dev/null +++ b/jingdai/Untitled.ipynb @@ -0,0 +1,218 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 55, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from math import pi\n", + "\n", + "class Circle(object):\n", + " \n", + " def __init__(self,radius):\n", + " self._radius=radius\n", + " \n", + " @staticmethod\n", + " def radius_to_area(radius):\n", + " return pi*radius**2\n", + "\n", + " @classmethod\n", + " def my_class_method(cls): #cls is the class method decorator\n", + " pass\n", + " \n", + " @property\n", + " def radius(self):\n", + " return self._radius\n", + " \n", + " @radius.setter\n", + " def radius(self,radius):\n", + " self._radius=radius\n", + " \n", + " @property\n", + " def diameter(self):\n", + " return self._radius*2\n", + " \n", + " @diameter.setter\n", + " def diameter(self,diameter):\n", + " self._radius=diameter/2\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 56, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "c=Circle(10)" + ] + }, + { + "cell_type": "code", + "execution_count": 57, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "10" + ] + }, + "execution_count": 57, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c.radius" + ] + }, + { + "cell_type": "code", + "execution_count": 58, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "c.radius = 20" + ] + }, + { + "cell_type": "code", + "execution_count": 59, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "40" + ] + }, + "execution_count": 59, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c.diameter" + ] + }, + { + "cell_type": "code", + "execution_count": 60, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "c.diameter = 50" + ] + }, + { + "cell_type": "code", + "execution_count": 62, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "50.0" + ] + }, + "execution_count": 62, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c.diameter" + ] + }, + { + "cell_type": "code", + "execution_count": 63, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "25.0" + ] + }, + "execution_count": 63, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c._radius" + ] + }, + { + "cell_type": "code", + "execution_count": 64, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "25.0" + ] + }, + "execution_count": 64, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c.radius" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.4.3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/jingdai/circle_class.py b/jingdai/circle_class.py new file mode 100644 index 0000000..d232bf5 --- /dev/null +++ b/jingdai/circle_class.py @@ -0,0 +1,90 @@ +from math import pi + +class Circle (object): + + def __init__(self, radius=0): + self._radius=radius + + @property + def radius(self): + self._radius + print("Radius is: {}".format(self._radius)) + + @radius.setter + def radius(self, value): + if value < 0: + raise ValueError("Negative radius is not possible") + print("Setting value") + self._radius = value + + @property + def diameter(self): + self._radius*2 + print("Diameter is: {}".format(self._radius*2)) + + @diameter.setter + def diameter(self, value): + if value < 0: + raise ValueError("Negative diameter is not possible") + print("Setting value") + self._diameter = value + self._radius=value/2 + + @property + def area(self): + area=pi*self._radius**2 + print("Area is: {:.2f}".format(area)) + + #Add an “alternate constructor” that lets the user create a Circle directly with the diameter + @classmethod + def from_diameter(cls,value): + return cls(value/2) + + def __str__(self): + str(self._radius) + return "Circle with radius: {}".format(str(self._radius)) + + #not sure + def __repr__(self): + return repr("Circle({})".format(str(self._radius))) + + def __add__(self, other): + total_radius=self._radius +other._radius + return Circle(total_radius) + + def __mul__(self, other): + total_radius=self._radius *other._radius + return Circle(total_radius) + + def __eq__(self, other): + return self._radius== other._radius + + def __lt__(self, other): + return self._radius < other._radius + + + +#SmallCircle is to test inheitance +# try use super() , does not necessarily need __init__, also use **kwargs +class SmallCircle(Circle): + def __init__(self, radius): + self._radius=radius + print("SmallCircle radius is {}".format(self._radius)) + + +if __name__ == "__main__": + c=Circle(90) + c1=Circle(50) + print(c> :add a donor and donation h:help l:list donors r:print report t:thank donors q:quit") + + +def load_donordb(): + try: + with open('mailroom.pickle', 'rb') as db_handle: + donor_db = pickle.load(db_handle) + except IOError: + donor_db = { + "Aristotle": [384.0, 322.0], + "Kant": [1724.0, 1804.0, 1785.0], + "Locke": [1632.0], + "Russell": [1872.0, 1970.0, 1950.0], + "Dennett": [1942.0], + } + return donor_db + + +def save_donordb(db): + try: + with open('mailroom.pickle', 'wb') as db_handle: + pickle.dump(db, db_handle) + except IOError: + raise "Error: Unable to save donor database." + + +def add_donation(db, donor, contribution): + if donor in db.keys(): + db[donor].append(float(contribution)) + else: + db[donor] = [float(contribution)] + + +def tally_report(values): + donation_total = sum(values) + num_gifts = len(values) + average_gift = donation_total / num_gifts + return donation_total, num_gifts, average_gift + + +def print_report(db): + # Print a header + print("Donor Name | Total Given | Num Gifts | Average Gift") + + # Print each row + for names, values in db.items(): + donation_total, num_gifts, average_gift = tally_report(values) + + print("{} | {:11,.2f} | {} | ${:11,.2f}".format( + names.ljust(25), + donation_total, + str(num_gifts).rjust(9), + average_gift, + )) + + +def thank_donors(donor, amount): + with open('mailroom-thankyou-{}.txt'.format(donor), 'w') as f: + f.write("Thank you, {}, for your generous donation of ${}.\nSincerly, The Mailroom Team\n".format(donor, amount)) + + +def list_donor_files(): + import glob + print(glob.glob("mailroom-thankyou-*.txt")) + + +if __name__ == '__main__': + print_usage() + + donor_db = load_donordb() + + while True: + user_input = input("mailroom>> ") + + # A handy way to break out of the loop/program + if user_input == 'quit' or user_input == 'q': + save_donordb(donor_db) + break + + # If the user wants a help prompt, print it + if user_input == 'help' or user_input == 'h': + print_usage() + continue + + # If the user wants a list of donors, print it and then continue with a new prompt + if user_input == 'list' or user_input == 'l': + print(sorted(set(donor_db.keys()))) + continue + + # If the user wants a report, print it and then continue with a new prompt + if user_input == 'report' or user_input == 'r': + print_report(donor_db) + continue + + # Generate thank you letters and then continue + if user_input == 'thanks' or user_input == 't': + [thank_donors(name, sum(value)) for name, value in donor_db.items()] + list_donor_files() + continue + + # After the cases above we can assume that the input is a donor's name + donor = user_input + + # We still need an amount + contribution_amount = input("mailroom>> How much is {} contributing? ".format(donor)) + + # Validate user input + try: + float(contribution_amount) + except Exception as my_except: + print("mailroom>> Input validation error: {}".format(my_except)) + continue + + # Catch embezzlement + try: + assert float(contribution_amount) >= 0.0 + except Exception as my_except: + print("mailroom>> Donations must be greater than $0.00: {}".format(my_except)) + continue + + # Add the donation to the db + add_donation(donor_db, donor, contribution_amount) diff --git a/jingdai/sherlock_small.txt b/jingdai/sherlock_small.txt new file mode 100644 index 0000000..dcccaab --- /dev/null +++ b/jingdai/sherlock_small.txt @@ -0,0 +1,17 @@ +One night--it was on the twentieth of March, 1888--I was +returning from a journey to a patient (for I had now returned to +civil practice), when my way led me through Baker Street. As I +passed the well-remembered door, which must always be associated +in my mind with my wooing, and with the dark incidents of the +Study in Scarlet, I was seized with a keen desire to see Holmes +again, and to know how he was employing his extraordinary powers. +His rooms were brilliantly lit, and, even as I looked up, I saw +his tall, spare figure pass twice in a dark silhouette against +the blind. He was pacing the room swiftly, eagerly, with his head +sunk upon his chest and his hands clasped behind him. To me, who +knew his every mood and habit, his attitude and manner told their +own story. He was at work again. He had risen out of his +drug-created dreams and was hot upon the scent of some new +problem. I rang the bell and was shown up to the chamber which +had formerly been in part my own. + diff --git a/jingdai/test_pickle.py b/jingdai/test_pickle.py new file mode 100644 index 0000000..f8f2cb0 --- /dev/null +++ b/jingdai/test_pickle.py @@ -0,0 +1,37 @@ +def conver_to_roman(a,map): + + a=int(a) + if a==0: + print("Roman number does not include Zero.") + else: + if a/10<1: + return map[a] + if a/10>=1 and a/10<10: + pass + + + + +map={0:"",1:"I",2:"II",3:"III",4:"IV",5:"V",6:"VI",7:"VII",8:"VIII",9:"IX"} +map1={} +for key in map: + map1[key]=map[key] + map1[key+10]="X"+map[key] + map1[key+20]="XX"+map[key] + map1[key+30]="XXX"+map[key] + map1[key+40]="XL"+map[key] + map1[key+50]="L"+map[key] + map1[key+60]="LX"+map[key] + map1[key+70]="LXX"+map[key] + map1[key+80]="LXXX"+map[key] + map1[key+90]="XC"+map[key] +print(map1) + + + + +#map1={10:"X",11:"XI",12:"XII",13:"XIII",14:"XIV",15:"XV",16:"XVI",17:"XVII",18:"XVIII",19:"XIX"} +#map2={20:"XX",21:"XXI",22:"XXII"} +#user_input = input("number>>") +#b=conver_to_roman(user_input,map) +#print(b) diff --git a/jingdai/test_random_unitest.py b/jingdai/test_random_unitest.py new file mode 100644 index 0000000..f825be5 --- /dev/null +++ b/jingdai/test_random_unitest.py @@ -0,0 +1,30 @@ +import random +import unittest + + +class TestSequenceFunctions(unittest.TestCase): + + def setUp(self): + self.seq = list(range(10)) + + def test_shuffle(self): + # make sure the shuffled sequence does not lose any elements + random.shuffle(self.seq) + self.seq.sort() + self.assertEqual(self.seq, list(range(10))) + + # should raise an exception for an immutable sequence + self.assertRaises(TypeError, random.shuffle, (1, 2, 3)) + + def test_choice(self): + element = random.choice(self.seq) + self.assertTrue(element in self.seq) + + def test_sample(self): + with self.assertRaises(ValueError): + random.sample(self.seq, 20) + for element in random.sample(self.seq, 5): + self.assertTrue(element in self.seq) + +if __name__ == '__main__': + unittest.main() diff --git a/jingdai/trigram_1.py b/jingdai/trigram_1.py new file mode 100644 index 0000000..08c9abd --- /dev/null +++ b/jingdai/trigram_1.py @@ -0,0 +1 @@ +#!/usr/bin/env python3 import random def open_file(file): with open(file,'r') as f: s=f.read() s = s.replace("\n", " ") # remove line feed s = s.replace("--"," ") s = s.replace(",","") s = s.replace(".","") s = s.replace("(","") s = s.replace(")","") return s def build_dict(s): l=s.split(' ') d={} for i in range(len(l)-2): values=[] key=l[i]+ ' '+l[i+1] value=l[i+2] values.append(value) if key in d: for i in range(len(d[key])): # get all the elements from the value list values.append(d[key][i]) values.reverse() d[key]=values key_count={} # store number of values of a key key_list=list(d.keys()) for key in key_list: if key in d.keys(): count=len(d[key]) key_count[key]=count return (d, key_count, key_list) def trigram(d,key_count,key_list): seed=random.randint(0,len(key_list)) # choose a random number as a starting point start_point=key_list[seed-1] new_string=start_point key_point={} # store the number of how many times a key was hit key_point=key_count.copy() for key in key_point: values=0 key_point[key]=values for i in range(len(d)): nl=new_string.split(' ') new_key=nl[i] + ' '+nl[i+1] if new_key in d: if key_count[new_key]==1: new_string= new_string+ ' ' + d[new_key][0] key_point[new_key]=1 elif key_count[new_key]>1: if key_point[new_key]