如何根据python中的模式生成数字 [英] How to generate numbers based on a pattern in python

查看:54
本文介绍了如何根据python中的模式生成数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须根据模式生成整数.
例如,我必须生成所有仅包含 4 和 0 且以一个或多个 4 开头并以零个或多个 0 结尾的数字
我只想要 Python (2.7) 中的代码.我不想检查模式.我想在模式中生成数字

解决方案

这应该有效:

[int("4"*i + "0"*(n-i)) for n in range(0,31) for i in range(1,n+1)]

它生成 465 个不同的整数:

4, 40, 44, 400, 440, ..., 4444444444444444444444444444440, 444444444444444444444444444444

On Edit:递归方法适用于更一般的情况:

def multiRepeats(chars,n,initial = True):字符串 = []如果 len(chars) == 0 或 n == 0:返回 [""]c = 字符[0]休息 = 字符 [1:]基数 = 1 如果初始否则为 0对于范围内的 i (base,n+1):头 = c * istrings.extend([head + tail for tail in multiRepeats(rest,n-i,False)])返回字符串def digitRepeats(digitString,n):return sorted([int(s) for s in multiRepeats(digitString,n)])

例如

<预><代码>>>>digitRepeats("420",4)[4, 40, 42, 44, 400, 420, 422, 440, 442, 444, 4000, 4200, 4220, 4222, 4400, 4420, 4422, 4440, 4444]

要回答您的原始帖子,请评估 digitRepeats("40",30)

I have to generate integers based on a pattern.
For example, I have to generate all the numbers that contain only 4's and 0's and that start with one or more 4's and end with zero or more 0's
I want code in Python (2.7) only. I don't want to check the pattern. I want to generate numbers in the pattern

解决方案

This should work:

[int("4"*i + "0"*(n-i)) for n in range(0,31) for i in range(1,n+1)]

It generates 465 distinct integers:

4, 40, 44, 400, 440, ..., 444444444444444444444444444440, 444444444444444444444444444444

On Edit: A recursive approach works in the more general case:

def multiRepeats(chars,n,initial = True):
    strings = []
    if len(chars) == 0 or n == 0: return [""]
    c = chars[0]
    rest = chars[1:]
    base = 1 if initial else 0
    for i in range(base,n+1):
        head = c * i
        strings.extend([head + tail for tail in multiRepeats(rest,n-i,False)])
    return strings

def digitRepeats(digitString,n):
    return sorted([int(s) for s in multiRepeats(digitString,n)])

For example

>>> digitRepeats("420",4)
[4, 40, 42, 44, 400, 420, 422, 440, 442, 444, 4000, 4200, 4220, 4222, 4400, 4420, 4422, 4440, 4442, 4444]

To answer your original post, evaluate digitRepeats("40",30)

这篇关于如何根据python中的模式生成数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆