Version number comparison in Python

后端 未结 17 2087
小蘑菇
小蘑菇 2020-11-27 10:32

I want to write a cmp-like function which compares two version numbers and returns -1, 0, or 1 based on their compared va

17条回答
  •  鱼传尺愫
    2020-11-27 11:15

    This is my solution (written in C, sorry). I hope you'll find it useful

    int compare_versions(const char *s1, const char *s2) {
        while(*s1 && *s2) {
            if(isdigit(*s1) && isdigit(*s2)) {
                /* compare as two decimal integers */
                int s1_i = strtol(s1, &s1, 10);
                int s2_i = strtol(s2, &s2, 10);
    
                if(s1_i != s2_i) return s1_i - s2_i;
            } else {
                /* compare as two strings */
                while(*s1 && !isdigit(*s1) && *s2 == *s1) {
                    s1++;
                    s2++;
                }
    
                int s1_i = isdigit(*s1) ? 0 : *s1;
                int s2_i = isdigit(*s2) ? 0 : *s2;
    
                if(s1_i != s2_i) return s1_i - s2_i;
            }
        }
    
        return 0;
    }
    

提交回复
热议问题