基于变量参数推广函数

时间:2018-01-11 04:20:12

标签: python arrays numpy args

这是我的第一篇文章,我是初学程序员。我希望你能帮助我成为一个更好的人。

我正在尝试为五(05)名玩家建立一个循环多米诺骨牌游戏。在每轮比赛中,只有四名(04)球员以两队(02)的比分进行比赛。对于固定数量的5名玩家,下面的公式可以解决问题。

我的具体问题是如何让它适用于任何数量的玩家;以及如何提高效率。 (我认为这是可能的,因为我是新手)。

感谢。

Results to be modeled

代码:

import numpy

def calculo(*args):

    wints= numpy.zeros(len(args),dtype=int)

    for i, item in enumerate(args):

        if i is 0:
            if item[0]>item[1]:
                wints+=[1,1,0,0,0] # players 12
            else:
                wints+=[0,0,1,1,0] # players 34

        if i is 1:
            if item[0]>item[1]:
                wints+=[1,0,0,0,1] # players 15
            else:
                wints+=[0,1,1,0,0] # players 23

        if i is 2:
            if item[0]>item[1]:
                wints+=[1,0,0,1,0] # players 14
            else:
                wints+=[0,1,0,0,1] # players 25

        if i is 3:
            if item[0]>item[1]:
                wints+=[1,0,1,0,0] # players 13
            else:
                wints+=[0,0,0,1,1] # players 45

        if i is 4:
            if item[0]>item[1]:
                wints+=[0,1,0,1,0] # players 24
            else:
                wints+=[0,0,1,0,1] # players 35

    return wints

print(calculo([118,28],[128,66],[26,133],[111,0],[57,109]))

1 个答案:

答案 0 :(得分:0)

很难理解你想要做什么,但你可以先减少这样的冗余代码:

#include <stdio.h>

void    func(char *s, char c);

int main(void)
    {
    char    s[30], c;

    printf("Enter string: ");
    fflush(stdout);
    gets(s);
    printf("Enter char: ");
    c = getchar();

    func(s, c);
    return 0;
    }

void func(char *s, char c)
    {
    char    str1[30], *dp;

    dp = str1;              // point to destination buffer
    while(*s) {             // while not null byte
        if(*s != c)         // if byte != char
            *dp++ = *s++;   // copy to dest buffer
    else
        if(*s == c) {       // if byte == char
            s++;            // bump source pointer
            continue;       // continue till null found
            }
        }
*dp = '\0';             // append null byte to dest
printf("Filtered string: %s\n", str1);
}

这里似乎有一种模式......

def calculo(items):
    wints = numpy.zeros(len(items), dtype=int)

    if items[0][0] > items[0][1]:
        wints += [1,1,0,0,0] # players 12
    else:
        wints += [0,0,1,1,0] # players 34

    if items[1][0] > items[1][1]:
        wints += [1,0,0,0,1] # players 15
    else:
        wints += [0,1,1,0,0] # players 23

    if items[2][0] > items[2][1]:
        wints += [1,0,0,1,0] # players 14
    else:
        wints += [0,1,0,0,1] # players 25

    if items[3][0] > items[3][1]:
        wints += [1,0,1,0,0] # players 13
    else:
        wints += [0,0,0,1,1] # players 45

    if items[4][0] > items[4][1]:
        wints += [0,1,0,1,0] # players 24
    else:
        wints += [0,0,1,0,1] # players 35

    return wints

输出:

  

[3 2 2 0 3]

您可以根据需要生成配对。