Python3.3: Square
Here the code on Python3.3:
import sys, re, math
str1 = str(sys.stdin.readlines())
Data = re.findall('bd+b', str1)
for i in reversed (Data):
print('%.4f' % math.sqrt(float(i)))
as you can see, this program grabs data (multi-line random string) from input, and search for every digits this string contains. After that just returns square root of every digit it finds.
Well, algorithm works, but not fast enough, and i have no idea how to optimize it. Please help me with that. What i need to do to optimize code above?
This is a negative result. I tried using a couple of tricks to make it faster, but it's only a little bit faster.
import sys, re, math
def find_numbers(f):
for line in f:
for word in line.split():
if word.isdigit():
yield float(word)
lst = list(find_numbers(sys.stdin))
lst.reverse()
for x in lst:
print('%.4f' % math.sqrt(x))
I thought reversing the list might be making it slow, but it didn't really make much difference when I just printed the numbers without reversing.
The fastest solution for Python would be to just run the above code in PyPy.
This is not a very difficult problem, and if you need speed, you might want to write a solution in C code. C code will be about as fast as you can get for this problem.
You can try loading and processing the file with Numpy:
import numpy as np
for i in reversed(np.fromfile(sys.stdin, sep=' ')**0.5):
print i
As a high-performance numeric library for Python, I'd expect it to be the fastest solution available to you.
You asked for Python, but this can be done pretty well in C. This C program does not reverse the numbers, but you can simply pipe the output through the tac
program, which is like cat
but reverses the lines.
In my tests this is about 3x the speed of the NumPy solution, and about 6x the speed of my Python solution or the original solution.
#include <ctype.h>
#include <math.h>
#include <stdio.h>
int
main()
{
char buf[1024];
char ch;
float f;
int i, n;
for (i = 0;;)
{
ch = getchar();
if (i > sizeof(buf))
{
fprintf(stderr, "number too long!n");
return 1;
}
if (isspace(ch) || EOF == ch)
{
if (i > 0)
{
buf[i] = ' ';
n = atoi(buf);
f = sqrtf(n);
printf("%0.4fn", f);
i = 0;
}
if (EOF == ch)
return 0;
continue;
}
buf[i++] = ch;
}
}
链接地址: http://www.djcxy.com/p/85732.html
上一篇: Matlab:优化器/求解器的准确性差
下一篇: Python3.3:Square