guys thanks for having me I've got a question already.
What I wanna do is to get sum of the list without for loop after splitting the given text by math symbols which the text as an example ** (1+3) * 3 ** should obtain the math priority for calculation.
my first question is how to get sum and sub and multiply or divide by the list and then how to check the priority and check it first.
# my calc
a = input()
result = a.split('+')
print(sum(result))
sol1: split brackets and mul /dev earlier sum /sub later but I know that split is not the best way!
sol2: make a tree I don t know what it is lol but mind it
it has answered here I know but with no split
Calculator in python
You could use eval (but be aware that it is usually a bad practice, see this answer):
result = eval(input())
If you input a string like (3-8)*4+5/2, the result will be automatically computed using normal priorities: -17.5.
Related
I'm working in Python and I would like to insert a string within another string at a random location. But I would like the choice of random location based on a probability distribution that favors certain locations more than others. Specifically, I want to insert more strings towards beginning of the original string and less towards the end.
For example, if the insertion string is "I go here" and the original string is "this is a test string and it can be long." I want to insert the insertion string at a random location in the original string. But if I do it say 100 times, I would the result "I go here this is a test string and it can be long" to be the result more number of times than "this is a test string and it can be long. I go here". I want to be able to tune the probability distribution.
Any help is appreciated.
You can use the random.gauss() function.
It returns a random number with gaussian distribution.
The function takes two parameters: mean and sigma. mean is the expected mean of the function outputs and sigma is the standard deviation- 'how far the values will be from the mean'.
Try something like this:
import random
original_str_len = 7
mean = 0
sigma= original_str_len # just an example.
r = random.gauss(mean, sigma) # random number- can be negative
r = abs(r)
insertion_index = int(r)
Notice, this code is not perfect but the general idea should work.
I recommend you to read more about the Gaussian Distribution.
I want to know if there is any way to differentiate a whole number from any other output only using maths, eg if you have the number 5 I would like to convert that into the number 0 using equations, however, the number 5.4342 would output the number -1
(What i am trying to do is very hard to put into words so i can clear up any questions)
Use type() to check if it's an integer or a float. In python, it's usually best to do it this way.
Mathematically, if you allow integer divisions, you could use this:
def isInt(n): return 0**(n-n//1)-1
isInt(5) # 0
isInt(5.4342) # -1.0
If can also work with a modulo:
def isInt(n): return 0**(n%1)-1
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.
I am currently trying to do a quadratic equation solver. I searched on the web how people did their version, but all of them implied that the user entered the coefficients, which, although the easiest way, I really hate it.
I want the user to introduce the whole equation, and let the program know which are the coefficients, and calculate the solution. I discovered the concept of regex, and automatically, the re module.
I understand how to implement the quadratic formula to solve the problem, but the problem is that I don't know which function should I use, and how to get the coefficients from the input.
I want the regex to be like:
\d(\sx\s\(\^)\s2/x\^2)(\s\+\s)\dbx(\s\+\s)\d = 0
To find the coefficients in this:
ax^2 + bx + c = 0
I am aware that the regex sucks, because I only started to understand it yesterday, so you can also tell me how to improve that.
EDIT:
Let's clarify what I exactly want.
How to improve the regex that I tried doing above?
What Python function should I use so that I can only have the coefficients?
How can I take the groups and turn them into usable integers, assuming that it doesn't store those groups?
Assumptions: the coefficients are numbers and the variable is x:
(-?\d+)x\^2 ([+-]\d+)x ([+-]\d+)
Now for -3x^2 +7x -44 your first group match will be -3, second group will be +7 and third group will be -44.
Round brackets (()) define a group
? says that what was followed can be matched one or zero times
[+-] defines a character set that will match either a + or a - one time
EDIT: Start to end solution (excuse my rusty python skills, but I hope you get an idea of how to use the regex):
import re
quadratic_equation_matcher = re.compile(r'(-?\d+)x\^2 ([+-]\d+)x ([+-]\d+)')
quadratic_equation = '-3x^2 +7x -44'
matches = quadratic_equation_matcher.match(quadratic_equation)
a = int(matches.group(1))
b = int(matches.group(2))
c = int(matches.group(3))
d = b**2 - 4*a*b
x1 = (-b + d**0.5)/(2*a)
x2 = (-b - d**0.5)/(2*a)
x1 # => -0.75542709911179939
x2 # => 3.0887604324451328
Note that you can make the regex more space permissive like so:
(-? ?\d+) ?x\^2 ([+-] ?\d+) ?x ([+-] ?\d+)
I'd recommend cleaning the input up a but first. Get rid of all the white space, or at least the spaces. Check for an equal sign and see if there's a 0 on one side or the other. If there is you can remove it. If not you have to decide how clever you want to be.
Get it close to a format you want to deal with, in other words. Then you can check if they've entered a valid re.
You also need to decide if you can handle shuffling the order of the terms around and letters other than x. Also whether you want the ^ or ** or just x2.
You probably want to grab each term individually (all the terms between the + or -) and decide what kind of term it is.
In other words there's a lot to do before the re expression.
Incidentally have you seen SymPy
First of all I'm not a Python expert, so here is my topic:
I want to invert a number, let say number = "ABCD123" (yes this is a string but I need to do it this way ...), the problem is that I'm not really satisfy with the way Python deal with the inversion, for example ~0xABCD123 is -180146468 and I don't want the MSB but only the "current" bits to be inverted. I can go with something like ~0xABCD123 & 0XFFFFFFF but the size of the number can actually change...
Question
Is there a way to dynamically "cast" or remove the bit sign in Python with the operator ~
A simple hack:
def invert_int(n):
number_bit_len = n.bit_length()
max_val = (2 ** number_bit_len) - 1
return ~n & max_val