could someone please explain me this answer to me the question is so it says convert the following while loop into a for loop. Your code should be written so that the return statement does not need to be altered. You are allowed to change the code before the while loop proper. string_list is a list of string that contains at least 15 instances of the string '***' j=0 while i<15: if string_list[j] ='***': i +=1 j +=1 return j
and the answer to this is j=0 counter = 0 for i in range(len(string_list)): if string_list[i] == '***' counter +=1 if counter ==15: j +=1 return j i have no clue what happened to the i and where this counter came from
@shandelman
i know yesterday the string can be long as it wants so that is why we used for i in range(len(string_list)) and then i dont know what happens
and also what does this answer mean the question is write a function called line_to_list so that the code with * comments is replaced by a single line that includes a call to line_to_list. input_file is a file. nested_list = [] for line in input_file: line _list = [] #* for char in line: #* line_list.append(char) #* nested_list.append(line_list) #* Solution: def line_to_list(in_str): '''(str --> list) return a list where element i is the corresponding character of in_str.''' ret_list = [] for char in in_str: ret_list.append(a) return ret_list nested_list = [] for line in input_file: nested_list.append(line_to_list(line)) pleasee helpp
Let me reword it for you: they give you a function, and they want you to rewrite the four marked lines as its own function, and then just call that function instead. So in the solution, they basically move those four lines of code into its own function list_to_list and then append what it returns into the nested list. The solution code does exactly what the code you were given does. This is what is known as "refactoring"...taking code and changing it without actually changing what it does. Why do this? Well, one of the best reasons is to make the code more abstracted, because abstracted code is easier to understand without knowing what's going on under the surface. Take a look at the code nested_list = [] for line in input_file: nested_list.append(line_to_list(line)) This code is ridiculously easy to understand: There's an empty list, and there's this file called input_file, and then the program goes through each line in the input_file, turns that line into a list, and then appends that to the main list. You don't even have to know HOW line_to_list works, just that that's what it does. It's much easier to understand than the original code.
Join our real-time social learning platform and learn together with your friends!