第15周项目2++

本文介绍了一种使用链地址法解决哈希表中冲突的方法,并提供了完整的C语言实现代码。通过具体实例展示了如何构建哈希表、输出哈希表以及计算查找成功和不成功情况下的平均查找长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题及代码:

(2)若处理冲突的方法采用链地址法,请设计算法,输出哈希表,并计算成功情况和不成功情况下的平均查找长度。

    #include <stdio.h>
#include <string.h>
#include <malloc.h>
#define N 15
#define M 26
typedef struct node   //定义哈希链表的节点类型
{
    char *key;
    struct node *next;
} LNode;

typedef struct
{
    LNode *link;
} HTType;

int H(char *s)   //实现哈希函数
{
    return ((*s-'a'+1)%M);
}

//构造哈希表
void Hash(char *s[], HTType HT[])
{
    int i, j;
    LNode *q;
    for(i=0; i<M; i++)   //哈希表置初值
        HT[i].link=NULL;
    for(i=0; i<N; i++)   //存储每一个关键字
    {
        q=(LNode*)malloc(sizeof(LNode));   //创建新节点
        q->key = (char*)malloc(sizeof(strlen(s[i])+1));
        strcpy(q->key, s[i]);
        q->next=NULL;
        j=H(s[i]);    //求哈希值
        if(HT[j].link==NULL)   //不冲突,直接加入
            HT[j].link=q;
        else        //冲突时,采用前插法插入
        {
            q->next = HT[j].link;
            HT[j].link=q;
        }
    }
}

//输出哈希表
void DispHT(HTType HT[])
{
    int i;
    LNode *p;
    printf("哈希表\n");
    printf("位置\t关键字序列\n");

    printf("---------------------\n");
    for(i=0; i<M; i++)
    {
        printf(" %d\t", i);
        p=HT[i].link;
        while(p!=NULL)
        {
            printf("%s ", p->key);
            p=p->next;
        }
        printf("\n");
    }
    printf("---------------------\n");
}

//求查找成功情况下的平均查找长度
double SearchLength1(char *s[], HTType HT[])
{
    int i, k, count = 0;
    LNode *p;
    for(i=0; i<N; i++)
    {
        k=0;
        p=HT[H(s[i])].link;
        while(p!=NULL)
        {
            k++;   //p!=NULL,进入循环就要做一次查找
            if(strcmp(p->key, s[i])==0)   //若找到,则退出
                break;
            p=p->next;
        }
        count+=k;
    }
    return 1.0*count/N;   //成功情况仅有N种
}

//求查找不成功情况下的平均查找长度
double SearchLength2(HTType HT[])
{
    int i, k, count = 0;  //count为各种情况下不成功的总次数
    LNode *p;
    for(i=0; i<M; i++)
    {
        k=0;
        p=HT[i].link;
        while(p!=NULL)
        {
            k++;
            p=p->next;
        }
        count+=k;
    }
    return 1.0*count/M;   //不成功时,在表长为M的每个位置上均可能发生
}
int main()
{
    HTType HT[M];
    char *s[N]= {"if", "while", "for", "case", "do", "break", "else", "struct", "union", "int", "double", "float", "char", "long", "bool"};
    Hash(s, HT);
    DispHT(HT);
    printf("查找成功情况下的平均查找长度 %f\n", SearchLength1(s, HT));
    printf("查找不成功情况下的平均查找长度 %f\n", SearchLength2(HT));
    return 0;
}


运行结果:

 

### MCP in Python Usage and Implementation #### Overview of MCP in Python The Model Context Protocol (MCP) is a protocol designed to facilitate interactions between AI models and external tools, data sources, or APIs[^3]. In the context of Python, MCP can be implemented using the MCP Python SDK, which provides tools for building both servers and clients. This implementation allows developers to interact with MCP bridges or agents effectively. #### Installing MCP Python SDK To integrate MCP into Python projects, the MCP Python SDK can be installed via pip: ```bash pip install mcp ``` This command installs the necessary libraries for interacting with MCP servers or clients[^1]. #### Configuring MCP Server in Python A MCP server can be configured in Python by defining its behavior and endpoints. Below is an example of setting up a basic MCP server using Python: ```python from mcp.server import MCPServer def handle_request(data): # Process incoming request data return {"result": "Processed"} if __name__ == "__main__": server = MCPServer(handle_request, port=8080) server.start() ``` In this example, the `MCPServer` class initializes a server that listens on port 8080 and processes incoming requests by calling the `handle_request` function[^1]. #### Configuring MCP Client in Python For interacting with an existing MCP server, a client can be set up as follows: ```python from mcp.client import MCPClient client = MCPClient(mcp_url="http://localhost:8080", mcp_port=8080) response = client.send_request({"action": "fetch_data"}) print(response) ``` Here, the `MCPClient` sends a request to the MCP server at the specified URL and port, and retrieves the response[^2]. #### Advanced Configuration Options MCP servers and clients can be further customized with additional parameters such as JSON formatting, logging levels, and security settings. For instance: ```python client = MCPClient( mcp_url="http://localhost:8080", mcp_port=8080, hide_json=True, json_width=120 ) ``` This configuration hides JSON results from tool executions and sets the maximum width for JSON output to 120 characters. #### Integration with Databases MCP can also be integrated with databases to enhance data retrieval and model interaction. This approach offers advantages over traditional RAG methods by providing more efficient and precise data access[^4]. An example of integrating MCP with a database might look like this: ```python from mcp.server import MCPServer import sqlite3 def fetch_data_from_db(query): conn = sqlite3.connect("example.db") cursor = conn.cursor() cursor.execute(query) result = cursor.fetchall() conn.close() return result def handle_request(data): query = data.get("query") if query: return {"data": fetch_data_from_db(query)} return {"error": "No query provided"} if __name__ == "__main__": server = MCPServer(handle_request, port=8080) server.start() ``` This script sets up an MCP server that executes SQL queries against a SQLite database[^4]. #### Best Practices for MCP Implementation - Ensure secure communication between MCP clients and servers using authentication mechanisms. - Optimize performance by configuring appropriate logging levels and resource limits. - Test the MCP implementation thoroughly to handle edge cases and errors gracefully.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值