简体   繁体   English

在C中复制python字符串行为

[英]Replicating python string behavior in C

I'm trying to learn C, and I thought a good way to do so was to rework some programing praxis problems that I did in python. 我正在尝试学习C,我认为这样做的一个好方法是重新编写一些我在python中所做的编程实践问题。 I'm currently working on this one. 我目前正在研究这个

My solution: 我的解决方案:

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 performs some witchery when doing recursive function calls where it creates a new string per function call ie "" results in "10" which results in "10+", "10-", "10*", "10/", "10" so on and so forth for every permutation. Python在执行递归函数调用时会产生一些麻烦,即在每个函数调用处创建一个新字符串,即“”导致“ 10”,从而导致“ 10 +”,“ 10-”,“ 10 *”,“ 10 /”,“每个排列10“,依此类推。 An example if you uncommented that print statement: 如果您取消注释该打印语句的示例:

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

Seeing how hands on you have to be with memory allocation and strings in C, is it even possible to do that sort of "forking" behavior that python exhibits in C? 看看您必须如何使用C中的内存分配和字符串,甚至有可能做到python在C中表现出来的那种“分叉”行为吗?

UPDATE: 更新:

Figured it out, 弄清楚了,

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);
    }
}

Of course you can. 当然可以。 Use malloc and free to allocate memory for each invocation. 使用mallocfree为每次调用分配内存。 Some very complex program that process text, like a compiler, are written in C. They are just hugely painful compare to Python. 一些处理文本的非常复杂的程序(例如编译器)是用C编写的。与Python相比,它们非常痛苦。 Or you can use C++, which has a string class so that you can do basic thing like string concatenation more easily. 或者,您可以使用C ++,它具有一个字符串类,这样您就可以更轻松地完成诸如字符串连接之类的基本操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM