What's the best way to find all possible combinations of a numeric string in Python and compare them with a given string?

huangapple go评论66阅读模式
英文:

What's the best way to find all possible combinations of a numeric string in Python and compare them with a given string?

问题

我不知道如何解决我的问题。我有一个字符串,像'0.0.0',我需要找到所有可能的组合,像'0.0.1','0.0.2'...... '9.9.9',然后与另一个字符串比较是否更大或不大。

现在我有这样的代码:

K = 1

res = []
for ele in version_string:

    if ele.isdigit():
        res.append(str(int(ele) + K))
        version_string = res
        version_string = ''.join(version_string)
    else:
        res.append(ele)

print(str(version_string))

输出

0.0
1.1
2.2
3.3
4.4
5.5
6.6

这段代码只是逐一递增每个数字,但我需要所有的组合。

谢谢

英文:

i've no idea how to resolve my problem. i ve a string like '0.0.0' and i need to find all possible combinination, like '0.0.1', '0.0.2'....... '9.9.9' then compare with another string if is bigger or no.
no i've code like this

K = 1

    res = []
    for ele in version_string:

        if ele.isdigit():
            res.append(str(int(ele) + K))
            version_string = res
            version_string = ''.join(version_string)
        else:
            res.append(ele)

    print(str(version_string))

output

0.0
1.1
2.2
3.3
4.4
5.5
6.6

this code only increment every number by one but i need all combination.

thanks

答案1

得分: 1

如果你想在没有额外模块的帮助下完成这个任务那么

    s = '0.0.0'
    
    def combos(s):
        w = s.count('.') + 1
        for x in range(10**w):
            yield '.'.join(f'{x:0{w}}')
    
    def func(s):
        for combo in combos(s):
            print(combo)
    
    func(s)
英文:

If you want to do this without the aid of additional modules then:

s = '0.0.0'

def combos(s):
    w = s.count('.') + 1
    for x in range(10**w):
        yield '.'.join(f'{x:0{w}}')

def func(s):
    for combo in combos(s):
        print(combo)

func(s)

答案2

得分: 0

import itertools

for numstr in ('.'.join(map(str, p)) for p in itertools.product(range(10), repeat=3)):
    print(numstr)
英文:
import itertools

for numstr in ('.'.join(map(str, p)) for p in itertools.product(range(10), repeat=3)):
    print(numstr)

huangapple
  • 本文由 发表于 2023年5月29日 17:22:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76356116.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定