0

I have a pseudocode and I am required to implement a python code. Here is my pseudocode

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

Below is what I have done, but there are bugs and it just could not output something. I was not really familiar with python though

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]]
  • What are the bugs? What is your input? What is your output? – Olivier Melançon Feb 09 '18 at 04:54
  • Can you explain a little more about your input data? I'm guessing x is the input and a 1 indicates scared and 0 not scared? So does each row represent a person? Which row is the bully? – Paul Rooney Feb 09 '18 at 05:22
  • 1
    Your input data are not clear. Or is the bully afraid of himself? – Mr. T Feb 09 '18 at 06:49
  • The input will be a matrix with 1 and 0. If x[i][j] == 1 means student i is afraid of student j. A bully is someone that do no afraid of anyone but everyone else if afraid of him. The algorithm above need to output the number of bullies in the class. – Brennie Khaw Feb 11 '18 at 14:39

1 Answers1

2

I think you need to read about Python and follow a few tutorials. Although, I love Python and would like to demonstrate how easy and readable it can be. The following code reads almost as pseudo-code.

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

I don't think any other language can beat the readability capabilities that Python can achieve.

On the other hand, it does not mean you cannot achieve unreadable one-liners:

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)
Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73