Fastest way to concatenate two numbers in Python [closed] - python

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
suppose you have two strings (with digits only) in Python, say string a and string b. What is the fastest way to produce the number c = a.b (hence, a integer part, and b decimal part)?

If quicker is meant in terms of speed, my usage recommends me this:
float("%s.%s"% ("12", "345"))
timeit results:
>>> timeit.Timer('float("%s.%s"% ("12", "245"))').timeit()
0.39421987533569336
>>> timeit.Timer('float("{0}.{1}".format("12", "245"))').timeit()
0.573634147644043

Primitive formatting (might be the quickest? ): float(str(a) + '.' + str(b))
This solution doesn't need to parse a format string.
[Added as the answer to the disbelievers]
>>> timeit.Timer('float("%s.%s"% ("12", "245"))').timeit()
1.147318164738806
>>> timeit.Timer('float("{0}.{1}".format("12", "245"))').timeit()
1.5033958226534452
>>> timeit.Timer('float("12" + "." + "245")').timeit()
0.6646503955111598
Part of the explanation could be that you can always write %s even for the int arguments. It is likely that there is an extra string conversion when formatted via % or via .format().

Using float and format.
>>> a, b = '12', '345'
>>> float('{0}.{1}'.format(a, b))
12.345
EDIT: Cannot claim this is fastest (as I haven't tested the speed w.r.t. other solutions), but does get the job done.

This will raise a ValueError if a or b cannot be converted to integers (if not only digits for example):
float('%d.%d' % (int(a), int(b)))
(tested on Python 2.7)

Related

Python3 - solve math equations that are in string format [duplicate]

This question already has answers here:
Evaluating a mathematical expression in a string
(14 answers)
Closed 3 years ago.
Is there a way to solve math equations that are in string format?
For example, I have
x = 2
y = 3
equations_str = ('x+y', 'x-y')
and I want a function that will give
results = (5, -1)
I want to do this because I want to have the equations as titles of figures, so they need to be strings.
I'm aware that a similar question was asked for java, but I'm not familiar enough with java so translate it to python.
Thanks!
Look into eval() https://www.geeksforgeeks.org/eval-in-python/ You can write statements and execute them.
eval example (interactive shell):
>>> x = 1
>>> eval('x + 1')
2
>>> eval('x')
1
As Jam mentioned, you can do the following:
equations_str = (eval('x+y'), eval('x-y'))
The only way I can think of solving this problem is to take your equation, calculate it as a regular integer, and then convert it into a string using str(). Then you could put that result into an array before proceeding. The only thing is that this method won't work for large amounts, but if you only need a few, this should work. Hope this helps, Luke.
Try the sympify function of the sympy package. It lets you evaluate strings, but uses the eval function, so do not use it on unsanitized input.
Example:
>>> from sympy import sympify
>>> str_expr = "x**2 + 3*x - 1/2"
>>> expr = sympify(str_expr)
>>> expr
x**2 + 3*x - 1/2
>>> expr.subs(x, 2)
19/2

What is the difference between a string and non-string? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm beginning to learn the basics of python. I had just learned that str() turns non-strings into strings - example: str(2) would change 2 to "2". That raised a question - what is a string and what difference does it have from a non-string? I've googled this but I could not find this question is directly answered and the general explanations don't quite make it clear for me.
"That raised a question - what is a string and what difference does it have from a non-string?"
It sounds like python is your first language. That being said, for conceptual sake, a string is text, and a 'non-string' is a number. You will see why this is not quite true as you program more, but for understanding the difference between a string and a 'non-string' this will suffice. You can do math with 'non-strings'. "2" is a string, but 2 is a 'non-string'. Adding strings is NOT the same as arithmetic addition. "2" + "2" results in another string "22" (this operation is called concatenation ), but 2 + 2 results in a 'non-string' A.K.A. the NUMBER (not string) 4, because the addition is arithmetic addition.
A string is any sequence of characters — not just numbers, but letters and punctuation and all of Unicode.
Something that isn't a string is... not that. :) (There are lots of things that aren't strings! String isn't special.) For example, 2 is an int. You can do math on an int, because it's a number. But you can't do math on a str like "2"; it's only the way we write the number in Western mathematics, not the number itself. You couldn't ask "dog" to wag its tail, either, because it's not a real dog; it's just the written word "dog".
As a more practical example:
2 + 2 gives you 4, the result of combining two numbers.
"2" + "2" gives you "22", the result of combining two written "words".
just to put another spin on this...
objects in python come with a variety of attributes and methods. attributes tend to represent data associated with the object. methods tend to represent behaviors that can be performed by the object. if we create a string and give it the name a and look at the list of attributes/methods, we see that the list encompasses many of the things you would want to know about a string or do with a string.
In [91]: a = '1' # assign a string the name 'a'
In [92]: a.
a.capitalize a.format a.isupper a.rindex a.strip
a.center a.index a.join a.rjust a.swapcase
a.count a.isalnum a.ljust a.rpartition a.title
a.decode a.isalpha a.lower a.rsplit a.translate
a.encode a.isdigit a.lstrip a.rstrip a.upper
a.endswith a.islower a.partition a.split a.zfill
a.expandtabs a.isspace a.replace a.splitlines
a.find a.istitle a.rfind a.startswith
on the other hand, if we create a number and give it the name b and look at the list of attributes/methods, we see that they are very different and focuses on things we would want to know about a number or do with a number.
In [92]: b = 1 # assign a number the name 'b'
In [93]: b.
b.bit_length b.denominator b.numerator
b.conjugate b.imag b.real

Check if a string contains date or timestamp in python [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I need to come up with a function which will take a single string and it will do the following :
check if it is a timestamp in UTC format (e.g. if it is of the form 2014-05-10T12:30:00).
If it is in the format described above, replace 'T' with space and return the string.
If it is not of timestamp, simply return the string.
What is the best way to accomplish this in python? I thought I could use datetime module. But can this be done using re module?
While zmo's answer is correct, I see many people, especially experienced sys-admins, who are excellent with regex opt, to often, to crafting their own regular expression.
Regular expressions are hard to maintain and to read, and Python's own STL offers some great tried and tested way to do it without the need to re-invent the correct regular expression.
Here is my 2 cent, Pythonic solution:
In[87]: import time
In[88]: correct = "2014-05-10T12:30:00"
In[89]: wrong = "some string" # will raise ValueError
In[90]: try:
time.strptime(correct, "%Y-%m-%dT%H:%M:%S")
correct = correct.replace('T',' ')
except ValueError:
pass
....
In [91]: correct
Out[91]: '2014-05-10 12:30:00'
In [93]: wrong = "foo bar baz"
In [94]: try:
time.strptime(wrong, "%Y-%m-%dT%H:%M:%S")
correct = correct.replace('T',' ')
except ValueError:
pass
....
In [95]: wrong
Out[95]: 'foo bar baz'
you can match using a regex:
>>> s1 = "1) check if it is a timestamp in UTC format (e.g. if it is of the form '2014-05-10T12:30:00')."
>>> s2 = "3) If it is not of timestamp, simply return the string."
>>> re.compile('\d\d\d\d-\d\d-\d\d\(T\)\d\d:\d\d:\d\d')
<_sre.SRE_Pattern object at 0x7f9781558470>
>>> s = re.sub(r'(.*\d\d\d\d-\d\d-\d\d)T(\d\d:\d\d:\d\d.*)',r'\1 \2',s1)
>>> print(s)
1) check if it is a timestamp in UTC format (e.g. if it is of the form '2014-05-10 12:30:00').
>>> s = re.sub(r'(.*\d\d\d\d-\d\d-\d\d)T(\d\d:\d\d:\d\d.*)',r'\1 \2',s2)
>>> print(s)
3) If it is not of timestamp, simply return the string.
>>>
Play with it
The trick here, is to catch groups left and right of the T character, and paste them again around a space. As a bonus, if there's no match, there's no substitution.

Pi calculation in python [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
n=iterations
for some reason this code will need a lot more iterations for more accurate result from other codes, Can anyone explain why this is happening? thanks.
n,s,x=1000,1,0
for i in range(0,n,2):
x+=s*(1/(1+i))*4
s=-s
print(x)
As I mentioned in a comment, the only way to speed this is to transform the sequence. Here's a very simple way, related to the Euler transformation (see roippi's link): for the sum of an alternating sequence, create a new sequence consisting of the average of each pair of successive partial sums. For example, given the alternating sequence
a0 -a1 +a2 -a3 +a4 ...
where all the as are positive, the sequences of partial sums is:
s0=a0 s1=a0-a1 s2=a0-a1+a2 s3=a0-a1+a2-a3 s4=a0-a1+a2-a3+a4 ...
and then the new derived sequence is:
(s0+s1)/2 (s1+s2)/2 (s2+s3)/2 (s3+s4)/2 ...
That can often converge faster - and the same idea can applied to this sequence. That is, create yet another new sequence averaging the terms of that sequence. This can be carried on indefinitely. Here I'll take it one more level:
from math import pi
def leibniz():
from itertools import count
s, x = 1.0, 0.0
for i in count(1, 2):
x += 4.0*s/i
s = -s
yield x
def avg(seq):
a = next(seq)
while True:
b = next(seq)
yield (a + b) / 2.0
a = b
base = leibniz()
d1 = avg(base)
d2 = avg(d1)
d3 = avg(d2)
for i in range(20):
x = next(d3)
print("{:.6f} {:8.4%}".format(x, (x - pi)/pi))
Output:
3.161905 0.6466%
3.136508 -0.1619%
3.143434 0.0586%
3.140770 -0.0262%
3.142014 0.0134%
3.141355 -0.0076%
3.141736 0.0046%
3.141501 -0.0029%
3.141654 0.0020%
3.141550 -0.0014%
3.141623 0.0010%
3.141570 -0.0007%
3.141610 0.0005%
3.141580 -0.0004%
3.141603 0.0003%
3.141585 -0.0003%
3.141599 0.0002%
3.141587 -0.0002%
3.141597 0.0001%
3.141589 -0.0001%
So after just 20 terms, we've already got pi to about 6 significant digits. The base Leibniz sequence is still at about 2 digits correct:
>>> next(base)
3.099944032373808
That's an enormous improvement. A key point here is that the partial sums of the base Leibniz sequence give approximations that alternate between "too big" and "too small". That's why averaging them gets closer to the truth. The same (alternating between "too big" and "too small") is also true of the derived sequences, so averaging their terms also helps.
That's all hand-wavy, of course. Rigorous justification probably isn't something you're interested in ;-)
That is because you are using the Leibniz series and it is known to converge very (very) slowly.

Why does exponential notation with decimal values fail? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
Conventionally 1e3 means 10**3.
>>> 1e3
1000.0
>>> 10**3
1000
Similar case is exp(3) compared to e**3.
>>> exp(3)
20.085536923187668
>>> e**3
20.085536923187664
However now notice if the exponent is a float value:
>>> exp(3.1)
22.197951281441636
>>> e**3.1
22.197951281441632
which is fine. Now for the first example:
>>> 1e3.1
File "<stdin>", line 1
1e3.1
^
SyntaxError: invalid syntax
>>> 10**3.1
1258.9254117941675
which shows Python does not like 1e3.1, Fortran too.
Regardless it could be a standard (!) why it is like that?
The notation with the e is a numeric literal, part of the lexical syntax of many programming languages, based on standard form/scientific notation.
The purpose of this notation is to allow you to specify very large/small numbers by shifting the point position. It's not intended to allow you to encode multiplication by some arbitrary power of 10 into numeric literals. Therefore, that point and the following digits aren't even recognised as part of the numeric literal token.
If you want arbitrary powers, as you've found, there are math functions and operators that do the job. Unlike a numeric literal, you even get to determine the parameter values at run-time.
From the docs:
sign ::= '+' | '-'
digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
indicator ::= 'e' | 'E'
digits ::= digit [digit]...
decimal-part ::= digits '.' [digits] | ['.'] digits
exponent-part ::= indicator [sign] digits #no dots allowed here
You seem to be conflating syntax for literals with operators. While you can claim that 1e3.1 follows your "convention" it should be quite clear that 1e3.1 is not a valid literal expression to the Python interpeter. The language has a defined standard grammar, and that grammer doesn't support floating point literal expressions as "exponents" for its numeric literals.
The "e" in a Python numeric literal is not an operator (any more than the decimal point would be). So your expectation that Python's literal syntax should support some "convention" ... based on some pattern you've divined ... is not particularly reasonable.

Categories

Resources