I'm writting a program that will take a file as input and go through the list of numbers in the file and return the max number uing recusions. I'm not very good with recursions here is what I have so far. Also I'm not allowed to use the max command.

def Mymax(lists):
    if (len(lists[1:])>0):
        return 


def main():
    fname = input("Enter filename: ")
    infile = open(fname, "r")
    data = infile.read()

    for line in data.splitlines():
        print(eval(line))

main()

Recommended Answers

All 5 Replies

I do not see any recursion.

Recursion calls the function from within the function with an adjusted parameter.
Example:

def remove_char_right(mystr, num, count=0):
    """
    remove num of characters to the right of a string
    """
    print("{} {}".format(count, mystr))  # test
    # exit condition, return the final result
    if count >= num:
        return mystr
    mystr = mystr[:-1]
    # needs return
    # function calls itself
    # notice the adjusted parameters mystr and count
    return remove_char_right(mystr, num, count+1)

# test it
mystr = 'parameter'
num = 5
newstr = remove_char_right(mystr, num)
print('-'*15)
print(newstr)

''' output -->

0 parameter
1 paramete
2 paramet
3 parame
4 param
5 para
---------------
para

'''

Here the update to the code but it's still not giving me the maximum number in the lines for the code. I'm trying to pull the numbers out of the list one by one and then to compare them to the rest of the remaining numbers but I must be doing something out of order. In the end my list should be empty.

def numlist(s):
    first = (s[0:1])
    rest = (s[1:2])
    if first >= rest:
        return first
    else:
        return line.remove(s[0:1])

def main():
    fname = input("Enter filename: ")
    infile = open(fname, "r")
    data = infile.read()

    for line in data.splitlines():
        print(eval(line))
        numlist(line)
        print("The maximum number is: ", line)
main()

Put in a few test print() to catch the many errors.

Notice that a while loop mimics a recursive function rather closely. It should give you hints how to set it up ...

''' maxnum1.py
find the highest number in a list
not using Python's max(list) function
'''

mylist = [1, 2, 3, 4, 5 ,6, 7, 3, 5]

maxnum = 0
index = 0
while True:
    num = mylist[index]
    # update maxnum to be the highest number
    if num > maxnum:
        maxnum = num
    # go to next index
    index += 1
    # exit condition
    if index >= len(mylist):
        break

print(maxnum)  # 7
# test
print(max(mylist))  # 7

Actually, while loops are faster then the high overhead recursive functions.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.