想用给定的伪代码实现python代码吗

2024-10-01 22:41:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个伪代码,我需要实现一个python代码。 这是我的伪代码

find_bully_1(A):
    for student in class:
        if student is afraid of no one:
            candidate = student

    if no such candidate found:
        return None

    if everyone is afraid of candidate:
        return candidate as bully
    else:
        return None

下面是我所做的,但有错误,它只是不能输出一些东西。不过,我对python并不太熟悉

def find_bully_1(A):

    n = len(A)
    candidate = 0
    bully = 0
    a = []

    for i in range(n):
        count = 0
        for j in range(n):
            if A[i][j] == 0:
                count = count + 1
        if count == n:
            candidate += 1
            a = [a,i]

    count_scare = 0

    for k in [a]:
        count_scare = 0
        for g in range(n):
            if (zip(*A))[k][g] == 1:
                count_scare += 1
                if count_scare == n-candidate:
                    bully += 1

    return bully


x = [[1,1,1,1],
     [0,0,0,1],
     [0,0,0,0],
     [0,0,0,0]]

Tags: of代码inforreturnifiscount
1条回答
网友
1楼 · 发布于 2024-10-01 22:41:56

我认为您需要了解Python并遵循few tutorials。尽管如此,我还是喜欢Python,并想展示一下它是多么容易阅读。下面的代码几乎是伪代码。你知道吗

find_bully_in(my_class):
    for student, afraid in enumerate(my_class):
        if not any(afraid):
            candidate = student
        else:
            continue

        other_students = [student for student, _ in enumerate(my_class) if student != candidate]

        if all([afraid_of[candidate] for afraid_of in other_students]):
            return candidate
    else:
        return None

我不认为任何其他语言可以打败Python所能实现的可读性功能。你知道吗

另一方面,这并不意味着你不能实现不可读的一行程序:

find_bully_in(cls):
    return next(filter(lambda s: not any(s[1]) and list(zip(*cls))[s[0]].count(1) == len(cls) - 1, enumerate(cls)), None)

相关问题 更多 >

    热门问题