将这段代码改写成python#include <iostream> #include "string.h" using namespace std; #define N 4 struct node { char c; double probablity; node* next; }; //输入节点的符号以及出现频率 node* Input() { node* p,*head; double pro = 0.0; //a head = new node; head->c = 'a'; head->probablity = 0.1; p = new node; //b head->next = p; p->c = 'b'; p->probablity = 0.4; p->next = new node; //c p = p->next; p->next = p; p->c = 'c'; p->probablity = 0.2; p->next = new node; //d p = p->next; p->next = p; p->c = 'd'; p->probablity = 0.3; p->next = NULL; /* head->c = 'a'; cin >> pro; head->probablity = pro; p = new node; head->next=p; for (int i = 1; i < N; i++) { p->c = 'a' + i; cin>>pro; p->probablity = pro ; //cout <<i<< p->c << '\t' << p->probablity<<endl; p->next = new node; p = p->next; } cout << endl; p->next = NULL; */ //打印链表 p = head; /*for (int i = 0; p != NULL; i++) { cout << p->c << '\t' << p->probablity << endl; p = p->next; }*/ return head; } //编码 double encoding(node* head) { node* p; p = new node; p = head; double low = 0.0, high = 1.0; double range; double range_high_low[2][N]; double prob = 0.0; //各字符范围 for (int i = 0; i < N; i++) { range_high_low[0][i] = prob; range_high_low[1][i] = p->probablity + prob; prob = range_high_low[1][i]; p = p->next; //cout << range_high_low[0][i] << '\t' << range_high_low[1][i] << endl; } //输入压缩信息a~d //注:double精度会缺失; char ch[] = {"cadacdb"}; //找到对应的概率值 for (int j = 0; j < 9; j++) { p = head; for (int i = 0; p!=NULL; i++) { if ((int(ch[j])-int(p->c))==0) { cout << p->c << '\t'; int n = ch[j] - 'a'; //编码 range = high - low; high = low + range * range_high_low[1][n]; low = low + range * range_high_low[0][n]; cout << low << '\t' << high << endl; } p = p->next; } } return low; } int main() { node* head,*p; head = Input(); p = head; double coder=encoding(p); cout << coder; return 0; }
时间: 2024-03-04 13:53:36 浏览: 109
以下是Python版本的代码:
class Node:
def __init__(self, c, probability):
self.c = c
self.probability = probability
self.next = None
def input_nodes():
head = Node('a', 0.1)
p = Node('b', 0.4)
head.next = p
p.next = Node('c', 0.2)
p = p.next
p.next = Node('d', 0.3)
return head
def encoding(head):
p = head
low, high = 0.0, 1.0
range_high_low = [[0.0]*4 for _ in range(2)]
prob = 0.0
for i in range(4):
range_high_low[0][i] = prob
range_high_low[1][i] = p.probability + prob
prob = range_high_low[1][i]
p = p.next
ch = "cadacdb"
coder = 0.0
for j in range(9):
p = head
for i in range(4):
if ch[j] == p.c:
print(p.c, end='\t')
n = ord(ch[j]) - ord('a')
range_val = high - low
high = low + range_val * range_high_low[1][n]
low = low + range_val * range_high_low[0][n]
print(low, end='\t')
print(high)
p = p.next
coder = low
return coder
if __name__ == '__main__':
head = input_nodes()
coder = encoding(head)
print(coder)
阅读全文