i want to make a calculator to "/","*",and "+" so i write my code like that
x,op,y=raw_input()
if op=='+':
print int(x)+int(y)
here if i enter number have two digit it will make error i should enter digit less than 10 form 0 to 9 only to make plus or minus and so on so i tried to split them like this
x,op,y=raw_input().split()
if op=='+':
print int(x)+int(y)
put the input will be like 20 + 20 here is the problem i want to remove this space between the number more than 9 to make the operation i want the input like 20+20 not 20 + 20 on them so i can submit the code on the online judge help me please
Do you actually need to parse the expression yourself? What about
expression = raw_input()
answer = eval(expression)
print answer
?
You could use try: and catch exceptions and do something sensible if the default exception raising isn't the behavior you want. (Like, for instance, if the expression ends up being asdf'.8 or some other garbage expression, you might want a different behavior from the default SyntaxError.)
Note: a criticism of the approach I suggest above is it allows potentially malicious strings to be evaluated, so it might make sense to sanitize your input first...
try re.split("([+-/*])",raw_input()) maybe ?
my_input = raw_input()
numbers = re.split("([+-/*])", my_input)
if '+' in my_input:
print float(numbers[0]) + float(numbers[1])
or
>>> import re
>>> re.split("\s*([+-/*])\s*",raw_input())
29+ 22
['29', '+', '22']
Related
Im trying to solve one of the a2oj problems "given three numbers a , b and c. print the total sum of the three numbers added to itself."
I came with this
import sys
numbers = [int(x) for x in sys.stdin.read().split()]
print(numbers[0] + numbers[1] + numbers[2])
I saw many topics but I cant figure out how to read just 3 values from input. I know I can stop this procces by typing CTRL+D, but is there any possibility to make it automatic (after reaching third value)?
Thanks
// Thanks for very quick answers, I made mistake and posted only Problem Statement without Input Format: "three numbers separated by bunch of spaces and/or new lines"
So for example input should look like this:
2
1 4
// Ok thanks to you guys finally I made this:
n = []
while len(n) < 3:
s=input()
i = s.split()
[n.append(int(j)) for j in i]
print(2 * sum(n))
It's working but when I sent my results I got Runtime Error. I have no idea why:
Link: https://a2oj.com/p?ID=346
You could just use:
sys.argv
import sys
numbers = [int(x) for x in sys.argv[1:4]]
print(numbers)
print(sum(numbers))
When inputs are given line by line.
from sys import stdin
sum = 0
for num in stdin.readline(4):
sum = sum + int(num)
print(sum)
When inputs are given on CLI.
from sys import argv
sum = 0
for num in argv[1:4]:
sum = sum + int(num)
print(sum)
Use Python strip() and split() functions as per your usecases
I am not sure what you are looking for, but it seems that you are looking for is the input function, from python's builtins:
x=input()
This reads any input from the user, as a string. You have then to convert it to a number if needed.
You can read three values:
x=input("First value:")
y=input("Second value:")
z=input("Third value:")
As you have now specified more precisely the problem statement, I edit my answer:
In your case, this is not very complicated. I am not going to give you the answer straight away, as it would defeat the point, but the idea is to wrap the input inside a while loop. Something like:
numbers=[]
while (you have less than 3 numbers):
(input one line and add the numbers to your list)
(print the sum of your numbers)
That way you are waiting for as many inputs as you need until you reach 3 numbers. By the way, depending on your input, you might have to check whether you do not get more than 3 numbers.
After seeing the update from the question author and linked the online judge question description, the tweak to his code needed is below. It's worth noting that the expected output is in float and has precision set to 6 and the output is 2 * sum of all inputs, not just sum. There is no description on this in the online judge question and you've to understand from the input vs output.
n = []
while len(n) < 3:
s = input()
i = s.split()
n.extend(float(j) for j in i)
print(format(2 * sum(n), '.6f'))
Screenshot below
But the first version of this answer is still valid to the first version of this question. Keeping them if anyone else is looking for the following scenarios.
To separate inputs by enter aka New lines:
numbers_List = []
for i in range(3):
number = int(input())
numbers_List.append(number)
print("Sum of all numbers: ", sum(numbers_List))
Screenshot:
To separate inputs by space aka Bunch of spaces:
Use map before taking input. I'd suggest using input as well instead of sys.stdin.read() to get input from users, separated by space, and ended by pressing Enter key.
Very easy implementation below for any number of inputs and to add using sum function on a list:
numbers = list(map(int, input("Numbers: ").split()))
print("Sum of all numbers: ", sum(numbers))
The screenshot below and link to the program is here
Read Python's Built-in Functions documentation to know more about all the functions I used above.
So I have completed a python program which can essentially make a calculator work in real life, i.e. my code will do this:
>>>3*6
>>>18
So, this works very much like a real calculator EXCEPT for the fact that a calculator would print it out on the same line (talking about basic calculator).
for example:
>>>3*6= 18
3*6 is input and = 18 is printed by program, and I don't want them in different line.
So, if anyone could help me make it on the same line by giving me ideas, it would be appreciated so my calculator would look more pretty. Also, please let me know if my code can be prettier, thanks ;).
OK, here is the pretty messy code:
def addition(a,b):#this will do addition
print (a+b)
def subtraction(a,b):
print(a-b)
def mutiplication(a,b):
print(a*b)
def division(a,b):
print (a/b)
def modulo(a,b):
print(a%b)
def mainoperations(a,b,number, expression):#this will be the place where you will be doing calculations
print("basic calculator: use four operations, +, -, /, *")
indexn=0#the index number starts at 0
while(indexn<len (expression)):#indexn is the index number of the operation you have typed.
if(indexn != '1' or '2' or '3' or '4' or '5' or '6' or '7'or '8' or '9' or '0'):
indexn+=1#this will look at every index of the expression
if(indexn=="+"):#if an addition sign is seen...
addition(expression[:indexn-1],expression[indexn+1:])
elif(indexn=="-"):#if a subtraction sign is seen...
subtraction(expression[:indexn-1],expression[indexn+1:])
elif(indexn=="*"):#if a multiplication sign is seen...
multiplication(expression[:indexn-1],expression[indexn+1:])
elif(indexn=="/"):#if a division sign is seen...
division(expression[:indexn-1],expression[indexn+1:])
elif(indexn=="%"):#if a modulo sign seen...
modulo(expression[:indexn-1],expression[indexn+1:])
expression=input()#the expression is what you inputed
mainoperations#do the function
In print() statement, there is a parameter names 'end'. You can use it to tell python interpreter not to shift the content to the next line. It's default value is '\n' which indicates new line.
For example-
print('Hello', end=' ')
print('World!')
Output-
Hello World!
You can read more about print() function and it's parameters from here.
If you have any doubt, feel free to ask in comments. :)
My program should have a single input where you write either an arabic number, a roman number, or adding roman numbers. For example:
Year: 2001
... MMI
Year: LX
... 60
Year: MI + CI + I
... MCIII
Year: ABC
... That's not a correct roman numeral
Well, I guess you get the deal. First, I tried with something like this:
def main():
year = input ("Year: ")
if type(int(year)) == type(1):
arab_to_rome(year)
else:
rome_to_arab(year)
main()
This have obvious problems, firstly, everything else than an integer will be considered as roman numerals and it doesn't take addition in consideration.
Then I googled and found something called isinstance. This is the result of trying that:
def main(input):
year = input ("Year: ")
if isinstance(input,int):
arab_to_rome(year)
elif isinstance(input,str):
rome_to_arab (year)
else:
print ("Error")
main()
This has problems as well. I get an error message stating: Invalid syntax.
This code doesn't take addition in consideration either.
You can use a try/except block to see if the input is an int. This makes up the first 3 lines of the code. For more on that see this question.
year = input('Year: ')
try:
print(arab_to_rome(int(year)))
except ValueError:
result = 0
for numeral in year.split('+'):
numeral.replace(' ','')
result += rome_to_arab(numeral)
print(result)
The part after the except is a simple way to handle the addition, and you could migrate this into your rome_to_arab function if you wish. It splits the string on each + and then add the result of the Arabic calculations together to make a complete Arabic result. The replace() function gets rid of any extra spaces to make sure it doesn't break your other methods. See this question or more info on split() and replace().
As you haven't shown us the conversion methods I'm going to assume arab_to_rome returns a string and rome_to_arab returns an int. If not you should probably change them such that they do (not just for my example, but for good code convention)
x=raw_input('what is your favorite number? ')
n=x*10
print n
If I plug in 5, I don't get 50. I get 5555555
I have tried declaring float(n) and tooling around with it. nothing helped. I realize this is minor league, but I am just starting to teach myself python.
Thanks, Todd
You are taking in your number as raw_input, meaning, it is returned to the program as a string. When you multiply a string by an integer and print the result, it just prints the string x times, in your case 10 because you attempted to multiply by 10. To prove this, change, the 10 to 20 and watch what happens.
There are two ways to fix this. The first would be to use input() instead of raw_input(), so that it returns a number as a result.
x=input("Please enter a number here.\n")
The second way would be to reassign x to the integer equivalent of the string, using the function int().
x=int(x) # Will turn "10", which is what you have, into 10
This should solve your problem.
Best of luck, and happy coding!
This is because the default data type of raw_input() is string. You have to cast the string input to an integer for achieving the desired result.
When you read a value in from user input like this it is as a string. So x actually equals the string '5' but what you actually want is the number 5.
int(x) * 10
I am fairly new to python.
I have been asked to create a calculator using only string commands, conversions between int/string/float etc.(if needed), and using functions is a requirement. while and for loops can also be used.
The program needs to take an input of the form x/y or x/y/z, where x y z are any positive or negative number. Where "/" can be replaced by addition multiplication and subtraction as well. And where any number of white spaces can exist between operands and operators. This is an idea of what I have so far.
I would have a unique definition for +,-,/, and *. I would create a function for what the user inputs. I would use ".lstrip" and ".rstrip" to get rid of white spaces.
Now what I am having trouble with is creating the input function. I am very new to functions and this is basically what I have. I know it isn't much to work with but I am really stuck on how to properly enter the function.
def multiplication(x,a,y,b,z):
if (a== "*"):
return x*y
if (b== "*"):
return y*z
def division(x,a,y,b,z):
if (a== "/"):
return x/y
if (b== "/"):
return y/z
def addition(x,a,y,b,z):
if (a== "+"):
return x+y
if (b== "+"):
return y+z
def subtraction(x,a,y,b,z):
if (a== "-"):
return x-y
if (b== "-"):
return y-z
def (x,y,z):
x=0
y=0
z=0
zxc=int(input()):# this is where I get stuck and I don't know how to implement x,y,z into the input.
All help is appreciated. If you are unsure of whether the code you provide is too intense for my needs, please ask before wasting your time for me, making code that I can't possibly use. I promise to reply ASAP.
Basically I am trying to find a way to split the inputted string AND THEN start calculations with it.
Since this looks like homework, I doubt the OP is allowed to use the typical ways to solve the problem. I think this is an exercise in input validation and string manipulation; followed by program flow and understanding function return values.
There are two things you need to do here:
Figure out what would be valid inputs to your program.
Keep prompting the user till he or she enters input that is valid for your program.
For #1, we know that valid inputs are numbers (positive or negative integers), and they must be in the form of an expression. So this means, the minimum length of the input will be three (two numbers and a math symbol) and characters (strings) in the input are not valid.
This is our basic loop to get the user's input:
expression = raw_input('Please enter the expression: ')
expression_result = check_input(expression)
while not expression_result:
print 'You did not enter a valid expression'
expression = raw_input('Please enter the expression: ')
expression_result = check_input(expression)
The check_input method will validate whatever the user entered is accurate based on our rules:
def check_input(input_string):
# Check the basics
if len(input_string) < 3:
return False
# Check if we are getting passed correct characters
for character in input_string:
if character not in '1234567890' or character not in '/*+-':
return False
# Things like /23 are not valid
if input_string[0] in '/*+':
return False
return input_string
After you have the correct input, the next step is to split the input into the various parts that you need to feed to your math functions. I'll leave that part up to you.
Assuming you have the correct string (that is, it is valid input for your program), you now need to split it into two parts.
The operator (the math symbol)
The operands (the numbers surrounding the math symbol)
So we know that we have a limited set of operators +,-,/,*, so one idea is to use the split() method of strings. This works well:
>>> s = '4+5'
>>> s.split('+')
['4', '5']
You would try splitting the string with all of your operators and then check the results. Note that splitting a string with a character that doesn't exist won't raise any errors, but you'll just the string back:
>>> s = '4+5'
>>> s.split('/')
['4+5']
So one approach is - split the string on the operators, if the resulting list has length > 2, you know that the first member of the resulting list is the left hand side of the operator, and the second member of the list is whatever is on the right hand side.
This works fine with positive numbers, with negative numbers however:
>>> s = '-4+3'
>>> s.split('-')
['', '4+3']
Good news is we aren't the first ones to reach this problem. There is another way to evaluate equations, called the Polish notation (also called prefix notation). Here's the algorithm from the wikipedia page:
Scan the given prefix expression from right to left
for each symbol
{
if operand then
push onto stack
if operator then
{
operand1=pop stack
operand2=pop stack
compute operand1 operator operand2
push result onto stack
}
}
return top of stack as result
To get a normal expression (called infix) to the polish flavor, use the shunting yard algorithm, which is my favorite train-based algorithm in computer science.
Use shunting yard to convert your expression to Polish notation, then use the pseudo code to solve the equation. You can use lists as your "stack".
Keep in mind all your inputs are in strings, so make sure you convert them to integers when you are doing the actual math.
If you're making just a toy calculator, eval() accepts local and global variables, so you could use something like this:
def calculate(x=0, y=0, z=0):
expression = raw_input('Enter an expression: ')
return eval(expression, None, locals())
Here's a sample console session:
>>> calculate()
Enter an expression: x + 5 - y
5
Note that eval() is not secure. If you want to make something serious, you will have to parse the expression.
Also, since your expressions are simple, you could use a regex to validate the input before evaling it:
def validate(expression):
operator = r'\s*[+\-/*]\s*'
return bool(re.match(r'^\s*(?:x{o}y|x{o}y{o}z)$'.format(o=operator), expression))
Here is a possible solution outline using regular expressions. Error checking left as exercise. If this isn't homework and you'd like to see the fleshed-out solution, view it here
import re
# input is a list of tokens (token is a number or operator)
tokens = raw_input()
# remove whitespace
tokens = re.sub('\s+', '', tokens)
# split by addition/subtraction operators
tokens = re.split('(-|\+)', tokens)
# takes in a string of numbers, *s, and /s. returns the result
def solve_term(tokens):
tokens = re.split('(/|\*)', tokens)
ret = float(tokens[0])
for op, num in <FILL THIS IN>:
# <apply the operation 'op' to the number 'num'>
return ret
# initialize final result to the first term's value
result = solve_term(tokens[0])
# calculate the final result by adding/subtracting terms
for op, num in <FILL THIS IN>:
result += solve_term(num) * (1 if op == '+' else -1)
print result
I have an alternative to your code. The user can enter stuff like: 8*6/4-3+3 and this will still work. It also will not crash if a letter (d, a, s) is entered. Very compact.
Code (Python v3.3.0):
valid_chars = "0123456789-+/* \n";
while True:
x = "x="
y = input(" >> ")
x += y
if False in [c in valid_chars for c in y]:
print("WARNING: Invalid Equation");
continue;
if(y == "end"):
break
exec(x)
print(x)