Smoother way to solve the problem

I’m posting below a problem I solved, but I feel there is a smoother, more elegant way to do it. If you don’t mind, please look at my code and tell me where I can fine-tune it, make it prettier.

*The prompt: Write a Python program that accepts a list *
of integers and calculates the length and the fifth element.
*Return true if the length of the list is 8 and the fifth element *
occurs thrice in the said list.

var1 = [19, 19, 15, 5, 5, 5, 1, 2]
var2 = [19, 15, 5, 7, 5, 5, 2]

count = 0
if len(var1) == 8:
    fifth_el = var1[4]
    for n in var1:
        if n == fifth_el:
            count = count + 1
if count == 3:
    print("True")
else:
    print("False")

If it was a function, I would write:

def check_fifth_elem(list):
    if len(list) == 8:
        fifth_el = list[4]
        count = list.count(fifth_el)
    return count == 3

check_fifth_elem([19, 19, 15, 5, 5, 5, 1, 2]) # True
1 Like

Check this out:

def short(list):
    return len(list) == 8 and list.count(list[4]) == 3

I did a benchmark and it is about 30% faster than that other function. No I’m not competitive. :wink:

Try running it yourself: Einblick

Also here’s how I did the benchmarking: Benchmarking and Profiling

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.