python - How to recursively read all characters in a list? -
i need write function recursively read chars in file , append list.the function needs 2 parameters , file , list. recursion stumping me.any tips on thinking recursively appreciate well. bellow code have written print chars of list , without recursion.
def newchar(usrfile,usrlist): line in usrfile: c in line: usrlist.append(c) print(usrlist) def main(): usrfile = open("input.txt",'r') usrlist = [] newchar(usrfile,usrlist) main()
result :
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', ' ', 'p', 'r', 'i', 'n', 't', ' ', 'a', 'l', 'l', ' ', 't', 'h', 'e', 's', 'e', ' ', 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r', 's', '.']
one way think recursion try , solve small piece of problem, , imagine recursive call 'magically' solves rest of problem. importantly, have consider happens when rest of problem trivial solve; called base case.
in case, small piece can solve in 1 recursive call reading single character (byte). base case occurs if there no characters left in file; when happens, append nothing list , return have built up.
this idea can implemented follows.
f = open('test_file.txt', 'r') char_list = [] def read_rec(fh, chars): curchar = fh.read(1) if curchar: #returns false @ end of file chars.append(curchar) #append chars return read_rec(fh, chars) #recursively read rest of file return chars print read_rec(f, char_list)
output
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', ' ', 'm', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's', ' ', 'g', 'a', 'r', 'r', 'e', 't', 't', '\n']
Comments
Post a Comment