Okay so I am super noob in programming. Wrote a program to find the frequency of each element in an array
print("Running own")
arr = [1, 2, 8, 3, 2, 2, 2, 5, 1];
fr = [None] * len(arr)
vsi = -1
for i in range(0, len(arr)):
count = 1
for j in range(i + 1, len(arr)):
if (arr[i] == arr[j]):
count += 1
fr[j] = vsi
print("j={0} and fr[j]={1}".format(j, fr[j]))
if [fr[i] != vsi]:
fr[i] = count
print(fr)
print("fr=", fr)
print("---------------------");
print(" Element | Frequency");
print("---------------------");
for i in range(0, len(fr)):
if(fr[i] != vsi):
print(" " + str(arr[i]) + " | " + str(fr[i]));
print("---------------------")
so I used square brackets on the if to check if the element is visited and to assign count to the frequency array.(This line: if [fr[i] != vsi]: ) After banging my head against the wall for 5 hours and tracing the program like 20 times I figured out that the compiler is treating if as always true.
Why didn't I get an error to begin with?
[fr[i] != vsi]
evaluates to a list with a single boolean value in it. When a non-empty list is being evaluated for truthyness (like what you're doing), it will be considered "truthy". If the list were empty, it would be "falsey".