python编程玩具_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 的特性

deftriangel():

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=0for element intriangel():print(element,'\t') #循环打印 generator 中动态生成的 每一行数据

n = n+1

if(n==10): #如果打印 了 10 行 就停止打印

break

##-----------------=============我是华丽的分割线=============-----------------###之前的注释 如下

#杨辉三角#1#1 1#1 2 1

#使用 yield 来制造 generator 动态的扩展

deftriangel():#定义第一行

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=0for element intriangel():print(element)

n=n+1

if(n==10):breakt.append(element)print()for e int:print(e)

杨辉三角

#-*- coding: utf-8 -*-

deftriangles():

l=[1]whileTrue:yieldl

l.append(0)

l= [ l[i-1]+l[i] for i inrange(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 intriangles():print(t)

results.append(t)

n= n + 1

if n == 10:break

#print(results)

for i,e inenumerate(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, 双击吧 老铁!deftriangle(max):

l=[1]

n=0whileTrue:yieldl

l.append(0)

l=[l[i-1]+l[i] for i inrange(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

exceptStopIteration 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)

#第一种写法使用函数式编程

defpower(x):return x*x

l=[i for i in range(10)]for e inlist(map(power,l)):print(e)print('')#第二种写法 使用列表生成式

l=[x*x for x in range(10)]for e inl:print(e)

deftrim(s):if bool([x for x in s if x is not ' ']) is notTrue:return ''

#TypeError

while s[0] is ' ':

s= s[1:]while s[-1] is ' ':

s= s[:-1]returns#测试:

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 importIterabledefprintIterator(itera):ifisinstance(itera,Iterable):print(type(itera))for e initera:print(e)else:raiseValueError

l=list(range(10))

printIterator(l)print('')

dict={'0':0,'1':1,'2':2}

printIterator(dict)

printIterator("a,b,c,d")

#-*- coding: utf-8 -*-

from functools importreduce

DIGITS= {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}#分析 整数位 与 小数位 分别 对待 就可以

defstr2float(s):

wholeNum= s.split('.',1)

intDigt=wholeNum[0]

decimalDigt= wholeNum[1]#整数部分处理

defintDigtFunc(x,y):return x * 10 +ydefintDigitStr2Decimal(intDigt):returnreduce(intDigtFunc,map(lookUpValue,intDigt))#小数部分处理

defpower(x,y):

n=1mul=1

while n<=y:

mul=mul*x

n=n+1

returnmuldeflookUpValue(ch):returnDIGITS[ch]#做两次 相加

defparseDecimalDigt(s):returnmap(lookUpValue,s)defdecimalDigitStr2Decimal(decimalDigt):

sum=0.0

for i, value inenumerate(parseDecimalDigt(decimalDigt)):#print(i,'--> ',value)

#print(power(10,i+1))

sum = sum + value*1.0/(power(10,i+1))returnsum#将处理后的 整数, 小数部分 加起来

finalResult=intDigitStr2Decimal(intDigt)+decimalDigitStr2Decimal(decimalDigt)print(finalResult)returnfinalResult

str2float('123.456')

#-*- coding: utf-8 -*-

def_mt3odd_seq_generator():

n= 1

whileTrue:

n= n+2

yieldndeffn(n):return lambda itValue: itValue % n >0#获取素数生成器

defprimes():yield 2 #2 作为一个特殊的素数需要被缓存

it = _mt3odd_seq_generator() #初始化大于3的序列

#开始疯狂筛选

whileTrue:#将筛选后的序列的第一个数 缓存

n = next(it) #3,5,7.....

yieldn#开始循环过滤 n 的倍数的 那些数字,并且筛掉后构造一个新的序列返回给 it

it =filter(fn(n),it)for e inprimes():if e >= 30:break

else:print('e:',e)

#-*- coding: utf-8 -*-

defis_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 -*-

importosdefreplaceStrInFile(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_nameprint('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')exceptIOError:print('IO Error!')defmodify_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')

packagecom.yli.utils;import java.io.*;

classFileUtils {public static voidmain(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=newFile(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 voidreplaceStrInFile(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(newFileReader(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

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值