According to the documentation of any
:
Returns True
if any element of iterable is true. If iterable is empty, returns False
.
As this function returns a boolean, it makes no sense to compare them as you are doing in each of the three if
s. Each any
simply checks that each list satisfies, at least once, the condition of the predicate.
Therefore, you must count how many upper case letters and how many lower case letters that word has in order to make the comparison once it is in possession of those two numbers.
One option would be to change the any
for sum
, which returns the sum of all the elements in the list. The list of boolean is correctly summed since boolean
is a subclass of int
(which means that True
amounts to 1
and False
, to 0
). Learn more here.
In that case, we shall have:
word = input("Uma palavra: ")
if sum(x.islower() for x in word) > sum(x.isupper() for x in word):
print(word.lower())
elif sum(x.islower() for x in word) < sum(x.isupper() for x in word):
print(word.upper())
elif sum(x.islower() for x in word) == sum(x.isupper() for x in word):
print(word.lower())
The problem is, just to count, we’d have to sweep the string twice, once for each sum
.
If this is a problem, you can make use of a counter, so just iterate (to count) once. Something like this:
def count_casing(word):
upper = lower = 0
for char in word:
if char.isupper():
upper += 1
elif char.islower():
lower += 1
return upper, lower
word = input("Uma palavra: ")
upper, lower = count_casing(word)
if upper > lower:
print(word.upper())
else:
print(word.lower())
Note that upper
and lower
also travel the string again. Therefore, the above code "scans" the string twice.
Also note that the last if
(in case the number of upper and lower case letters are equal) is not necessary, since the else
covers that case as well. :)
This Javascript mania of creating object for everything :-) In Python you can create the counters separately and return them in a tuple: https://ideone.com/tfTarV
– hkotsubo
@hkotsubo, indeed, becomes much more succinct without the dictionary; it was in fact a language addiction. :Thank you very much for the suggestion, I edited the reply.
– Luiz Felipe
Just to be pedantic,
sum
does not convert booleans into numbers. Actually, according to documentation, Boolean is a sub-type ofint
, so much so thatisinstance(True, int)
returnsTrue
(andTrue
andFalse
are equivalent to 1 and 0 respectively - so much so thatTrue == 1
andFalse == 0
are true, and remembering that Python does not do the crazy coercion of JS). See more here and here– hkotsubo