簡體   English   中英

在 Python 中制作 n 唯一 l 長 0-1 系列

[英]Making n unique l long 0-1 series in Python

我想讓 n 隨機 l 長 0-1 系列,這樣它們都是不同的。 我試圖用while循環來制作它們,但效率很低。 我想知道是否有更好的方法來做到這一點。 (我寫了一個單獨的 function,它返回了 1 l 長的 0-1 系列,我在我的其他 function 中使用了它。)

import numpy as np
alph=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' ', '!', ',', '-', '.', ':', '?', ';','0','1','2','3','4','5','6','7','8','9']
class Error(Exception): 
    def __init__(self, text , data):
        self.text = text 
        self.data = data
        
    def __str__(self):
        return str(self.text)+str(self.data)
def key_gen(l):
    a = np.random.randint(2, size=(l))
    return ''.join([str(i) for i in a])
def dict_gen(k):
    if 2**k < len(alph):
        raise Error("There is not enough 0/1 series, can not assign different series to different letters, k is too small:", k)
    else:
        letter={}
        for i in alph:
            for j in alph:
                letter[i]=key_gen(k)
                while key[i]==key[j]:
                    letter[i]=key_gen(k)
      
        return letter

例如 3 個長 1-0 系列:010、100、111.... 我想制作一個這樣的字典,沒有 while 循環我有時會得到不同鍵的相同值。 如果您能幫助我更正我的代碼,我將不勝感激。

您編寫的代碼非常晦澀,並沒有描述您的整體問題。

alph的目的是什么? 只是n=len(alph) ,但即使這樣也不清楚,因為現在你運行一個長度為nxn的雙循環。 那么你想創造多少獨特的序列呢?

同樣對於長度為 3 的序列,只有 7 個 (2^3-1),但 len(alph) 比這長得多。 因此,您的代碼應該為您的示例引發異常“沒有足夠的 0/1 系列,不能將不同的系列分配給不同的字母,k 太小:3”

您顯示的代碼中的另一個問題是未定義key[] 你的意思是letter[]

也許是主要問題:你在 i, j 上運行了一個雙循環。 但是您只能根據密鑰i將結果保存在 map 中。

如果我不得不猜測你想要做什么,就是生成一個自動編碼/將alph中的字母編碼為某種唯一的 0-1 代碼(注意,這些代碼序列必須長於 3,更像int(math.log2(len(alph))) + 1 )。 如果我推測正確,您的else分支基本上應該是:

        letter={}
        for i in alph:
          newseq = key_gen(k)
          while newseq in letters.values():
            newseq = key_gen(k)
          letter[i] = newseq
        return letter

但如果我繼續推測,一個實際有效的方法是:

def dict_gen(alph):
  codes = list(range(len(alph)))
  # now scramble
  n_scramble = len(alph) * 5 # choose
  rngs = np.random.randint(len(alph), size=(n_scramble,2))
  for r in rngs: 
    codes[r[0]], codes[r[1]] = codes[r[1]], codes[r[0]]
  length = int(math.log2(len(alph))) + 1
  fmt = '{{0:0{}b}}'.format(length)
  letters = { c: fmt.format(codes[i]) for i,c in enumerate(alph) }
  return letters

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM