Friday 13 September 2019

Python: Which is Quicker to Search a String, Find or In?

There are many ways to do the same task in Python, as with most things. Here I wanted to know which was quicker to see if a string contained a space:
if x.find(' ') != -1:
or
if ' ' in x:
So a little test...
import datetime x = 'abc def' r = 100000000 def test_a(): if x.find(' ') != -1: pass def test_b(): if ' ' in x: pass start = datetime.datetime.now() for a in range(0, r): test_a() print('Test A: ' + str(datetime.datetime.now()-start)) start = datetime.datetime.now() for a in range(0, r): test_b() print('Test B: ' + str(datetime.datetime.now()-start))
... found that ...
Test A: 0:00:27.240583 Test B: 0:00:13.469368
"in" being the clear winner here and no real surprise as "find" has to do more work to return the character's position.

Thursday 21 February 2019

HTML Character Codes

There are several websites which list the popular HTML Character Codes but if you need to view them all, this short HTML Javascript snippet will list all the numbered codes in your browser.

<html> <head> <style> table { border-collapse: collapse; } th { width: 3em; padding: 0.6em; background: lightgray; color: darkslategray; font-size: 0.6em; } td { width: 3em; padding: 0.6em; display: inline-block; border: 1px solid lightgray; text-align: center; } </style> </head> <body> <table> <script> for (i=0; i<80000; i++) { document.write('<tr><th>&#' + i + ';</th><td> &#' + i + '; </td></tr>'); } </script> </table> </body> </html>

Tuesday 22 January 2019

Adding Floating Point Numbers in Python

I've recently been doing some work in Python and noticed that it can't add floating point numbers correctly! I Googled it and found that this isn't a bug, it's expected because the C code underneath converts the floating point into a fraction to add the numbers and not all numbers can be converted to fractions and vice-versa!!

It may be expected but it is definitely in no way correct.

With my limited knowledge I've created this function to convert the floating point numbers to decimals, perform the addition, then convert back to floating point.

def add_floats(v): multiplier = 1 for i in v: multiplier = max(len(str(i)) - str(i).find('.'), multiplier) multiplier = 10**multiplier total = 0 for i in v: total += (i * multiplier) total = total / multiplier return total x = float('1.41') y = float('1.4') z = x+y print(x+y) print(add_floats([x, y]))
Output:

2.8099999999999996 2.81
My Python knowledge is limited, so if anyone wishes to improve this, please let me know.