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评论91阅读模式
英文:

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',然后与另一个字符串比较是否更大或不大。

现在我有这样的代码:

  1. K = 1
  2. res = []
  3. for ele in version_string:
  4. if ele.isdigit():
  5. res.append(str(int(ele) + K))
  6. version_string = res
  7. version_string = ''.join(version_string)
  8. else:
  9. res.append(ele)
  10. print(str(version_string))

输出

  1. 0.0
  2. 1.1
  3. 2.2
  4. 3.3
  5. 4.4
  6. 5.5
  7. 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

  1. K = 1
  2. res = []
  3. for ele in version_string:
  4. if ele.isdigit():
  5. res.append(str(int(ele) + K))
  6. version_string = res
  7. version_string = ''.join(version_string)
  8. else:
  9. res.append(ele)
  10. print(str(version_string))

output

  1. 0.0
  2. 1.1
  3. 2.2
  4. 3.3
  5. 4.4
  6. 5.5
  7. 6.6

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

thanks

答案1

得分: 1

  1. 如果你想在没有额外模块的帮助下完成这个任务那么
  2. s = '0.0.0'
  3. def combos(s):
  4. w = s.count('.') + 1
  5. for x in range(10**w):
  6. yield '.'.join(f'{x:0{w}}')
  7. def func(s):
  8. for combo in combos(s):
  9. print(combo)
  10. func(s)
英文:

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

  1. s = '0.0.0'
  2. def combos(s):
  3. w = s.count('.') + 1
  4. for x in range(10**w):
  5. yield '.'.join(f'{x:0{w}}')
  6. def func(s):
  7. for combo in combos(s):
  8. print(combo)
  9. func(s)

答案2

得分: 0

  1. import itertools
  2. for numstr in ('.'.join(map(str, p)) for p in itertools.product(range(10), repeat=3)):
  3. print(numstr)
英文:
  1. import itertools
  2. for numstr in ('.'.join(map(str, p)) for p in itertools.product(range(10), repeat=3)):
  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:

确定