Reputation: 19
I've just started learning python, and since there are different ways to write the same thing, I was wondering if some ways were more efficient than other. For example, I've written two versions of this super basic code that will print the longest of 3 words; is one of the two versions more efficient than the other? Thank you.
#print the longest word 1
def long_word (word1,word2,word3):
if word1.__len__() > word2.__len__() and word1.__len__()>word3.__len__():
print ("the longest word is" + word1)
elif word2.__len__() >word1.__len__() and word1.__len__()()>word3.__len__():
print ("the longest word is" +word2)
elif word3.__len__() >word1.__len__() and word3.__len__() > word2.__len__():
print ("the longest word is" +word3)
input1=input ("Write 3 words; I will print the longest word. Word 1: ")
input2=input ("Word 2:")
input3=input ("Word 3:")
long_word(input1, input2,input3)
#print the longest word 2
def long_word (word1,word2,word3):
word1a=(len(word1))
word2a=(len(word2))
word3a=(len(word3))
if word1a > word2a and word1a>word3a:
print ("the longest word is" + word1)
elif word2a >word1a and word1a>word3a:
print ("the longest word is" +word2)
elif word3a >word1a and word3a > word2a:
print ("the longest word is" +word3)
input1=input ("Write 3 words; I will print the longest word. Word 1: ")
input2=input ("Word 2:")
input3=input ("Word 3:")
long_word(input1, input2,input3)
Upvotes: 0
Views: 111
Reputation: 2117
In python, it is not the best practice to use magic methods directly.
And yes, if you want to compare code you can use timeit module as suggested by @mark
Also, there are other ways of comparing 3 words, one example below:
#example data
word1 = "hello"
word2 = "hi"
word3 = "awsome"
# creating a list of example data
words = [word1, word2, word3]
#finding the max length of word
max_length = max(list(map(len, words)))
# iterating and printing max length word
for word in words:
if len(word) == max_length:
print(f"longest word - {word}")
Upvotes: 1
Reputation: 800
In general you can use one of the methods listed in the answers to the question How to measure elapsed time in Python?.
In your specific case, I expect the running times of the two functions to be very very similar (the running time is never the same because it depends on what other operations your system is doing) because the expression word1.__len__()
is exactly equivalent to len(word1)
, so the algorithm is exactly the same.
You should never call __len__
directly (it is not Pythonic), but instead use always len
that internally calls __len__
.
Upvotes: 1