Enjoy an ad free experience by logging in. Not a member yet? Register.

Results 1 to 3 of 3
Thread: Homework Help: Python Function

12042013, 03:38 AM #1
 Join Date
 Dec 2013
 Posts
 1
 Thanks
 0
 Thanked 0 Times in 0 Posts
Homework Help: Python Function
As the title says, I need help with my homework. So I have to create a program that will: open a file that consists of different sets of three numbers, and then output the smallest number for each line. (Note: I'm not allowed to use the min() function!!)
6,3,5
4,4,8
3,7,2
1,8,9
9,0,6
The program would output:
3
4
2
1
0
I was wondering if anyone could check my code and see what's wrong with it, because it doesn't seem to be getting the smallest number?
Code:def smallest(*lowest): small_numbers = [lowest] small_numbers.sort() def main(): input_file = open("datanums.txt", "r") number_file = input_file.readlines() smallest(number_file) for i in range(len(number_file)): print number_file[i][0] main()

09132014, 01:03 AM #2
 Join Date
 Sep 2014
 Posts
 4
 Thanks
 0
 Thanked 0 Times in 0 Posts
Hello coding_potato,
I rewrote your function as a generator that takes a filename as input and combined both functions into one. The generator returns a generator object that you can then loop over. Hope it helps.
def smallest(filename):
""" Generator function to determine smallest number in a file line"""
input_file = open(filename, "r")
for i in input_file.readlines():
lst = i.strip().split(',')
x=lst[0]
# compare each integer to determine the smallest
for i in lst:
if i < x:
x = i
yield x
if __name__ == '__main__':
for i in smallest('datanums.txt'):
print i

09132014, 01:03 AM #3
 Join Date
 Sep 2014
 Posts
 4
 Thanks
 0
 Thanked 0 Times in 0 Posts
Hello coding_potato,
I rewrote your function as a generator that takes a filename as input and combined both functions into one. The generator returns a generator object that you can then loop over. Hope it helps.
def smallest(filename):
""" Generator function to determine smallest number in a file line"""
input_file = open(filename, "r")
for i in input_file.readlines():
lst = i.strip().split(',')
x=lst[0]
# compare each integer to determine the smallest
for i in lst:
if i < x:
x = i
yield x
if __name__ == '__main__':
for i in smallest('datanums.txt'):
print i