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.

4
  • 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 Commented Oct 25, 2019 at 21:19
  • 1
    Possible duplicate of How to test multiple variables against a value? Commented Oct 25, 2019 at 21:23
  • @MattR, This worked. thanks Commented Oct 25, 2019 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. (?) Commented Oct 25, 2019 at 21:25

2 Answers 2

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): 
Sign up to request clarification or add additional context in comments.

Comments

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]): ... 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.