首页 > 解决方案 > 从 0 和 1 的字符串创建一组字符串,其中只有两个字符被更改(python)

问题描述

假设我有以下字符串:'0000'

我想创建一组字符串,其中只有两个数字被更改(在这种情况下从 0 到 1)

例如从一个字符串'0000'我会得到一个结果:{'0011', '0101', '0110', '1001', '1010', '1100'}

这是我的代码:

def shift_two(string):
  shift_2 = set()
  for i in range(len(string)):
    if i == len(string) - 1:
      break

    str_temp = list(string)
    if str_temp[i] == '1':
      str_temp[i] = '0'
    else:
      str_temp[i] = '1'

    #copy a string, because list is mutable
    for j in range(i+1,len(string)):
      copy_str = str_temp.copy()

      if copy_str[j] == '1':
        copy_str[j] = '0'
        shift_2.add(''.join(copy_str))
      else:
        copy_str[j] = '1'
        shift_2.add(''.join(copy_str))

  return shift_2

但也许有更有效的方法(并且更具可读性)来完成这项任务?

标签: pythonstring

解决方案


这是一个使用[Python 3.Docs] 的变体: itertools - 创建迭代器以进行高效循环的函数

代码00.py

#!/usr/bin/env python

import sys
import itertools as it


def replace(s, replacements):
    if len(s) < len(replacements):
        return s
    base = s[:-len(replacements)] + "".join(replacements)
    return sorted(set("".join(i) for i in it.permutations(base, len(base))))


def main(*argv):
    s = "0000"
    repls = ("1", "1")
    l = list(replace(s, repls))
    print(l)


if __name__ == "__main__":
    print("Python {0:s} {1:d}bit on {2:s}\n".format(" ".join(item.strip() for item in sys.version.split("\n")), 64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    main(*sys.argv[1:])
    print("\nDone.")

输出

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q061258915]> "e:\Work\Dev\VEnvs\py_pc064_03.07.06_test0\Scripts\python.exe" code00.py
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] 64bit on win32

['0011', '0101', '0110', '1001', '1010', '1100']

Done.

推荐阅读