如何从TXT列表读取数值修改Python2.7脚本并保存结果至新TXT
Alright, let's walk through how to modify your Python 2.7 script to read x1 values from List.txt, process each one systematically, and save all the results to an output file. Here's a step-by-step breakdown plus the updated code:
Step 1: Read Values from List.txt
First, we need to load the space-separated integers from List.txt into a list. We'll use a with statement to safely open/close the file, and handle edge cases like missing or empty files gracefully.
Step 2: Loop Through Each x1 Value
Instead of processing a single fixed x1, we'll iterate over every value in the loaded list. For each x1, we'll run your existing elliptic curve calculation logic to compute the corresponding Q point.
Step 3: Save All Results to Output File
We'll open the result file once and write each x1's output to it, adding context (like which x1 generated the result) so the output is easy to read.
Step 4: Maintain Command Line Compatibility
We'll keep the original command line argument handling intact—if you pass an x1 via CLI, it will take priority over the file values, so you can still test single values quickly.
Updated Full Code
import sys # Default parameters a = 0 b = 7 p = 37 x1_default = 6 x2 = 8 # Handle command line arguments (override defaults if provided) if len(sys.argv) > 1: x1_default = int(sys.argv[1]) if len(sys.argv) > 2: x2 = int(sys.argv[2]) if len(sys.argv) > 3: p = int(sys.argv[3]) if len(sys.argv) > 4: a = int(sys.argv[4]) if len(sys.argv) > 5: b = int(sys.argv[5]) def modular_sqrt(a, p): """ Find a quadratic residue (mod p) of 'a'. p must be an odd prime. Solve the congruence of the form: x^2 = a (mod p) And returns x. Note that p - x is also a root. 0 is returned is no square root exists for these a and p. The Tonelli-Shanks algorithm is used (except for some simple cases in which the solution is known from an identity). This algorithm runs in polynomial time (unless the generalized Riemann hypothesis is false). """ # Simple cases if legendre_symbol(a, p) != 1: return 0 elif a == 0: return 0 elif p == 2: return p elif p % 4 == 3: return pow(a, (p + 1) / 4, p) # Partition p-1 to s * 2^e for an odd s s = p - 1 e = 0 while s % 2 == 0: s /= 2 e += 1 # Find some 'n' with legendre symbol n|p = -1 n = 2 while legendre_symbol(n, p) != -1: n += 1 x = pow(a, (s + 1) / 2, p) b_val = pow(a, s, p) g = pow(n, s, p) r = e while True: t = b_val m = 0 for m in xrange(r): if t == 1: break t = pow(t, 2, p) if m == 0: return x gs = pow(g, 2 ** (r - m - 1), p) g = (gs * gs) % p x = (x * gs) % p b_val = (b_val * g) % p r = m def legendre_symbol(a, p): """ Compute the Legendre symbol a|p using Euler's criterion. p is a prime, a is relatively prime to p (if p divides a, then a|p = 0) Returns 1 if a has a square root modulo p, -1 otherwise. """ ls = pow(a, (p - 1) / 2, p) return -1 if ls == p - 1 else ls def egcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y) def modinv(a, m): g, x, y = egcd(a, m) if g != 1: print("Error: Modular inverse does not exist for a={} mod m={}".format(a, m)) return None else: return x % m # Load x1 values from List.txt (unless command line x1 is provided) x1_list = [] if len(sys.argv) <= 1: try: with open('List.txt', 'r') as f: # Split the file content into individual numbers and convert to integers x1_list = [int(num.strip()) for num in f.read().split() if num.strip()] if not x1_list: print("Warning: List.txt is empty! Falling back to default x1={}".format(x1_default)) x1_list = [x1_default] except FileNotFoundError: print("Error: List.txt not found! Falling back to default x1={}".format(x1_default)) x1_list = [x1_default] else: # Use command line provided x1 x1_list = [x1_default] # Process each x1 and save results with open('Result01.txt', 'w') as result_file: # Write header with parameters result_file.write("=== Parameters ===\n") result_file.write("a = {}\nb = {}\np = {}\nx2 = {}\n\n".format(a, b, p, x2)) result_file.write("=== Results ===\n") for x1 in x1_list: print("\n--- Processing x1 = {} ---".format(x1)) print("a =", a) print("b =", b) print("p =", p) print("x-point =", x1) print("x-point =", x2) # Compute y1 z = (x1**3 + a*x1 + b) % p y1 = modular_sqrt(z, p) # Compute y2 z = (x2**3 + a*x2 + b) % p y2 = modular_sqrt(z, p) print("P1\t({}, {})".format(x1, y1)) print("P2\t({}, {})".format(x2, y2)) # Compute modular inverse (check if it exists) inv = modinv(x2 - x1, p) if inv is None: error_msg = "x1={}: Skipped - No modular inverse exists for (x2-x1) mod p\n".format(x1) print(error_msg.strip()) result_file.write(error_msg) continue # Compute s, x3, y3 s = ((-y2) - y1) * inv % p x3 = (s**2 - x2 - x1) % p y3 = ((s * (x2 - x3) + y2)) % p result_line = "x1={}: Q\t({}, {})\n".format(x1, x3, y3) print(result_line.strip()) result_file.write(result_line) print("\nAll results saved to Result01.txt")
Key Improvements:
- Robust File Handling: Safely reads
List.txtand falls back to the default x1 if the file is missing or empty. - Bulk Processing: Iterates over every x1 value from the file (or CLI) and processes each one.
- Error Checking: Validates if the modular inverse exists and skips invalid cases with a clear message.
- Clear Output: The result file includes a parameter header and labels each result with its corresponding x1 for readability.
- Backward Compatibility: Still supports command line arguments for quick single-value testing.
内容的提问来源于stack exchange,提问作者Izi Tors

