def readfromfile(filename): with open(filename, 'r') as f: s = f.read() arr =…
- User
def read_from_file(filename): with open(filename, 'r') as f: s = f.read() arr = list(map(int, s.split())) return [[arr[i], arr[i+1]] for i in range(0, len(arr), 2)]
def rotate(p, q, r): """ Returns positive if p-q-r are clockwise, negative if counterclockwise, and zero if collinear. """ return (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1])
def jarvis(A): n = len(A) if n < 3: return [] # Convex hull is not possible if there are less than 3 points
P = list(range(n)) # Convert range to a list to allow item deletion for i in range(1, n): if A[P[i]][0] < A[P[0]][0]: P[i], P[0] = P[0], P[i] H = [P[0]] del P[0] P.append(H[0]) while True: right = 0 for i in range(1, len(P)): if rotate(A[H[-1]], A[P[right]], A[P[i]]) < 0: right = i if P[right] == H[0]: break else: H.append(P[right]) del P[right] # Fixed typo here return [A[i] for i in H]points = read_from_file('input.txt') print(jarvis(points)) Интегрируй в код этот import time; start_time = time.time(); end_time = time.time() elapsed_time = end_time - start_time print(" | RunTime: {:.8f}".format(elapsed_time))
- Assistant
Below is the revised code that integrates the timing functionality using the
timemodule:import time def read_from_file(filename): with open(filename, 'r') as f: s = f.read() arr = list(map(int, s.split())) return [[arr[i], arr[i+1]] for i in range(0, len(arr), 2)] def rotate(p, q, r): """ Returns positive if p-q-r are clockwise, negative if counterclockwise, and zero if collinear. """ return (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1]) def jarvis(A): n = len(A) if n < 3: return [] # Convex hull is not possible if there are less than 3 points P = list(range(n)) # Convert range to a list to allow item deletion for i in range(1, n): if A[P[i]][0] < A[P[0]][0]: P[i], P[0] = P[0], P[i] H = [P[0]] del P[0] P.append(H[0]) while True: right = 0 for i in range(1, len(P)): if rotate(A[H[-1]], A[P[right]], A[P[i]]) < 0: right = i if P[right] == H[0]: break else: H.append(P[right]) del P[right] # Fixed typo here return [A[i] for i in H] # Start timing start_time = time.time() # Read points from the file points = read_from_file('input.txt') # Run the convex hull algorithm convex_hull = jarvis(points) # End timing end_time = time.time() # Print the convex hull and the runtime print(convex_hull) elapsed_time = end_time - start_time print("RunTime: {:.8f}".format(elapsed_time))