Reputation: 31
So im learning python right now and i really need your help. For example you do have random text file with words and numbers inside. You need to find the longest word and maximum number in this file. I managed to do the first half, i found the longest word:
def longest_word(word):
with open(word, 'r') as infile:
words = infile.read().split()
max_len = len(max(words, key=len))
return [word for word in words if len(word) == max_len]
print (("the longest word is :"), longest_word ('text.txt'))
can you help me with the second part? how to find maximum number in a file?
Upvotes: 2
Views: 419
Reputation: 36390
As numbers are integers you might get them using str
's method isdigit
, consider following example:
words = ['abc', '123', 'xyz', '1', '999']
numbers = [i for i in words if i.isdigit()]
print(numbers) # ['123', '1', '999']
then you might provide max
with int
as key
following way:
print(max(numbers, key=int)) # 999
remember to NOT compare strs
representing numbers as it might give surprising results, for example:
print(max(['9000','999'])) # 999
note that ValueError
will occur if original list (words
) do not contain any number.
Edit: I forget to note that above works solely for non-negative integers, to allow also negative one, you might write function for checking that as follow:
def represent_int(x):
if not x: # empty str
return False
if x[0] == '-': # leading - that is negative integer
return x[1:].isdigit()
return x.isdigit()
and use it as follows:
numbers = [i for i in words if represent_int(i)]
note that I assume represent_int
will be feeded solely with str
s.
Upvotes: 0
Reputation: 1991
You're almost there! You can check each word to see if it's actually an integer, and then check if that value is greater than the previous max. This assumes the goal is to find the largest integer
for word in words:
try:
if int(word) > MAX_INT:
MAX_INT = word
except:
pass
Upvotes: 1
Reputation: 8066
with open(word, 'r') as infile:
data = infile.read()
nums = [int(num) for num in re.findall('\d+', data)
max_num = max(nums)
Upvotes: 0
Reputation: 158
You can implement error handling and try to parse the str as int: "2" --> 2
def longest_integer(word):
max_int = 0
with open(word, 'r') as infile:
words = infile.read().split()
for word in words:
try:
int_val = int(word)
if int_val > max_int:
max_int = int_val
except:
pass
return max_int
print (("the longest integer is :"), longest_integer ('text.txt'))
Upvotes: 1