Advertisement
Guest User

Untitled

a guest
Dec 9th, 2019
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.96 KB | None | 0 0
  1. def main(expression: str):  # Expects user's input in the function (string)
  2.     if len(expression) == 0:
  3.         return "Empty string."  # Output when user's input is empty
  4.     first = expression[0]
  5.     signs = {'+', '-', '*'}
  6.     if first.isspace() or first in signs:
  7.         return "Invalid expression."  # Output when first character is space or any of signs
  8.     splits = [first]  # We populate splits list with the first character of the expression
  9.     for i in expression[1:]:  # Start the loop from second character
  10.         if splits[-1] == '*':
  11.             if i.isdigit():
  12.                 splits.append(i)
  13.             else:
  14.                 return "Invalid expression."  # Output when signs are next to each other
  15.         elif i.isdigit():
  16.             splits[-1] += i  # If current character is a digit, add it onto the last element of list
  17.         else:
  18.             if splits[-1] in signs:
  19.                 return "Invalid expression."  # Output when signs are next to each other
  20.             else:
  21.                 splits.append(i)  # If current character is + or -, we append a new element onto the list
  22.     j = 0  # Counter
  23.     while j < len(splits):
  24.         if splits[j] == '*':
  25.             splits[j - 1] = int(splits[j - 1]) * int(splits[j + 1])  # Multiply left, right hand of the multiply index
  26.             del splits[j: j + 2]  # Delete multiply index and right hand index, result is stored on left hand
  27.         else:
  28.             j += 1  # Otherwise increment if no multiply sign is found
  29.     # Sum of all elements in the list, we use list comprehension here to convert all elements with type 'str' to 'int'
  30.     return sum([int(x) for x in splits])
  31.  
  32.  
  33. user_input = input("Please enter an arithmetic expression: ")
  34. result = main(user_input)
  35. if type(result) == int:
  36.     # Format is used here so I can put a full-stop straight after the variable without having a space dividing it
  37.     print("The result is {0}.\nGoodbye.".format(result))
  38. else:
  39.     print(result)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement