我目前正在尝试用 C 语言为我的程序实现哈希函数。我找到了许多可能的解决方案,但我不理解它们。下面是哈希函数:
int hash(const char *word) {
int hash = 0;
int n;
for (int i = 0; word[i] != '\0'; i++) {
// alphabet case
if (isalpha(word[i]))
n = word[i] - 'a' + 1;
else // comma case
n = 27;
hash = ((hash << 3) + n) % SIZE;
}
return hash;
}
Run Code Online (Sandbox Code Playgroud)
我们为什么要从'a'+1中减去word[i]?另外,我们为什么要做以下事情:hash = ((hash << 3) + n) % SIZE?
我正在尝试使用键值对格式化字符串,其中字符串中的变量修饰符由键的名称引用.
我该怎么做?这是我的代码:
given_string2 = "I'm %(name)s. My real name is %(nickname)s, but my friends call me %(name)s."
def sub_m(name, nickname):
return given_string2 %{name:nickname}
print sub_m("Mike","Goose")
Run Code Online (Sandbox Code Playgroud) 我正在尝试实现一个替换以下值的函数:
# > with >
# < with <
# " with "
# & with &
Run Code Online (Sandbox Code Playgroud)
我的功能一直出错.究竟出了什么问题?
def escape_html(s):
data = list(s)
if ">" in data:
data.replace(">",">")
if "<" in data:
data.replace("<","<")
if '"' in data:
data.replace('"',""")
if "&" in data:
data.replace("&","&")
word = data.join()
return word
print escape_html("<>")
Run Code Online (Sandbox Code Playgroud)
注意:这更像是一个基本的编程问题.我的重点是我的功能不起作用的原因.我不能在这个项目中使用外部库.
鉴于此代码:
def double_char(str):
result = ""
for i in range(len(str)):
result += str[i] + str[i]
return result
Run Code Online (Sandbox Code Playgroud)
是result = ""字符串的初始化?如果是这样,有必要在第一时间做吗?
GDB告诉我第52行导致了分段错误.我不明白为什么.我正在实现一个简单的堆栈.它有两个功能:pop和push.看来pop不起作用.pop的目的是检索堆栈上的最高值.但是,当它试图这样做时,我得到一个分段错误.有谁知道原因?
/*************************************************************************
* stack.c
*
* Implements a simple stack structure for char* s.
************************************************************************/
// for strdup() in the testing code
#define _XOPEN_SOURCE 500
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// the capacity of the stack
#define CAPACITY 10
//global variable used to keep track of pop and push
typedef struct
{
// storage for the elements in the stack
char* strings[CAPACITY];
// the number of elements currently in the stack
int size;
}stack;
// …Run Code Online (Sandbox Code Playgroud)