Python入门练习题(5)-随机数生成器

设计一个函数,生成一段由大小写英文字母(a-z , A-Z)和阿拉伯数字(0-9)组成的随机字符串。
如:

  • 1aK3B5aL2
  • 64akGIKA14a54
  • KD123Hasd12Ad

随机字符串中,整体长度可以自己指定,但数字、大写字母、小写字母的长度和排列顺序要求是随机的。

下面的程序展现的时两种思想。

import random

# 方法一
def random_albt(count):
    length = 0
    while length < count:
        select = random.choice(range(1, 4))
        if select == 1:
            a = random.choice(range(1, 10))
            print(a, end="")
        if select == 2:
            b = random.choice(range(65, 90))
            print(chr(b), end="")
        if select == 3:
            c = random.choice(range(97, 122))
            print(chr(c), end="")
        length += 1

# 方法二
def random_albt2(count):
    s = list(map(lambda x: str(x), range(10))) + \
        list(map(lambda x: chr(x), range(65, 90))) + \
        list(map(lambda x: chr(x), range(97, 122)))
    string = []
    while count > 0:
        current_len = random.randint(0, count)
        string += random.sample(s, current_len)
        count -= current_len
    return "".join(string)


count = int(input("Please input the length you want:"))
#random_albt(count)
print(random_albt2(count))

其中,random.sample()可以从指定的序列中,随机的截取指定长度的片断,不作原地修改。

list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 从list中随机获取5个元素,作为一个片断返回  
slice = random.sample(list, 5)  
print slice  
# 原有序列并没有改变。
print list   

2018.8.11

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值