Answered step by step
Verified Expert Solution
Question
1 Approved Answer
I am getting an infinite loop on my second test case for a python program I wrote. The text file it is calling looks exactly
I am getting an infinite loop on my second test case for a python program I wrote.
The text file it is calling looks exactly like this:
2
300 2
59 9
Here is the program:
# Input: int n, the number of lines of code to write # int k, the productivity factor # Output: the number of lines of code that must be # written before the first cup of coffee
def linear_search(n: int, k: int) -> int: v = 1 while help(v, k) < n: v += 1 return v + 1 # Input: int n, the number of lines of code to write # int k, the productivity factor # Output: the number of lines of code that must be # written before the first cup of coffee def binary_search(n: int, k: int) -> int: v = n // 2 lines = help(v,k) lines2 = help(v -1, k) add = n // 4 while not (lines >= n > lines2): if lines > n: v += add elif lines2 < n: v -= add add //= 2 lines = help(v,k) lines2 = help(v-1,k) return v + 1 def help(v, k): lines = 1 while v > 0: lines = lines + v v = v / k return lines # main has been completed for you # do NOT change anything below this line def main(): in_file = open("work.txt", "r") num_cases = int((in_file.readline()).strip()) for i in range(num_cases): inp = (in_file.readline()).split() n = int(inp[0]) k = int(inp[1]) start = time.time() print("Binary Search: " + str(binary_search(n, k))) finish = time.time() print("Time: " + str(finish - start)) print() start = time.time() print("Linear Search: " + str(linear_search(n, k))) finish = time.time() print("Time: " + str(finish - start)) print() print() # The line above main is for grading purposes only. # DO NOT REMOVE THE LINE ABOVE MAIN if __name__ == "__main__": main()
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started