2014-11-29 3 views
-1

다음은 파이썬 코드입니다.이 코드는 알파벳을 내림차순으로 정렬하고 이제는 0과 다음 알파벳을 각각 1, 00,01,10으로 인코딩하려고합니다. 11,000,001 등. 그걸 도와주세요.내림차순으로 이진수로 알파벳 인코딩

from collections import defaultdict 
import string 
text ='intalks is an organization comprised of passionate students'.lower().translate(None,string.punctuation+' ') 
c = defaultdict(int) 
c.update({letter:0 for letter in string.lowercase[:26]}) 
for letter in text: 
     c[letter] += 1 


for letter,freq in sorted(c.iteritems(),key=lambda (l,f): (-f,l)): 
     print freq, letter 
+0

당신이 예상 출력을 줄 수 있습니까? –

+0

1 시부 터 00 시까 지 어떻게됩니까? 또는 11에서 000까지? –

+1

@BhargavRao 예상 출력의 0 제가 N 00 01 11 t E 000 D 001 P 10 O 010 011 R 100 ℃ F g 101 110 111 K L 0000 0001 m 0010 U Z 0011 B 0100 H 0101 J 0110 Q 0,111 1,000 V 1천1w X 1,010 012,351,y 1011 –

답변

0

이 프로그램은 다음과 같습니다 -

from collections import defaultdict 
import string 
text ='intalks is an organization comprised of passionate students'.lower().translate(None,string.punctuation+' ') 
c = defaultdict(int) 
c.update({letter:0 for letter in string.lowercase[:26]}) 
for letter in text: 
     c[letter] += 1 


def getbin(foo): 
    if len(set(a))==1 and a[0] == '1': 
     return '0'*(len(a)+1) 
    else: 
     return (("{0:0"+str(len(a))+"b}").format(int (a,2)+1)).zfill(len(a)) 


a = '0' 


for letter,freq in sorted(c.iteritems(),key = lambda (l,f) : f, reverse = True): 
    print letter,a,freq 
    a = getbin(a) 

출력은 다음과 같습니다 -

s 0 7 
a 1 6 
i 00 6 
n 01 6 
o 10 5 
t 11 5 
e 000 3 
d 001 2 
p 010 2 
r 011 2 
c 100 1 
g 101 1 
f 110 1 
k 111 1 
m 0000 1 
l 0001 1 
u 0010 1 
z 0011 1 
b 0100 0 
h 0101 0 
j 0110 0 
q 0111 0 
w 1000 0 
v 1001 0 
y 1010 0 
x 1011 0 
+0

빈도가 가장 높은 알파벳이 알파벳 "a"대신 0이되는 식으로 처리 할 수 ​​있습니까? –

+0

@ Gautam 예, 할 수 있습니다. 대신 빈도로 정렬해야합니다. –

+0

@Gautam 위의 편집 된 프로그램을 확인하십시오. –

관련 문제