zoukankan      html  css  js  c++  java
  • python 常用小程序汇总

    1、生成指定位数的随机字符串

    # -*- coding:utf-8 -*-
    import random
    def my_char(length):
        s=" abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKL MNOPQRSTUVIXYZ!aN$x*6*( )?"
        p = "" .join(random.sample(s,length ))
        return p
    
    a = my_char(5)
    print(a)
    
    


    2、猜数字游戏

    在这个游戏中,任务是创建一个脚本,能够在一个范围内生成一个随机数。如果用户在三次机会中猜对了数字,那么用户赢得游戏,否则用户输。

    import random
    number = random.randint(1, 20)
    print(number)
    
    for i in range(0, 3):
        user = int(input("guess the number:
    "))
        if user ==number:
            print("Nice")
            print("you guess the number right it's {}".format(number))
        elif user > number:
            print("you guess is too high")
        elif user < number:
            print("you guess is too low")
    else:
        print("没机会了...")
    


    3、已知一个字符串 "hello_world_test" ,如何得到一个列表 ["hello","world","test"]

    使用split方法:
    在Python的高级特性里有切片(split)操作符,可以对字符串进行截取。

    语法
    看一下源码:

        def split(self, *args, **kwargs): # real signature unknown
            """
            Return a list of the words in the string, using sep as the delimiter string.
            # 使用sep作为分隔符字符串,返回字符串中的单词列表
            # 有两个参数:sep, maxsplit
              sep
                The delimiter according which to split the string.  # 用于拆分字符串的分隔符。
                None (the default value) means split according to any whitespace,
                and discard empty strings from the result.
              maxsplit
                Maximum number of splits to do.
                # 分割次数
                -1 (the default value) means no limit.
            """
            pass
    

    例子1

    t = "Baidu JD Taobao Facebook"
    print(t.split())
    
    # 结果:
    # ['Baidu', 'JD', 'Taobao', 'Facebook']
    

    结论:当不带参数时,默认是以空字符作为参数进行分割,空字符全部被分割。

    例子2

    t = "Baidu JD Taobao Facebook"
    print(t.split(" ", 1))
    
    # 结果:
    # ['Baidu', 'JD Taobao Facebook']
    

    结论: 以 空格 为分隔符,指定第二个参数为 1,返回两个参数列表。

    所以题目的答案:

    test = "hello_world_test"
    print(test.split("_"))
    
    # 结果:
    # ['hello', 'world', 'test']
    


    4、编程输出1/1+1/3+1/5...1/99的和

    #coding=utf-8
    def mysum(num):
        sum=0
        for i in range(num):
            if(i%2) == 1:
                sum=sum+1/i
        return sum
    
    if __name__=='__main__':
        res=mysum(100)
    
  • 相关阅读:
    web服务器-Apache
    nginx优化
    nginx下载限速
    nginx-URL重写
    HDU 5358 First One 求和(序列求和,优化)
    HDU 5360 Hiking 登山 (优先队列,排序)
    HDU 5353 Average 糖果分配(模拟,图)
    UVALive 4128 Steam Roller 蒸汽式压路机(最短路,变形) WA中。。。。。
    HDU 5348 MZL's endless loop 给边定向(欧拉回路,最大流)
    HDU 5344 MZL's xor (水题)
  • 原文地址:https://www.cnblogs.com/wwho/p/15393929.html
Copyright © 2011-2022 走看看