关于切片/截取(slice)和random模块的使用(实例:猜单词小游戏)

本文详细介绍了一个基于Python的猜单词游戏,包括游戏的实现原理、random模块和切片操作的使用,以及两种不同的游戏版本play.py和test.py的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

切片和random的使用在源码中都有注释(可以直接下载):https://github.com/NoobZeng/GuessWords

1. README.MD

  • 基于Python的猜单词游戏
  • 猜单词小游戏
  • 主要使用random模块、切片slice
  • random模块的基础使用:demo_random.py
  • 切片的基础使用:demo_slice.py
  • 游戏运行play.py或者test.py
  • play和test不同地方是乱序单词的组合,前者用random.randrange()和切片的方式,后者使用random.sample()和join方法的方式

2. 切片的简单使用

# !/usr/bin/env python
# ! _*_ coding:utf-8 _*_
# @TIME   : 2019/9/10  6:13
# @Author : Noob
# @File   : demo_slice.py

# python中符合序列的有序序列都支持切片(slice)
# 如:字符串、列表(list)、元祖(tuple)
# 格式:[start: end: step]
# start:起始索引,从0开始,-1表示结束
# end:结束索引,切片结果不包含结束索引,即不包含最后一位,-1代表最后一个位置索引
# step:步长,可以不提供,默认值是1,但是值不能为0,不然会报错ValueError: slice step cannot be zero
# end-start=正数时,从左向右取值,end-start=负数时,反向取值

"""
举例:字符串
"""
str_slice = "python"

print("1. 全部截取")
str1 = str_slice[:]
print(str1)
# python

print("2. 从0开始到3,每次增加1截取,不包含索引结束的位置")
str2 = str_slice[0: 3: 1]
print(str2)
# pyt

print("3. 从0到倒数第二位,每次增加2截取,不包含索引结束的位置")
str3 = str_slice[0: -1: 2]
print(str3)
# pto

print("4. 默认从起始位置索引,每次增加1截取,结束索引为3,省略步长")
str4 = str_slice[: 3]
print(str4)
# pyt

print("5. 反向取值,每次增加1截取,不包含索引结束位置")
str5 = str_slice[3: 0: -1]
print(str5)
# hty

print("6. 从索引3开始到结束索引,省略步长1")
str6 = str_slice[3:]
print(str6)
# hon
demo_slice.py

3. random模块的简单使用

# !/usr/bin/env python
# ! _*_ coding:utf-8 _*_
# @TIME   : 2019/9/10  6:13
# @Author : Noob
# @File   : demo_random.py

import random

# 1. 生成一个随机小数n,n大于等于0小于1.0
print("1. random.random():生成一个随机小数n,n大于等于0小于1.0")
n = random.random()
print(n)

# 2. 生成一个指定范围内的小数,两个参数中一个是上限一个是下限
# 如果a<b,则生成的随机数n的范围在a<=n<=b
# 如果a>b,则生成的随机数n的范围在b<=n<=a
print("2. random.uniform(a, b):生成一个指定范围内的小数,两个参数中一个是上限一个是下限")
n = random.uniform(10, 20)
print(n)
n = random.uniform(20, 15)
print(n)

# 3. 生成一个指定范围内的整数,其中参数a是下限,参数b是上限,生成的随机数范围在a<=n<=b
print("3. random.randint(a, b):生成一个指定范围内的整数")
n = random.randint(5, 9)
print(n)

# 4. 从指定范围内按指定基数递增的集合中获取一个随机数(有点类似于有序列表的切片),start包含在范围内,stop不包含在范围内
print("4. random.randrange([start], stop[, step]):从指定范围内按指定基数递增的集合中获取一个随机数")
n = random.randrange(2, 10, 3)
print(n)

# 5. 重序列中获取一个随机元素,其原型为random.choice(sequence),参数sequence标识一个有序类型。泛指序列数据结构,
# 字符串、列表、元祖都属于sequence。
print("5. random.choice(sequence):从序列中获取一个随机元素")
n = random.choice("hello world")
print(n)
n = random.choice(("java", "C", "C++", "php"))
print(n)
n = random.choice(["java", "C", "C++", "php"])
print(n)

# 6. 打乱列表中的元素,shuffle()返回的是none,只是该函数改变了原列表数据的顺序
print("6. random.shuffle(x[, random):打乱列表中的元素")
a = [1, 2, 3, 4, 5]
n = random.shuffle(a)
print(n)  # None
print(a)

# 7. 从指定序列中随机获取指定长度的片段,sample()函数不会修改原有序列
print("7. random.sample(sequence,k):从指定序列中随机获取指定长度的片段")
a = "abcdefg"
n = random.sample(a, 3)
print(n)
print(a)
demo_random.py

4. 猜单词游戏(1)play.py

# !/usr/bin/env python
# ! _*_ coding:utf-8 _*_
# @TIME   : 2019/9/10  3:51
# @Author : Noob
# @File   : play.py

# 导入random模块
import random

# 创建单词序列
words = ("python", "java", "peal", "vue", "http", "javascript", "php", "cplus")

# 开始游戏
print(
    """
    欢迎参加猜单词游戏
    把字母组合成一个正确的单词
    """
)

iscontinue = "y"

while iscontinue == 'y' or iscontinue == 'Y':
    # 从序列中随机抽出一个单词
    word = random.choice(words)
    # 一个用于判断玩家是否才对的变量
    correct = word
    # 创建乱序后单词
    jumble = ""
    while word:  # word不是空串循环
        # 根据word长度产生word的随机位置
        position = random.randrange(len(word))
        # 将position位置的字母组合到乱象需后单词
        jumble += word[position]
        # 通过切片将position位置的字母从元单词中
        word = word[:position] + word[(position+1):]
    print("乱序后单词:", jumble)

    guess = input("\n请你猜:")
    while (guess != correct and guess != "") or (guess == ""):
        print("对不起不正确.")
        guess = input("继续猜:")
    if guess == correct:
        print("真棒,你猜对了!")
    iscontinue = input("\n是否继续(Y/N):")
play.py

5. 猜单词游戏(2)test.py

# !/usr/bin/env python
# ! _*_ coding:utf-8 _*_
# @TIME   : 2019/9/10  22:16
# @Author : Noob
# @File   : test.py

import random

# 开始游戏
print(
    """
    欢迎参加猜单词游戏
    把字母组合成一个正确的单词
    """
)

# 判断游戏是否继续的标识
iscontinue = "y"
words = ["fiddler", "myeclipse", "pycharm", "sumblim", "jmeter", ""]
# 去掉单词库中的空字符串
# words = list(filter(None, words))

while iscontinue == "y" or iscontinue == "Y":
    # 判断词库列表长度
    if len(words) != 0:
        # 随机抽取一个单词
        word = random.choice(words)
        # 词库出现为空的单词就跳过
        if word == "" and len(words) != 1:
            continue
        elif word == "" and len(words) == 1:
            print("单词已经全部猜完,结束游戏!!!")
            break
        # random.sample(sequence, k):随机获取指定长度的序列片段,得到的是一个数组,且不会修改到原序列
        # 通过join方法重新拼合成一个字符串,是乱序后的单词
        jumple = "".join(random.sample(word, len(word)))
        print("\n" + jumple)
        # 用于判断输入单词是否正确的标识
        correct = input("请输入该单词的正确拼写:")
        while correct != word:
            correct = input("猜错了,请思考后继续:")
        print("恭喜猜对了!!!")
        # 猜完后将该单词移出列表
        words.remove(word)
        if len(words) != 0:
            iscontinue = input("是否继续(Y/N):")
    else:
        print("单词已经全部猜完,结束游戏!!!")
        break
test.py

转载于:https://www.cnblogs.com/noobzeng/p/11508400.html

### 时间序列数据增强方法 时间序列数据增强是指通过各种技术手段来增加可用的数据量或改变现有数据的形式,从而提高机器学习模型的泛化能力性能。具体到多频时间序列,在本研究中,根据特定公式将三个不同频率的时间序列组合成一个多频时间序列,其中参数设定为 \( k_1=88 \),\( k_2=222 \),\( k_3=333 \)[^1]。 #### 方法一:噪声注入 一种常见的做法是在原始信号上叠加随机生成的小幅度高斯白噪音或其他类型的扰动项。这种方法简单易行,能够有效提升网络对于微弱变化的学习能力。 ```python import numpy as np def add_noise(ts, noise_level=0.05): """Add Gaussian white noise to time series.""" return ts + noise_level * np.random.normal(size=len(ts)) ``` #### 方法二:时间扭曲(Time Warping) 通过对某些局部区域内的采样点进行拉伸或压缩操作,模拟实际场景下可能出现的速度波动情况。这有助于改善模型应对非线性变换的能力。 ```python from scipy.interpolate import interp1d def time_warp(ts, sigma=0.2, knot=4): """Apply random warping on a given timeseries""" orig_steps = np.arange(len(ts)) start_points = sorted(np.random.choice(orig_steps[:-knot], size=knot, replace=False)) end_points = [p + int((np.random.rand() - 0.5) * sigma * len(ts)) for p in start_points] wp = np.linspace(start_points[0], end_points[-1], num=len(ts)).astype(int) f = interp1d(wp, ts[start_points]) warped_ts = f(orig_steps).clip(min=-1e6,max=1e6) return warped_ts.tolist() ``` #### 方法三:窗口切片(Window Slicing) 从较长的时间序列片段中截取较短子串作为新的样本输入给定模型训练使用;也可以反过来拼接多个相邻但不重叠的小段形成更长的新实例。 ```python def window_slice(ts, win_size_ratio=(0.1, 0.9)): """Slice windows from original sequence with varying sizes""" low_bound, up_bound = map(lambda x: int(x*len(ts)), win_size_ratio) slice_len = np.random.randint(low_bound,up_bound+1) start_idx = np.random.randint(0,len(ts)-slice_len+1) sliced_part = ts[start_idx:start_idx+slice_len] return padded_sequence(sliced_part, length=len(ts)) ``` 以上三种方式均可以单独应用亦或是联合起来共同作用于同一组或多组时间序列之上,以此达到更好的效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值