I want to know why Java is accepted over Python when it comes to runtime. On performing the following Euler problem, Python takes up less lines and runs faster (Python ~0.05s, Java ~0.3s on my machine).
Could I optimize this Java code in any way? The problem is here (http://projecteuler.net/problem=22)
Python:
def main():
names = open("names.txt", "r").read().replace("\"", "").split(",")
names.sort()
print sum((i + 1) * sum(ord(c) - ord('A') + 1 for c in n) for i, n in enumerate(names))
if __name__ == "__main__":
main()
Java:
import java.util.Arrays;
import java.lang.StringBuilder;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class euler22
{
public static String readFileAsString(String path) throws IOException
{
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(
new FileReader(path));
String buffer = null;
while((buffer = reader.readLine()) != null)
{
builder.append(buffer);
}
reader.close();
return builder.toString();
}
public static void main(String[] args) throws IOException
{
String[] names = fileAsString("names.txt").replace("\"", "").split(",");
int total = 0;
Arrays.sort(names);
for(int i = 0; i < names.length; ++i)
{
int sum = 0;
for(char c : names[i].toCharArray())
{
sum += c - 'A' + 1;
}
total += (i + 1) * sum;
}
System.out.println(total);
}
}
with open('file.txt', 'r') as fin: names = fin.read()...
for better safety. You also probably can speed up the Java reading piece a bit if you tokenize things manually. Java's and Python's io library must differ, and one is taking more advantage of hardware maybe \$\endgroup\$