Advertisement
Programmin-in-Python

Converting Prefix notations of basic maths ops to Infix and writing them to a file viz. filename.out

Jan 4th, 2021
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.86 KB | None | 0 0
  1. # The Python File Consists of the follwing...
  2.  
  3. def file_math(filename):
  4.     with open(rf"{filename}.in") as file0:
  5.         data = file0.readlines()
  6.  
  7.     with open(rf"{filename}.out", 'w') as file:
  8.         for i in data:
  9.             L1 = i.split()
  10.  
  11.             if L1[0] in ('ADD', 'SUB', 'MUL', 'POW'):
  12.                 if L1[0] == 'ADD':
  13.                     file.write(f"{L1[1]} + {L1[2]} = {int(L1[1])+int(L1[2])}\n")
  14.                 elif L1[0] == 'SUB':
  15.                     file.write(f"{L1[1]} - {L1[2]} = {int(L1[1])-int(L1[2])}\n")
  16.                 elif L1[0] == 'MUL':
  17.                     file.write(f"{L1[1]} X {L1[2]} = {int(L1[1])*int(L1[2])}\n")
  18.                 elif L1[0] == 'POW':
  19.                     file.write(f"{L1[1]} ^ {L1[2]} = {int(L1[1])**int(L1[2])}\n")
  20.             else:
  21.                 file.write("Invalid Operation\n")
  22.  
  23.     print("File Successfully Read and Written...")
  24.  
  25. file_math("filename")
  26.  
  27. # Contents of the file named "filename.in"
  28. ADD 34 56
  29. SUB 28 35
  30. MUL 30 45
  31. POW 23 45
  32. CHK 23 34
  33. MOD 23 45
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement