2012-03-21 69 views
-2

我不知道如何有效地提出這個問題,但是我需要做的是將整數值賦給字符,使得字符的加入不等於第一個加上第二個,而不是序列中的下一個數字。如何在不添加asciis的情況下將整數值賦給Python

例如:

如果我使用ASCII值AZ設置爲1-26,然後,如果我有串ab總和將是3 不過,我想ab被分配27ac = 28ad = 29等。

所以a = 1az = 51(而不是27,如果我根本a + z

我不知道這是否會影響到康迪的解決方案,但一個tions是字符串中的字母必須按字母順序排列,因此字符串可以是「abc」,但不能是「cat

謝謝!

+3

家庭作業?你是否禁止「aa」作爲你的字母順序標準的一部分? – DSM 2012-03-21 15:01:34

+0

我不完全瞭解這些要求。 '「z」'和'「aa」'應該是什麼結果?似乎兩者都應該給26.這是正確的嗎? – 2012-03-21 15:03:12

+0

其課程的一部分,aa將被排除。由於字符串的格式必須越來越大,第二個字母必須位於第一個字母之後,依此類推。所以z會給26和aa會返回0 – will 2012-03-21 15:34:40

回答

1

可以按照請求的方式計算索引而不用建立所有可能的字符串列表,但是這樣做有點涉及。下面是一個有效的方法的實現要做到這一點:

import itertools 
import string 

letters = string.ascii_lowercase 

def _reference(max_len=4): 
    """A reference implementation of the desired index operation.""" 
    a = [] 
    for k in range(max_len + 1): 
     for comb in itertools.combinations(letters, k): 
      a.append("".join(comb)) 
    return a.index 

def choose(n, k): 
    """The binomial coefficient "n choose k".""" 
    if k < 0: 
     return 0 
    result = 1 
    for i in range(k): 
     result *= n - i 
     result //= i + 1 
    return result 

def index(s): 
    """An efficient implementation of the index operation.""" 
    n = len(s) 
    choices = len(letters) 
    result = 0 
    for i, c in enumerate(s): 
     new_choices = len(letters) - letters.index(c) 
     result += choose(choices, n - i) - choose(new_choices, n - i) 
     choices = new_choices - 1 
    for i in range(n): 
     result += choose(len(letters), i) 
    return result 

test_strings =[ 
    "a", "j", "ab", "az", "jw", "yz", "abc", "abhors", "almost", 
    "begins", "bijoux", "biopsy", "chimps", "chinos", "chintz"] 
ref_index = _reference(max(map(len, test_strings))) 
for s in test_strings: 
    print "{0:8}{1:8}{2:8}".format(s, index(s), ref_index(s)) 

該腳本的快捷功能的輸出與蠻力的實施進行比較,並輸出

a    1  1 
j    10  10 
ab   27  27 
az   51  51 
jw   228  228 
yz   351  351 
abc   352  352 
abhors  91047 91047 
almost 133902 133902 
begins 154337 154337 
bijoux 171130 171130 
biopsy 172655 172655 
chimps 201678 201678 
chinos 201734 201734 
chintz 201781 201781 
+0

我是**只是**即將提交(在一個無代碼教程般的答案)。作爲我的代碼的工作原理,indexify(''。join(sorted(「misery」)))== 252666 ..我用了Greg K的unchoose函數。 – DSM 2012-03-21 16:54:19

+0

@DSM:無論如何可能會讚賞類似教程的答案,因爲我的答案沒有解釋它的工作原理。我不知道任何關於「unchoose」的內容 - 我只是從一些基本的組合考慮中做出上述代碼。 – 2012-03-21 17:06:53

+0

這是一個很棒的解決方案,非常感謝! – will 2012-03-21 18:47:04

相關問題