Anonymous user
Compare length of two strings: Difference between revisions
→More
(→More) |
|||
Line 346:
</pre>
===
{{works with | Python 3.8}}
<lang Python>
An example code for the task "Compare length of two strings" (Rosseta Code).
print('"' + str1 + '"', 'has length', len(str1), 'and is longer')▼
This example code can handle not only strings, but any objects.
"""
def _(message):
else:▼
"""Translate: an placeholder for i18n and l10n gettext or similar."""
return message
Line 363:
"""
For objects given as parameters it prints which of them are the longest.
So if the parameters are strings, then the strings are printed, their
lengths and classification as the longest, shortest or average length.
Note that for N> 0 such objects (e.g., strings, byte strings, lists) it is
possible that exactly M> 0 of them will be of the maximum length, K> 0 of
them will be of the minimum length. In particular, it is possible that all
objects will be exactly the same length. So we assume that if an object has
both the maximum and minimum length, it is referred to as a string with the
maximum length.
Args:
*objects (object): Any objects with defined length.
sorted_ (bool, optional): If sorted_ is False then objects are not
sorted. Defaults to True.
reverse (bool, optional): If reverse is True and sorted_ is True
objects are sorted in the descending order. If reverse is False
and sorted_ is True objects are sorted in the ascending order.
Defaults to True.
Returns:
None.
"""
lengths = list(map(len, objects))
max_length = max(lengths)
min_length = min(lengths)
lengths_and_objects = zip(lengths, objects)
if sorted:▼
# Longer phrases make translation into other natural languages easier.
#
if all(isinstance(obj, str) for obj in objects):
predicate_max = _('is the longest string')
predicate_min = _('is the shortest string')
predicate_ave = _('is neither the longest nor the shortest string')
▲ else:
predicate_max = _('is the longest object')
predicate_min = _('is the shortest object')
predicate_ave = _('is neither the longest nor the shortest object')
lengths_and_objects = sorted(lengths_and_objects, reverse=reverse)
for length, obj in lengths_and_objects:
elif length == min_length:
predicate = predicate_min
else:
predicate = predicate_ave
A = 'I am string'
B = 'I am string too'
LIST = ["abcd", "123456789", "abcdef", "1234567"]
print('
print()
compare_and_report_length(A, B)
print()
print('
print()
compare_and_report_length(*LIST)
print()</lang>
{{out}}<pre>▼
<pre>
Two strings
"I am string too" has length 15 and is the longest string
"I am string" has length 11 and is
"123456789" has length 9 and is the longest string
"1234567" has length 7 and is
"abcdef" has length 6 and is
"abcd" has length 4 and is
</pre>
|