Python program to find the smallest number in a file
Last Updated :
19 Jan, 2023
Given a text file, write a Python program to find the smallest number in the given text file.
Examples:
Input: gfg.txt
Output: 9
Explanation:
Contents of gfg.txt: I live at 624 Hyderabad.
My mobile number is 52367. My favourite number is 9.
Numbers present in the text file are 9,624,52367
Minimum number is 9.
Approach:
- Create a file object using the open function and pass the filename as parameter.
- Read the contents in the file using readlines() function.
- For each line in the file, Using regex find all integers present in that line.
- Create a result variable to store the final answer.
- If a number in a line is less than the current result then update the result.
- Close the file object.
- Return the result.
Below is the implementation of the above approach.
Python3
import math
import re
def findMinimumElement(fileName):
file = open (fileName, 'r' )
lines_in_file = file .readlines()
result = math.inf
for line in lines_in_file:
nums = list ( map ( int , re.findall( '[0-9]+' , line)))
for i in nums:
result = min (result, i)
file .close()
return result
with open ( "gfg.txt" , "w" ) as file :
g
file .write(
"I live at 624 Hyderabad. \
My mobile number is 52367. \
My favourite number is 9. ")
print ( 'Smallest number in the file is:' ,
findMinimumElement( 'gfg.txt' ))
|
Output:
Smallest number in the file is: 9
Complexity analysis:
Time complexity: O(n)
Auxiliary Space: O(n)
Method : Using sort() method
Python3
import math
import re
def findMinimumElement(fileName):
file = open (fileName, 'r' )
lines_in_file = file .readlines()
result = math.inf
for line in lines_in_file:
nums = list ( map ( int , re.findall( '[0-9]+' , line)))
nums.sort()
result = nums[ 0 ]
file .close()
return result
with open ( "gfg.txt" , "w" ) as file :
file .write(
"I live at 624 Hyderabad. \
My mobile number is 52367. \
My favourite number is 9. ")
print ( 'Smallest number in the file is:' ,findMinimumElement( 'gfg.txt' ))
|
Output
Smallest number in the file is: 9
Complexity analysis:
N is the number of words.
Time complexity: O(n)
Auxiliary Space: O(n)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...