python 玩具代码
脚本语言的第一行,目的就是指出,你想要你的这个文件中的代码用什么可执行程序去运行它,就这么简单
#!/usr/bin/python是告诉操作系统执行这个脚本的时候,调用/usr/bin下的python解释器;
#!/usr/bin/env python这种用法是为了防止操作系统用户没有将python装在默认的/usr/bin路径里。当系统看到这一行的时候,首先会到env设置里查找python的安装路径,再调用对应路径下的解释器程序完成操作。
#!/usr/bin/python相当于写死了python路径;
#!/usr/bin/env python会去环境设置寻找python目录,推荐这种写法
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
s = (x * x for x in range(5))
print(s)
for x in s:
print(x)
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
return 'done'
f = fib(10)
print('fib(10):', f)
for x in f:
print(x)
# call generator manually:
g = fib(5)
while 1:
try:
x = next(g)
print('g:', x)
except StopIteration as e:
print('Generator return value:', e.value)
break
# 1 杨辉三角
# / \
# 1 1
# / \ / \
# 1 2 1
# / \ / \ / \
# 1 3 3 1
# / \ / \ / \ / \
# 1 4 6 4 1
# / \ / \ / \ / \ / \
# 1 5 10 10 5 1 # 数学规律就是 上一行错位相加 得到 当前行的 每一列的值 # 该方法本质是利用 杨辉三角的数学规律以及 yield 去动态扩展 generator 的特性
def triangel():
l=[1] # 定义第一行元素
while True: # 开启死循环来 动态扩展 generator 注意: 进入 while 循环认为 的 list 认为是保存当前行的 list
yield l # 每次都会把 l 这个 list 里保存的上一行的数据先缓存到 generator 里(这时候 l 还没有进行数学规律的运算 也就是还没有涉及到当前行)
l.append(0) # 将上一行 最末 补 0
l =[l[i]+l[i-1] for i in range(len(l))] # 此处对当前行进行数学规律运算 循环得到 当前行 每一列的值 l[-1] 取到 最后 一个元素 l 是 L 的小写 # 以上方法完毕 # 下面利用 n 来控制动态 generator 生成器 生成多少行
n=0
for element in triangel():
print(element,'\t') # 循环打印 generator 中动态生成的 每一行数据
n = n+1
if(n==10): # 如果打印 了 10 行 就停止打印
break ##-----------------=============我是华丽的分割线=============-----------------##
# 之前的注释 如下 # 杨辉三角
#
# 1 1
#1 2 1 # 使用 yield 来制造 generator 动态的扩展
def triangel():
# 定义第一行
L=[1] # 1 第一行的元素
while True: # 死循环来动态生成
yield L # 每次循环都用 yield 来保存 每行 List 到 generator
L.append(0) # 在上一行 List 里补上一个元素 0 用来能够恰好错位相加得到 当前行的值
L=[L[i-1]+L[i] for i in range(len(L))] #制造 当前行,这是一个 循环的 过程那么根据什么来循环比较好呢,当然 是根据 上一行补 0 的长度来计算当前行每个元素的值
#而规律我们是知道的,当前行的某一个元素等于上一行的特定的两个元素相加(你懂的)
#可以写一个公式,当前行的第n个元素 L(currentRow)[n]刚好等于 上一行第 n 列加上 上一行 第 n-1 列的值 L[currentRow-1](n) + L[currentRow-1](n-1) t=[]
n=0
for element in triangel():
print(element)
n=n+1
if(n==10):
break
t.append(element) print() for e in t:
print(e)
杨辉三角
# -*- coding: utf-8 -*- def triangles():
l=[1]
while True:
yield l
l.append(0)
l= [ l[i-1]+l[i] for i in range(0,len(l))]
# return 'finally finshied!'
# 期待输出:
# [1]
# [1, 1]
# [1, 2, 1]
# [1, 3, 3, 1]
# [1, 4, 6, 4, 1]
# [1, 5, 10, 10, 5, 1]
# [1, 6, 15, 20, 15, 6, 1]
# [1, 7, 21, 35, 35, 21, 7, 1]
# [1, 8, 28, 56, 70, 56, 28, 8, 1]
# [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
n = 0
results = []
for t in triangles():
print(t)
results.append(t)
n = n + 1
if n == 10:
break
#print(results)
for i,e in enumerate(results):
if i!=len(results)-1 :
del e[-1] print(results)
if results == [
[1],
[1, 1],
[1, 2, 1],
[1, 3, 3, 1],
[1, 4, 6, 4, 1],
[1, 5, 10, 10, 5, 1],
[1, 6, 15, 20, 15, 6, 1],
[1, 7, 21, 35, 35, 21, 7, 1],
[1, 8, 28, 56, 70, 56, 28, 8, 1],
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
]:
print('测试通过!')
else:
print('测试失败!')
杨辉三角全
这一波 666 , 双击吧 老铁!
def triangle(max):
l=[1]
n=0
while True:
yield l
l.append(0)
l=[l[i-1]+l[i] for i in range(len(l))]
n=n+1
if(n==max):
return "done" g=triangle(10)
count=1
while 1:
try:
x=next(g)
print("第 %d 行的值为 %s"%(count,x))
count=count+1
except StopIteration as e:
print("generator value: ",e.value)
break
# 斐波拉契
# 1,1,2,3,5,8..... def fib(max):
n=0
a=0
b=1
while n<=max:
a,b = b,a+b
n = n+1
return b for i in range(10):
print(fib(i))
# 斐波拉契 生成器写法
# 1,1,2,3,5,8..... def fib(max):
n=0
a=0
b=1
while n<=max:
yield b
a,b = b,a+b
n = n+1 for i in (fib(10)):
print(i)
# 第一种写法使用函数式编程
def power(x):
return x*x l=[i for i in range(10)]
for e in list(map(power,l)):
print(e) print('') # 第二种写法 使用列表生成式
l=[x*x for x in range(10)]
for e in l:
print(e)
def trim(s):
if bool([x for x in s if x is not ' ']) is not True:
return ''
#TypeError
while s[0] is ' ':
s = s[1:]
while s[-1] is ' ':
s = s[:-1]
return s # 测试:
if trim('hello ') != 'hello':
print('测试失败!')
elif trim(' hello') != 'hello':
print('测试失败!')
elif trim(' hello ') != 'hello':
print('测试失败!')
elif trim(' hello world ') != 'hello world':
print('测试失败!')
elif trim('') != '':
print('测试失败!')
elif trim(' ') != '':
print('测试失败!')
else:
print('测试成功!')
from collections import Iterable
def printIterator(itera):
if isinstance(itera,Iterable):
print(type(itera))
for e in itera:
print(e)
else:
raise ValueError l=list(range(10))
printIterator(l) print('') dict={'':0,'':1,'':2} printIterator(dict) printIterator("a,b,c,d")
# -*- coding: utf-8 -*-
from functools import reduce
DIGITS = {'': 0, '': 1, '': 2, '': 3, '': 4, '': 5, '': 6, '': 7, '': 8, '': 9}
# 分析 整数位 与 小数位 分别 对待 就可以
def str2float(s):
wholeNum = s.split('.',1)
intDigt = wholeNum[0]
decimalDigt = wholeNum[1] # 整数部分处理
def intDigtFunc(x,y):
return x * 10 + y
def intDigitStr2Decimal(intDigt):
return reduce(intDigtFunc,map(lookUpValue,intDigt)) # 小数部分处理
def power(x,y):
n=1
mul=1
while n<=y:
mul=mul*x
n=n+1
return mul def lookUpValue(ch):
return DIGITS[ch]
# 做两次 相加
def parseDecimalDigt(s):
return map(lookUpValue,s) def decimalDigitStr2Decimal(decimalDigt):
sum=0.0
for i, value in enumerate(parseDecimalDigt(decimalDigt)):
# print(i,'--> ',value)
# print(power(10,i+1))
sum = sum + value*1.0/(power(10,i+1))
return sum # 将处理后的 整数, 小数部分 加起来
finalResult=intDigitStr2Decimal(intDigt)+decimalDigitStr2Decimal(decimalDigt)
print(finalResult)
return finalResult str2float('123.456')
# -*- coding: utf-8 -*-
def _mt3odd_seq_generator():
n = 1
while True:
n = n+2
yield n def fn(n):
return lambda itValue: itValue % n > 0 # 获取素数生成器
def primes():
yield 2 # 2 作为一个特殊的素数需要被缓存
it = _mt3odd_seq_generator() # 初始化大于3的序列
#开始疯狂筛选
while True:
#将筛选后的序列的第一个数 缓存
n = next(it) # 3,5,7.....
yield n
# 开始循环过滤 n 的倍数的 那些数字,并且筛掉后构造一个新的序列返回给 it
it = filter(fn(n),it) for e in primes():
if e >= 30:
break
else:
print('e: ',e)
# -*- coding: utf-8 -*-
def is_palindrome(s):
return s==int(str(s)[::-1]) # 测试:
output = filter(is_palindrome, range(1, 1000))
print('1~1000:', list(output))
if list(filter(is_palindrome, range(1, 200))) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]:
print('测试成功!')
else:
print('测试失败!')
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
def replaceStrInFile(file_name,old_str,new_str,extension_name):
print('file name: ',file_name)
paths = os.path.split(file_name)
file_name_new = paths[0]+'\\'+ paths[1][:paths[1].rindex(extension_name)]+'_new'+extension_name
print('file new name: ',file_name_new)
try:
with open(file_name,'r') as fsR:
line = fsR.readline()
with open(file_name_new,'a') as fsW:
while line: # len(line) != 0
print(line.replace(old_str,new_str))
line = fsR.readline()
print('line: '+line)
fsW.write(line.replace(old_str,new_str)+'\n')
except IOError:
print('IO Error!') def modify_specified_directory(dir_path,old_str,new_str,extension_name):
for file_name in [x for x in os.listdir(dir_path) if os.path.isfile(dir_path+'\\'+x) and os.path.splitext(x)[1]==extension_name]:
print('absolute path: '+dir_path+'\\'+file_name)
replaceStrInFile(dir_path+'\\'+file_name,old_str,new_str,extension_name) modify_specified_directory('C:\\Users\xxx\\Desktop\\test','th>','td>','.txt')
package com.yli.utils;
import java.io.*; class FileUtils {
public static void main(String[] args){
System.out.println("start to convert file encoding...");
String srcPath="C:\\Users\\行行行\\Desktop\\天津样例数据\\rest";
String tarPath="C:\\Users\\xxx\\Desktop\\天津样例数据\\rest\\in";
File file=new File(srcPath);
if(file.exists()){
//如果传进来的参数是文件夹
if(file.isDirectory()){
File[] fileList=file.listFiles();
for(File f:fileList){
System.out.println("start to convert file "+f.getName()+" from other encoding to UTF-8");
replaceStrInFile("th>",f,"td>",tarPath);
}
}
else{ //传进来的是个文件名
System.out.println("start to convert file "+file.getName()+" from other encoding to UTF-8");
System.out.println(file.getAbsoluteFile());
replaceStrInFile("th>",file,"td>",tarPath);
}
}
else throw new RuntimeException("The file or file folder doesn't exist!!! please check!!!");
} public static void replaceStrInFile(String oldStr, File file, String newStr, String tarPath) {
// if(!(Charset.isSupported(srcCharset))) throw new UnsupportedCharsetException(srcCharset);
BufferedReader fileBufRead=null;
BufferedWriter fileBufWrite=null;
String line=null;
String realFileName=file.getName();
try{
fileBufRead=new BufferedReader(new FileReader(file));
fileBufWrite=new BufferedWriter(new FileWriter(tarPath+"\\"+realFileName));
System.out.println("abs file path: "+file.getAbsoluteFile());
while((line=fileBufRead.readLine())!=null){
if(line.indexOf("th>")!=-1){
line=line.replace(oldStr,newStr);
}
fileBufWrite.write(line,0,line.length());
fileBufWrite.flush();
fileBufWrite.newLine();
//System.out.println(line);
} }
catch(IOException ioe){
ioe.getCause();
}
finally{
if(fileBufRead!=null)
try{
fileBufRead.close();
}
catch(IOException ioe){ ioe.printStackTrace();}
}
}
// todo
}
python 玩具代码的更多相关文章
- Python一行代码
1:Python一行代码画出爱心 print]+(y*-)**-(x**(y*<= ,)]),-,-)]) 2:终端路径切换到某文件夹下,键入: python -m SimpleHTTPServ ...
- python爬虫代码
原创python爬虫代码 主要用到urllib2.BeautifulSoup模块 #encoding=utf-8 import re import requests import urllib2 im ...
- Python小代码_2_格式化输出
Python小代码_2_格式化输出 name = input("name:") age = input("age:") job = input("jo ...
- Python小代码_1_九九乘法表
Python小代码_1_九九乘法表 max_num = 9 row = 1 while row <= max_num: col = 1 while col <= row: print(st ...
- Python IDLE 代码高亮主题
Python IDLE 代码高亮主题 使用方法: 打开C盘我的 C:\Documents and Settings\你的用户名.idlerc文件夹 里面会有一个 config-highlight.cf ...
- 代码块: 以冒号作为开始,用缩进来划分作用域,这个整体叫做代码块,python的代码块可以提升整体的整齐度,提高开发效率
# ### 代码块: 以冒号作为开始,用缩进来划分作用域,这个整体叫做代码块 if 5 == 5: print(1) print(2) if True: print(3) print(4) if Fa ...
- uiautomatorviewer 优化定位符生成,支持生成Java,Python自动化代码
项目介绍 二次开发 uiautomatorviewer 优化定位符生成,支持生成Java,Python自动化代码,修复自带工具画面有动态加载时截图失败问题,优化自带工具截图速度 ,实现类似录制脚本功能 ...
- Python实现代码统计工具——终极加速篇
Python实现代码统计工具--终极加速篇 声明 本文对于先前系列文章中实现的C/Python代码统计工具(CPLineCounter),通过C扩展接口重写核心算法加以优化,并与网上常见的统计工具做对 ...
- Python静态代码检查工具Flake8
简介 Flake8 是由Python官方发布的一款辅助检测Python代码是否规范的工具,相对于目前热度比较高的Pylint来说,Flake8检查规则灵活,支持集成额外插件,扩展性强.Flake8是对 ...
随机推荐
- <转>性能测试浅谈
本文主要针对WEB系统的性能测试.不涉及具体的执行操作,只是本人对性能测试的一点理解和认识. 性能测试的目的,简单说其实就是为了获取待测系统的响应时间.吞吐量.稳定性.容量等信息.而发现一些具体的性能 ...
- 通过C#的HttpClient模拟form表单请求
post提交表单一般无非是一般text文本和文件类型,如下 <input type="file"/> <input type="text"/& ...
- 基于tensorflow使用全连接层函数实现多层神经网络并保存和读取模型
使用之前那个格式写法到后面层数多的话会很乱,所以编写了一个函数创建层,这样看起来可读性高点也更方便整理后期修改维护 #全连接层函数 def fcn_layer( inputs, #输入数据 input ...
- java第二次实验报告
课程:Java实验 班级:201352 姓名:池彬宁 学号:20135212 成绩: 指导教师:娄佳鹏 实验日期:15.05.05 实验密级: ...
- 软件工程课程设计——第一个Spring
开发会议框架表格: 1.我们团队Reborn针对需求功能进行热烈的讨论会议,从功能的方面分析开发,结合在一起组合为App软件,再另外思考附加的功能性娱乐项目. 2.开发过程中,以表格的形式反思开发过程 ...
- Final版本发布评论
1.飞天小女警组做的礼物挑选小工具,相比较beta版本并没有太大的改动,新增添了“猜你喜欢”模块,在最后给出的礼物推荐下面会给出三个猜你喜欢的礼物.这样解决了推荐礼物的单一,也让礼物推荐变得更有趣了. ...
- Installing OpenSSH from the Settings UI on Windows Server 2019 or Windows 10 1809
Installing OpenSSH from the Settings UI on Windows Server 2019 or Windows 10 1809 OpenSSH client and ...
- 深入理解Java反射+动态代理
答: 反射机制的定义: 是在运行状态中,对于任意的一个类,都能够知道这个类的所有属性和方法,对任意一个对象都能够通过反射机制调用一个类的任意方法,这种动态获取类信息及动态调用类对象方法的功能称为j ...
- 实体框架自定义代码优先约定(EF6以后)
仅限EF6仅向前 - 此页面中讨论的功能,API等在实体框架6中引入.如果您使用的是早期版本,则部分或全部信息不适用. 使用Code First时,您的模型是使用一组约定从您的类计算的.默认的Code ...
- 【设计模式】—— 创建者模式Builder
前言:[模式总览]——————————by xingoo 模式意图 一个对象的创建十分复杂,为了区分构建过程和使用过程,因此分开.使用一个Director类进行对象的创建,Builder规定了这个创建 ...