DEV Community

Cover image for Plus Minus
Meg
Meg

Posted on

Plus Minus

Although I feel more comfortable coding in C++ and JavaScript, I've been brushing up on my Python for interview practice. The below is a walk though of how I solved the Plus Minus problem, then refactored my original answer.

The problem:
"Given an array of integers, calculate the ratios of its elements that are positive, negative, and zero. Print the decimal value of each fraction on a new line with 6 places after the decimal."

How I solved it (pseudo code):

Input: Array
Output: Decimal

What I'll need:

  • Because our input is an array I will either need a loop or a method that iterates through that loop.
  • I’ll have to divide by the total number of items in the array, so I'll need the array length.
  • Finally I'll need to keep a tally of how many elements are in each bucket.

I’m sure I could do this with a filter, but I’m going to smash and grab it to start so I'm going to use a for loop, use len() to grab the array length and I'll create buckets for negatives, positives, and zeros.

From there I'll use several if statements to check to see if the item falls under certain conditions, and if it does, the corresponding bucket will be incremented. All three buckets will then be printed divided by the length of the original array.

The code:
neg = 0
pos = 0
zero = 0
length = len(arr)
for item in arr:
if item < 0:
neg+=1
if item == 0:
zero+=1
if item > 0:
pos+=1
print(pos/length)
print(neg/length)
print(zero/length)

Refactoring:

Once I pressed “run code” and verified my code worked I went back and researched how to use filter for Python.

Looking up filter I found I could use it like so to check to see if the item (x) is larger than 0 and thus positive:
filter(lambda x: x > 0, arr)

The filter method returns an array so I need to chain it with list to print it out: list(filter(lambda x: x > 0, arr))

From there I can chain it to len() to get the length or size of that array:
len(list(filter(lambda x: x > 0, arr)))

The length will directly correlate to the number of items that are positive, negative, or zero.

From there I could divide the length of my filtered array by len(arr), the size of the original array, to print out the decimal value of each fraction.

My final code:

print(len(list(filter(lambda x: x > 0, arr)))/len(arr))
 print(len(list(filter(lambda x: x < 0, arr)))/len(arr))
 print(len(list(filter(lambda x: x == 0, arr)))/len(arr))

Top comments (0)