【问题标题】:Replicating python string behavior in C在 C 中复制 python 字符串行为
【发布时间】:2013-01-29 19:41:55
【问题描述】:

我正在尝试学习 C,并且我认为这样做的一个好方法是重新处理我在 python 中所做的一些编程实践问题。我目前正在处理this 一个。

我的解决方案:

def main():
    nums = ["10", "9", "8", "7", "6", "5", "4", "3", "2", "1"]
    ops = ["+", "-", "*", "/", ""]

    recursive(nums, ops, "", 0)

def recursive(nums, ops, current_str, num_ind):
    if num_ind == len(nums)-1:
        # print current_str + nums[num_ind]
        if eval(current_str + nums[num_ind]) == 2013:
            print current_str + nums[num_ind]
        return 0
    else: 
        current_str = current_str + nums[num_ind]
        num_ind += 1
        for i in range(len(ops)):
            recursive(nums, ops, current_str+ops[i], num_ind)

Python 在执行递归函数调用时会执行一些巫术,它会为每个函数调用创建一个新字符串,即“”导致“10”导致“10+”、“10-”、“10*”、“10/” ", "10" 等等每个排列。如果您取消注释该打印语句的示例:

10+9+8+7+6+5+4+3+2+1
10+9+8+7+6+5+4+3+2-1
10+9+8+7+6+5+4+3+2*1
10+9+8+7+6+5+4+3+2/1
10+9+8+7+6+5+4+3+21

看看你必须如何处理 C 中的内存分配和字符串,是否有可能实现 python 在 C 中表现出的那种“分叉”行为?

更新:

想通了

int recursive(char** nums, char** ops, char* current_str, int num_ind){
    int i, ret;
    char new_str[100];

    num_ind++;
    if(num_ind == 9){
        //printf("%s\n", strcat(current_str,nums[num_ind]));
        ret = eval(strcat(current_str, nums[num_ind]));
        if(ret == 2013){
            printf("%s\n", current_str);
        }
        return 0;
    }
    for(i=0; i<5; i++){
        strcpy(new_str, current_str);
        strcat(new_str, nums[num_ind]);
        recursive(nums, ops, strcat(new_str, ops[i]), num_ind);
    }
}

【问题讨论】:

  • Python 是用 C 实现的。所以是的,有可能 :-) 您需要为每个新字符串分配内存,并用字符串内容手动填充分配的内存。
  • eval 但是,如果没有外部库,实现起来将变得更加困难......
  • Nitpick ... CPython 是用 C 实现的。
  • 旁注:像 python 一样使用 C 是一个坏主意(或者像 C 一样使用 python)。您应该尝试学习 C 的习语,而不是复制 Python 中的操作方式。
  • @nneonneo 是的,是的

标签: python c arrays string char


【解决方案1】:

当然可以。使用mallocfree 为每次调用分配内存。一些非常复杂的处理文本的程序,比如编译器,是用 C 语言编写的。与 Python 相比,它们非常痛苦。或者你可以使用 C++,它有一个字符串类,这样你就可以更容易地做一些基本的事情,比如字符串连接。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-18
    • 2012-07-20
    • 2019-03-18
    • 2015-07-04
    • 1970-01-01
    • 1970-01-01
    • 2020-06-29
    相关资源
    最近更新 更多