Python in minute
Please note that these examples are written in Python 2, and may need some adjustment to run under Python 3.
1 line: Output
print 'Hello, world!'
2 lines: Input, assignment
name = raw_input('What is your name?\n') print 'Hi, %s.' % name
3 lines: For loop, built-in enumerate function, new style formatting
friends = ['john', 'pat', 'gary', 'michael'] for i, name in enumerate(friends):print "iteration {iteration} is {name}".format(iteration=i, name=name)
4 lines: Fibonacci, tuple assignment
parents, babies = (1, 1) while babies < 100:print 'This generation has {0} babies'.format(babies)parents, babies = (babies, parents + babies)
5 lines: Functions
def greet(name):print 'Hello', name greet('Jack') greet('Jill') greet('Bob')
6 lines: Import, regular expressions
import re for test_string in ['555-1212', 'ILL-EGAL']:if re.match(r'^\d{3}-\d{4}$', test_string):print test_string, 'is a valid US local phone number'else:print test_string, 'rejected'
7 lines: Dictionaries, generator expressions
prices = {'apple': 0.40, 'banana': 0.50} my_purchase = {'apple': 1,'banana': 6} grocery_bill = sum(prices[fruit] * my_purchase[fruit]for fruit in my_purchase) print 'I owe the grocer $%.2f' % grocery_bill
8 lines: Command line arguments, exception handling
# This program adds up integers in the command line import sys try:total = sum(int(arg) for arg in sys.argv[1:])print 'sum =', total except ValueError:print 'Please supply integer arguments'
9 lines: Opening files
# indent your Python code to put into an email import glob # glob supports Unix style pathname extensions python_files = glob.glob('*.py') for file_name in sorted(python_files):print ' ------' + file_namewith open(file_name) as f:for line in f:print ' ' + line.rstrip()print
10 lines: Time, conditionals, from..import, for..else
from time import localtimeactivities = {8: 'Sleeping',9: 'Commuting',17: 'Working',18: 'Commuting',20: 'Eating',22: 'Resting' }time_now = localtime() hour = time_now.tm_hourfor activity_time in sorted(activities.keys()):if hour < activity_time:print activities[activity_time]break else:print 'Unknown, AFK or sleeping!'
11 lines: Triple-quoted strings, while loop
REFRAIN = ''' %d bottles of beer on the wall, %d bottles of beer, take one down, pass it around, %d bottles of beer on the wall! ''' bottles_of_beer = 99 while bottles_of_beer > 1:print REFRAIN % (bottles_of_beer, bottles_of_beer,bottles_of_beer - 1)bottles_of_beer -= 1
12 lines: Classes
class BankAccount(object):def __init__(self, initial_balance=0):self.balance = initial_balancedef deposit(self, amount):self.balance += amountdef withdraw(self, amount):self.balance -= amountdef overdrawn(self):return self.balance < 0 my_account = BankAccount(15) my_account.withdraw(5) print my_account.balance
13 lines: Unit testing with unittest
import unittest def median(pool):copy = sorted(pool)size = len(copy)if size % 2 == 1:return copy[(size - 1) / 2]else:return (copy[size/2 - 1] + copy[size/2]) / 2 class TestMedian(unittest.TestCase):def testMedian(self):self.failUnlessEqual(median([2, 9, 9, 7, 9, 2, 4, 5, 8]), 7) if __name__ == '__main__':unittest.main()
14 lines: Doctest-based testing
def median(pool):'''Statistical median to demonstrate doctest.>>> median([2, 9, 9, 7, 9, 2, 4, 5, 8])7'''copy = sorted(pool)size = len(copy)if size % 2 == 1:return copy[(size - 1) / 2]else:return (copy[size/2 - 1] + copy[size/2]) / 2 if __name__ == '__main__':import doctestdoctest.testmod()
15 lines: itertools
from itertools import groupby lines = ''' This is the first paragraph.This is the second. '''.splitlines() # Use itertools.groupby and bool to return groups of # consecutive lines that either have content or don't. for has_chars, frags in groupby(lines, bool):if has_chars:print ' '.join(frags) # PRINTS: # This is the first paragraph. # This is the second.
16 lines: csv module, tuple unpacking, cmp() built-in
import csv# write stocks data as comma-separated values writer = csv.writer(open('stocks.csv', 'wb', buffering=0)) writer.writerows([('GOOG', 'Google, Inc.', 505.24, 0.47, 0.09),('YHOO', 'Yahoo! Inc.', 27.38, 0.33, 1.22),('CNET', 'CNET Networks, Inc.', 8.62, -0.13, -1.49) ])# read stocks data, print status messages stocks = csv.reader(open('stocks.csv', 'rb')) status_labels = {-1: 'down', 0: 'unchanged', 1: 'up'} for ticker, name, price, change, pct in stocks:status = status_labels[cmp(float(change), 0.0)]print '%s is %s (%s%%)' % (name, status, pct)
18 lines: 8-Queens Problem (recursion)
BOARD_SIZE = 8def under_attack(col, queens):left = right = colfor r, c in reversed(queens):left, right = left - 1, right + 1if c in (left, col, right):return Truereturn Falsedef solve(n):if n == 0:return [[]]smaller_solutions = solve(n - 1)return [solution+[(n,i+1)]for i in xrange(BOARD_SIZE)for solution in smaller_solutionsif not under_attack(i+1, solution)] for answer in solve(BOARD_SIZE):print answer
20 lines: Prime numbers sieve w/fancy generators
import itertoolsdef iter_primes():# an iterator of all numbers between 2 and +infinitynumbers = itertools.count(2)# generate primes foreverwhile True:# get the first number from the iterator (always a prime)prime = numbers.next()yield prime# this code iteratively builds up a chain of# filters...slightly tricky, but ponder it a bitnumbers = itertools.ifilter(prime.__rmod__, numbers)for p in iter_primes():if p > 1000:breakprint p
21 lines: XML/HTML parsing (using Python 2.5 or third-party library)
dinner_recipe = '''<html><body><table> <tr><th>amt</th><th>unit</th><th>item</th></tr> <tr><td>24</td><td>slices</td><td>baguette</td></tr> <tr><td>2+</td><td>tbsp</td><td>olive oil</td></tr> <tr><td>1</td><td>cup</td><td>tomatoes</td></tr> <tr><td>1</td><td>jar</td><td>pesto</td></tr> </table></body></html>'''# In Python 2.5 or from http://effbot.org/zone/element-index.htm import xml.etree.ElementTree as etree tree = etree.fromstring(dinner_recipe)# For invalid HTML use http://effbot.org/zone/element-soup.htm # import ElementSoup, StringIO # tree = ElementSoup.parse(StringIO.StringIO(dinner_recipe))pantry = set(['olive oil', 'pesto']) for ingredient in tree.getiterator('tr'):amt, unit, item = ingredientif item.tag == "td" and item.text not in pantry:print "%s: %s %s" % (item.text, amt.text, unit.text)
28 lines: 8-Queens Problem (define your own exceptions)
BOARD_SIZE = 8class BailOut(Exception):passdef validate(queens):left = right = col = queens[-1]for r in reversed(queens[:-1]):left, right = left-1, right+1if r in (left, col, right):raise BailOutdef add_queen(queens):for i in range(BOARD_SIZE):test_queens = queens + [i]try:validate(test_queens)if len(test_queens) == BOARD_SIZE:return test_queenselse:return add_queen(test_queens)except BailOut:passraise BailOutqueens = add_queen([]) print queens print "\n".join(". "*q + "Q " + ". "*(BOARD_SIZE-q-1) for q in queens)
33 lines: "Guess the Number" Game (edited) from http://inventwithpython.com
import randomguesses_made = 0name = raw_input('Hello! What is your name?\n')number = random.randint(1, 20) print 'Well, {0}, I am thinking of a number between 1 and 20.'.format(name)while guesses_made < 6:guess = int(raw_input('Take a guess: '))guesses_made += 1if guess < number:print 'Your guess is too low.'if guess > number:print 'Your guess is too high.'if guess == number:breakif guess == number:print 'Good job, {0}! You guessed my number in {1} guesses!'.format(name, guesses_made) else:print 'Nope. The number I was thinking of was {0}'.format(number)
转载于:https://www.cnblogs.com/Ironman-Jason/p/5822950.html
Python in minute相关推荐
- python将excel日期比大小_sql与excel、python比较(二)——日期和时间函数
1.CURDATE()或CURRENT_DATE():返回当前的日期 select curdate(),current_date(); excel:TODAY python:datetime和time ...
- 面试环节最后的一问一答
来源:摘自陈鹏的博客http://chenpeng.info/html/2734# 引言: 综合或者技术面试最后都会问面试者有什么想问的吗,记得第一次被思杰hr问时就随后说了句企业文化,还 ...
- Python||datetime.timedelta()详解,核心是minutes与minute
datetime官方文档 from datetime import datetime,timedelta timedelta代表两个datetime之间的时间差. class datetime.tim ...
- pytorch源码解析:Python层 pytorchmodule源码
尝试使用了pytorch,相比其他深度学习框架,pytorch显得简洁易懂.花时间读了部分源码,主要结合简单例子带着问题阅读,不涉及源码中C拓展库的实现. 一个简单例子 实现单层softmax二分类, ...
- Python分析离散心率信号(上)
Python分析离散心率信号(上) 一些理论和背景 心率包含许多有关信息.如果拥有心率传感器和一些数据,那么当然可以购买分析包或尝试一些可用的开源产品,但是并非所有产品都可以满足需求.也是这种情况.那 ...
- Python学习笔记第五周
目录 一.基础概念 1.模块定义 2.包的定义 3.导入包的本质 4.导入模块的本质 5.导入方法 6.import的本质 7.导入优化 8.模块分类 9.标准库介绍 1.time与datetime ...
- python做定时任务的方式及优缺点_python BlockingScheduler定时任务及其他方式的实现...
本文介绍了python BlockingScheduler定时任务及其他方式的实现,具体如下: #BlockingScheduler定时任务 from apscheduler.schedulers.b ...
- python定时任务contrib_django+celery配置(定时任务+循环任务)
下面介绍一下django+celery的配置做定时任务 1.首先介绍一下环境和版本 python==2.7 django == 1.8.1 celery == 3.1.23 django-celery ...
- Python中处理时间 —— time模块
time模块 逝去的秒数 逝去的秒数表示从某个时间(Python中是"Thu Jan 1 07:00:00 1970")开始到现在所经过的秒数. 使用 time.time() 函数 ...
最新文章
- 开源天气预报api整理
- oracle手机号码检验字数_短信字数在线测试
- could not load java7_xml导入properties文件报异常:Could not load JDBC driver class [${jdbc.driver}]...
- The 2019 ICPC Asia Shanghai Regional Contest
- 第 45 届国际大学生程序设计竞赛(ICPC)亚洲区域赛(昆明) AC(带悔贪心)
- springBoot(20):使用Spring Session实现集群-redis
- php弹窗24小时一次,JS利用cookies设置每隔24小时弹出框
- Java 实例变量 和 实例方法 以及调用
- vc++2010注册表修改
- linux下的遥控器软件下载,万能遥控器软件
- 使用ResNet101作为预训练模型训练Faster-RCNN-TensorFlow-Python3-master
- R语言使用igraph包绘制网络图
- 基于CANoe的ECU Bootloader刷写软件
- Mysql插入数据 Incorrect string value: '\xF0\x9F\x98\x84
- python 老师_一个法语老师的python 入门之路
- 网站怎么被搜索引擎快速收录?
- java 刷题ide,力扣(LeetCode)刷题神器之Vs Code
- Python 之 Anaconda
- Juniper初始化之配置管理接口
- 国内CRM竞品分析【纷享销客 VS 销售易 VS 用友】
热门文章
- 2014年国外公布的中国内地大学排名18强名单
- PostgreSQL9.4: jsonb 性能测试 - Postgres2015全国用户大会--重磅嘉宾佳作分享(谭峰)
- Windows8 WiFi共享,让手机通过WiFi借用电脑有线网络上网
- c语言scanf s用法,C语言scanf与scanf_s
- 计算机网络实验报告二
- WIN10笔记本电脑任务栏wifi图标消失
- Student(3)——查询所有班级信息(上)
- java遍历文件夹的两种方式(递归和非递归)
- web前端期末大作业 html+css+javascript网页设计实例 企业网站制作
- wxWidgets:wxTreebook类的使用详解