def longestWord(sentence):
longest = 0 # Keep track of the longest length
word = '' # And the word that corresponds to that length
for i in sentence.split():
if len(i) > longest:
word = i
longest = len(i)
return word
>>> s = 'this is a test sentence with some words'
>>> longestWord(s)
'sentence'
Answer from Cory Kramer on Stack Overflowdef longestWord(sentence):
longest = 0 # Keep track of the longest length
word = '' # And the word that corresponds to that length
for i in sentence.split():
if len(i) > longest:
word = i
longest = len(i)
return word
>>> s = 'this is a test sentence with some words'
>>> longestWord(s)
'sentence'
You can use max with a key:
def max_word(splitlist):
return max(splitlist.split(),key=len) if splitlist.strip() else "" # python 2
def max_word(splitlist):
return max(splitlist.split()," ",key=len) # python 3
Or use a try/except as suggested by jon clements:
def max_word(splitlist):
try:
return max(splitlist.split(),key=len)
except ValueError:
return " "
making string comparision in python - Stack Overflow
python - Fastest way to compare one string of two lengths - Stack Overflow
Compare 2 Strings in Python - Stack Overflow
performance - Python program to take in two strings and print the larger string - Code Review Stack Exchange
< , > for string operands compare lexicogrphical orders, not their lengths.
>>> 'a' < 'b'
True
>>> 'a' > 'b'
False
>>> 'cat' > 'banana'
True
>>> 'cat' < 'banana'
False
Upper-case characters are smaller than their lower-case version.
>>> 'A' < 'a'
True
>>> 'A' > 'a'
False
So, your code does case-sensitive comparison.
You can use str.casefold for case-insensitive comparsison, (Python 3.3+ only).
>>> 'A'.casefold()
'a'
>>> 'A'.casefold() == 'a'.casefold()
True
Former one just compares the length of two strings. But latter one try to find which one is bigger. For instance:
A = "abcdef"
B = "b"
len(A) > len(B) will be true But B > A will be true, because "b" > "a" (which is the first letter of A)
- you do not need to call
lentwice, - you can utilize
abs
Example:
s = "Hello"
t = "Worl"
if abs(len(s) - len(t)) > 1:
print("string lengths differ by more than 1")
Update: With ipython's timeit there are almost no speed gain, however:
In [10]: s = str(range(100000))
In [11]: t = str(range(100001))
In [12]: %timeit len(s) > len(t) + 1 and len(s) < len(t) - 1
10000000 loops, best of 3: 106 ns per loop
In [13]: %timeit abs(len(s) - len(t)) > 1
10000000 loops, best of 3: 115 ns per loop
In [14]: %timeit 1 >= len(s) - len(t) >= -1
10000000 loops, best of 3: 113 ns per loop
Here's another run with shorter strings, but about the same result: https://gist.github.com/miku/6904419.
Nevertheless, in the context of OPs code, abs(len(s) - len(t)) > 1 really is faster.
It seems that the fastest way is
if 1 >= len(s) - len(t) >= -1:
print("string lengths differ by more than 1")
Indeed:
>>> %timeit abs(a) <= 1
1000000 loops, best of 3: 283 ns per loop
>>> %timeit 1 >= a >= -1
10000000 loops, best of 3: 198 ns per loop
I would use
def difference(word_one, word_two):
return sum(l1 != l2 for l1, l2 in zip(word_one, word_two))
Which works like
>>> difference('abcdef', 'abcdef')
0
>>> difference('abcdef', 'abcabc')
3
You can zip the strings together and then count how many different pairs there are:
def chardifferencecounter(x, y):
return len([1 for c1, c2 in zip(x, y) if c1 != c2])
>>> chardifferencecounter('abcdef', 'aabccf')
4
>>> chardifferencecounter('abcdef', 'accddf')
2
Explanation:
Zipping the strings together produces this:
>>> s1 = 'abcdef'
>>> s2 = 'aabccf'
>>> zip(s1, s2)
[('a', 'a'), ('b', 'a'), ('c', 'b'), ('d', 'c'), ('e', 'c'), ('f', 'f')]
so it takes a character from the same position in each string and pairs them together. So you just need to count how many pairs are different. That can be done using a list comprehension to create a list with those pairs that are the same filtered out, and then get the length of that list.
Python strings supports Python built-in len function. You don't need to iterate through them manually, as for lists/dicts/sets etc (it is not Pythonic):
def compare_strings_len(s1, s2):
if len(s1) > len(s2):
print('String 1 is longer: ', s1)
elif len(s1) < len(s2):
print('String 2 is longer: ', s2)
else:
print('Strings length are equal!')
Here's how I would get the longer string:
max(string_1, string_2, key=len) # Returns the longer string
The key keyword argument is a pattern you'll see frequently in python. It accepts a function as an argument (in our case len).
If you wanted to find the longest of multiple strings, you could do that too:
max('a', 'bc', 'def', 'ghi', 'jklm', key=len) # => 'jklm'
Warning:
This solution is not a great fit if you need to know when two strings are of equal length. If that's a requirement of yours, you'd be better off using a solution from one of the other answers.
I won't bother updating this approach to handle that requirement: that would feel like working against the language.