0

I am trying to create a function which counts the length of elements in the list and then run an if / elif loop on them:

k_nearest_samples_class = training_data[sorted_indices[:k]][:, -1]
# print(k_nearest_samples_class)
# counting number of occurrences of either 0's or 1's with below 2 lines
class_0_count = len(k_nearest_samples_class[k_nearest_samples_class == 0])
class_1_count = len(k_nearest_samples_class[k_nearest_samples_class == 1])
class_2_count = len(k_nearest_samples_class[k_nearest_samples_class == 2])

# Combining > & = sign so even in tie-up cases the instance will be classified to malignant - assumed it
# would be okay in order to reduce false positives
if class_0_count >= class_1_count and class_2_count:
    print("0", class_0_count)
    return 0
elif class_1_count >= class_0_count and class_2_count:
    print("1", class_1_count)
    return 1
else:
    print("2", class_2_count)
    return 2

Giving input one by one like:

[0.0]
[1.0]
[2.0]

currently, my if loop is working illogically.

ipaleka
  • 3,745
  • 2
  • 13
  • 33
User
  • 101
  • 1
  • 9
  • 1
    I'm not sure what your expected output is, but I think you may want to try `if class_0_count >= class_1_count and class_0_count >= class_2_count`. The `>=` is not being applied to both `class_1` and `class_2` like you may think – MattR Oct 25 '19 at 21:19
  • 1
    Possible duplicate of [How to test multiple variables against a value?](https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-value) – b_c Oct 25 '19 at 21:23
  • @MattR, This worked. thanks – User Oct 25 '19 at 21:25
  • `if ... class_2_count` is only testing that `class_2_count` is > 0. Is this your design? If not, this might be part of the issue. (?) – S3DEV Oct 25 '19 at 21:25

2 Answers2

1

This line:

if class_0_count >= class_1_count and class_2_count:

is equivalent to:

if class_0_count >= class_1_count and class_2_count > 0:

you need to change it to:

if class_0_count >= class_1_count and class_0_count >= class_2_count:

or you can compare with the maximum value of the two:

if class_0_count >= max(class_1_count, class_2_count):
Mohd
  • 5,523
  • 7
  • 19
  • 30
0

Expanding on @MoeA's answer above:

A (alternative) Pythonic way to perform this test is to use the all() function like:

if all([class_0_count >= class_1_count, class_0_count >= class_2_count]):
    ...
S3DEV
  • 8,768
  • 3
  • 31
  • 42