{"id":4673,"date":"2013-02-01T09:55:57","date_gmt":"2013-02-01T01:55:57","guid":{"rendered":"http:\/\/jpuyy.com\/?p=4673"},"modified":"2013-02-15T23:04:40","modified_gmt":"2013-02-15T15:04:40","slug":"python-simple-programs-b","status":"publish","type":"post","link":"https:\/\/jpuyy.com\/?p=4673","title":{"rendered":"python\u7684\u5165\u95e8\u7684\u51e0\u4e2a\u4f8b\u5b50(\u4e2d)"},"content":{"rendered":"<p>\u63a5\u7740\u4e0a\u4e00\u4e2ahttp:\/\/jpuyy.com\/2012\/12\/python-simple-programs-a.html<\/p>\n<p>\u4f8b11.\u4e09\u5f15\u53f7\uff0cwhile\u5faa\u73af&#8211;Triple-quoted strings, while loop<\/p>\n<pre dir=\"ltr\" id=\"CA-41855e2228c84d744fa66e2be87fe61d1ecd8f7c\" lang=\"en\">REFRAIN = '''\r\n%d bottles of beer on the wall,\r\n%d bottles of beer,\r\ntake one down, pass it around,\r\n%d bottles of beer on the wall!\r\n'''\r\nbottles_of_beer = 99\r\nwhile bottles_of_beer &gt; 1:\r\n    print REFRAIN % (bottles_of_beer, bottles_of_beer,\r\n        bottles_of_beer - 1)\r\n    bottles_of_beer -= 1<\/pre>\n<p>\u4f8b12.python\u4e2d\u7684\u7c7b&#8211;Classes<\/p>\n<pre dir=\"ltr\" id=\"CA-1be4ae961f9631b4fc0d9d22df3ebbf91055e48b\" lang=\"en\">class BankAccount(object):\r\n    def __init__(self, initial_balance=0):\r\n        self.balance = initial_balance\r\n    def deposit(self, amount):\r\n        self.balance += amount\r\n    def withdraw(self, amount):\r\n        self.balance -= amount\r\n    def overdrawn(self):\r\n        return self.balance &lt; 0\r\nmy_account = BankAccount(15)\r\nmy_account.withdraw(5)\r\nprint my_account.balance<\/pre>\n<p>\u6267\u884c\u7ed3\u679c\u662f10<\/p>\n<p>\u4f8b13.\u4f7f\u7528unittest\u6a21\u5757\u8fdb\u884c\u5355\u5143\u6d4b\u8bd5&#8211;Unit test with unittest<\/p>\n<pre dir=\"ltr\" id=\"CA-923b1a1e2d906f544f62fa781373ad665e36c831\" lang=\"en\">import unittest\r\ndef median(pool):\r\n    copy = sorted(pool)\r\n    size = len(copy)\r\n    if size % 2 == 1:\r\n        return copy[(size - 1) \/ 2]\r\n    else:\r\n        return (copy[size\/2 - 1] + copy[size\/2]) \/ 2\r\nclass TestMedian(unittest.TestCase):\r\n    def testMedian(self):\r\n        self.failUnlessEqual(median([2, 9, 9, 7, 9, 2, 4, 5, 8]), 7)\r\nif __name__ == '__main__':\r\n    unittest.main()<\/pre>\n<p>\u6267\u884c\u8fc7\u7a0b\uff1a\u5c06\u4e2d\u95f4\u503c\u8ba1\u7b97\u51fa\u6765\u4e0e7\u6bd4\u8f83\uff0c\u5982\u679c\u76f8\u7b49\uff0c\u5219\u901a\u8fc7\u6d4b\u8bd5\u3002<\/p>\n<p>\u4f8b14.\u57fa\u4e8eDoctest\u7684\u6d4b\u8bd5&#8211;Doctest-based testing<\/p>\n<pre dir=\"ltr\" id=\"CA-b291f26703d64f30db83c33958f05a85252f8b00\" lang=\"en\">def median(pool):\r\n    '''Statistical median to demonstrate doctest.\r\n    &gt;&gt;&gt; median([2, 9, 9, 7, 9, 2, 4, 5, 8])\r\n    7\r\n    '''\r\n    copy = sorted(pool)\r\n    size = len(copy)\r\n    if size % 2 == 1:\r\n        return copy[(size - 1) \/ 2]\r\n    else:\r\n        return (copy[size\/2 - 1] + copy[size\/2]) \/ 2\r\nif __name__ == '__main__':\r\n    import doctest\r\n    doctest.testmod()<\/pre>\n<p>\u6267\u884c\u7ed3\u679c\uff1a\u6ca1\u6709\u8f93\u51fa\u4efb\u4f55\u4e1c\u897f\uff0c\u8bf4\u660e\u4e2d\u95f4\u503c\u662f7<\/p>\n<p>\u4f8b15.\u4f7f\u7528itertools\u6a21\u5757<\/p>\n<pre>from itertools import groupby\r\nlines = '''\r\nThis is the\r\nfirst paragraph.\r\n\r\nThis is the second.\r\n'''.splitlines()\r\n# Use itertools.groupby and bool to return groups of\r\n# consecutive lines that either have content or don't.\r\nfor has_chars, frags in groupby(lines, bool):\r\n    if has_chars:\r\n        print ' '.join(frags)\r\n# PRINTS:\r\n# This is the first paragraph.\r\n# This is the second.<\/pre>\n<p>\u4f8b16.csv\u6a21\u5757\uff0c\u5143\u7ec4\u62c6\u5206\uff0c\u5185\u7f6e\u51fd\u6570cmp() &#8212; csv module, tuple unpacking, cmp() built-in<\/p>\n<pre dir=\"ltr\" id=\"CA-f6ba24a19e7058ddace7b75ade4a35920365fa8c\" lang=\"en\">import csv\r\n\r\n# write stocks data as comma-separated values\r\nwriter = csv.writer(open('stocks.csv', 'wb', buffering=0))\r\nwriter.writerows([\r\n    ('GOOG', 'Google, Inc.', 505.24, 0.47, 0.09),\r\n    ('YHOO', 'Yahoo! Inc.', 27.38, 0.33, 1.22),\r\n    ('CNET', 'CNET Networks, Inc.', 8.62, -0.13, -1.49)\r\n])\r\n\r\n# read stocks data, print status messages\r\nstocks = csv.reader(open('stocks.csv', 'rb'))\r\nstatus_labels = {-1: 'down', 0: 'unchanged', 1: 'up'}\r\nfor ticker, name, price, change, pct in stocks:\r\n    status = status_labels[cmp(float(change), 0.0)]\r\n    print '%s is %s (%s%%)' % (name, status, pct)<\/pre>\n<p>\u4f8b18. <a title=\"\u516b\u7687\u540e\u95ee\u9898python\" href=\"http:\/\/zh.wikipedia.org\/wiki\/%E5%85%AB%E7%9A%87%E5%90%8E%E9%97%AE%E9%A2%98\" target=\"_blank\">\u516b\u7687\u540e\u95ee\u9898<\/a>\uff0c\u9012\u5f52&#8211;8-Queens Problem (recursion)<\/p>\n<pre dir=\"ltr\" id=\"CA-53ce7fd3eb7f1860937f3648695333438a178d82\" lang=\"en\">BOARD_SIZE = 8\r\n\r\ndef under_attack(col, queens):\r\n    left = right = col\r\n\r\n    for r, c in reversed(queens):\r\n        left, right = left - 1, right + 1\r\n\r\n        if c in (left, col, right):\r\n            return True\r\n    return False\r\n\r\ndef solve(n):\r\n    if n == 0:\r\n        return [[]]\r\n\r\n    smaller_solutions = solve(n - 1)\r\n\r\n    return [solution+[(n,i+1)]\r\n        for i in xrange(BOARD_SIZE)\r\n            for solution in smaller_solutions\r\n                if not under_attack(i+1, solution)]\r\nfor answer in solve(BOARD_SIZE):\r\n    print answer<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>\u63a5\u7740\u4e0a\u4e00\u4e2ahttp:\/\/jpuyy.com\/2012\/12\/python-simple-programs-a.html \u4f8b11.\u4e09\u5f15\u53f7\uff0cwhile\u5faa\u73af&#8211;Triple-quoted strings, while loop REFRAIN = &#8221;&#8217; %d bottles of beer on the wall, %d bottles of beer, take one down, pass it around, %d bottles of beer on the wall! &#8221;&#8217; bottles_of_beer = 99 while bottles_of_beer &gt; 1: print REFRAIN % (bottles_of_beer, bottles_of_beer, bottles_of_beer &#8211; 1) bottles_of_beer -= 1 \u4f8b12.python\u4e2d\u7684\u7c7b&#8211;Classes class BankAccount(object): def [&hellip;]<\/p>\n","protected":false},"author":3,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[76],"tags":[23],"class_list":["post-4673","post","type-post","status-publish","format-standard","hentry","category-python","tag-summary"],"_links":{"self":[{"href":"https:\/\/jpuyy.com\/index.php?rest_route=\/wp\/v2\/posts\/4673","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/jpuyy.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jpuyy.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jpuyy.com\/index.php?rest_route=\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/jpuyy.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=4673"}],"version-history":[{"count":9,"href":"https:\/\/jpuyy.com\/index.php?rest_route=\/wp\/v2\/posts\/4673\/revisions"}],"predecessor-version":[{"id":4699,"href":"https:\/\/jpuyy.com\/index.php?rest_route=\/wp\/v2\/posts\/4673\/revisions\/4699"}],"wp:attachment":[{"href":"https:\/\/jpuyy.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=4673"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jpuyy.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=4673"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jpuyy.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=4673"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}