zoukankan      html  css  js  c++  java
  • 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,'	')  # 循环打印 generator 中动态生成的 每一行数据
     n = n+1
     if(n==10):  # 如果打印 了 10 行 就停止打印
      break
      
    
      
      
     ##-----------------=============我是华丽的分割线=============-----------------##
    # 之前的注释 如下
    
    # 杨辉三角
    #   1
    # 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':0,'1':1,'2':2}
    
    printIterator(dict)
    
    printIterator("a,b,c,d")
    # -*- coding: utf-8 -*-
    from functools import reduce
    DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 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)+'
    ')
        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:\Usersxxx\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
        }
    如果有来生,一个人去远行,看不同的风景,感受生命的活力。。。
  • 相关阅读:
    Java语言中:float数据类型在内存中是怎么存储的?
    Java语言中:在数据类型的讲解中补充的几个小问题
    groovy : poi 导出 Excel
    php 基础入门篇之前言
    C 实现strcmp,strcpy,strcat函数
    CSDN 夏令营程序 试题分析 (3)
    HDU 1560 IDA*搜索
    iOS怎样找到自己的沙盒
    51系列小型操作系统精髓 简单实现2
    排序算法总结之折半插入排序
  • 原文地址:https://www.cnblogs.com/Frank99/p/8295464.html
Copyright © 2011-2022 走看看