1

I'm still a bit new to python and I am trying to learn how to properly format my code for real world applications and interviews.

The code below takes a number as an input and then returns how many numbers in a list are above and below the given number. I create a class, solution, to store the function ,placeOfNum, that does all of the processing logic.

If I want to output my answer as I have below is it best practice call the Solution class function as I have below, or should I keep everything in the class to help with readability, or should I make another function, answer for example, within the class and output the solution within that class?

def placeOfNum(self, n, array):
    aboveNum = 0 
    belowNum = 0
    array = sorted(array)

    for x in array: 
        if x < n: 
            belowNum += 1
        if x > n: 
            aboveNum += 1 
     return (above, below)

numList = [1,5,21,2,1,10,232]
num = 21
x = Solution()

answer = x.placeOfNum(num, numList)
print("above:", answer[0], "below:", answer[1])

# returns "above:1, below:5"
3
  • 1
    You never refer to self in the only method defined for Solution. You don't need a class at all. (That said, is findPlace supposed to be placeOfNum?) Python isn't Java; you can define functions outside of a class. Commented Dec 6, 2018 at 17:36
  • 1
    This code might fit Code Review better Commented Dec 6, 2018 at 17:40
  • Also, if you are interviewing for a job that requires Python, I would use PEP8 standard style, so e.g don't use camelCase names, use snake_case. Commented Dec 6, 2018 at 18:01

1 Answer 1

1
def place_of_num(num, array):
    above_num = 0 
    below_num = 0

    for x in array: 
        if x < num: 
            below_num += 1
        if x > num: 
            above_num += 1
    return tuple((above_num, below_num))

num_list = sorted([1,5,21,2,1,10,232])
num = 21

answer = place_of_num(num, num_list)
print(f"above: {answer[0]} and below: {answer[1]}")

I would have written it this way. keep the naming consistent like using snake_case for variables, function, and CamelCase for Class names. keep the code simple and readable

Sign up to request clarification or add additional context in comments.

4 Comments

why are you sorting outside the function? That's more than a stylistic change
I don't find the need to sort the list inside a function. do you think it is bad practice?
But then it is a different function, not a style change. I agree, it doesn't seem necessary to sort at all.
ok, please feel free to edit the answer on how exactly it should be done.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.