I made a program in Python and wanted it to be faster, so I wrote it on C# because it's compiled. To my surprise, the Python program is much faster. I guess there is something wrong with my C# code, but it is pretty simple and straightforward, so I don't know. They are structured about the same way.
C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Diagnostics;
//This program generates a string of random lowercase letters and matches it to the user's input
//It does this until it gets a match
//It also displays the closest guess so far and the time it took to guess
namespace Monkey
{
class Program
{
static string userinput()
{
//Takes user input, makes sure it is all lowercase letters, returns string
string input;
while(true)
{
input = Console.ReadLine();
if (Regex.IsMatch(input, @"^[a-z]+$"))
{
return input;
}
}
}
static string generate(int len)
{
//generates string of random letters, returns the random string
Random rnd = new Random();
string alpha = "abcdefghijklmnopqrstuvwxyz";
int letterInt;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i++)
{
letterInt = rnd.Next(26);
sb.Append(alpha[letterInt]);
}
return sb.ToString();
}
static int count(int len, string s, string g)
{
//returns number of letters that match user input
int same = 0;
for (int i = 0; i < len; i++)
{
if(g[i] == s[i])
{
same++;
}
}
return same;
}
static void Main(string[] args)
{
Console.WriteLine("They say if you lock a monkey in a room with a typewriter and enough time,");
Console.WriteLine("the monkey would eventually type a work of Shakespeare.");
Console.WriteLine("Let's see how well C# does...");
Console.WriteLine("Enter a word");
Console.WriteLine("(3 letters or less is recommended)");
string solution = userinput();
int size = solution.Length;
bool success = false;
string guess = null;
int correct;
int best = 0;
Stopwatch watch = Stopwatch.StartNew();
while (!success)
{
guess = generate(size);
correct = count(size, solution, guess);
if (correct == size)
{
success = true;
}
else if (correct > best)
{
Console.Write("The best guess so far is: ");
Console.WriteLine(guess);
best = correct;
}
}
watch.Stop();
TimeSpan ts = watch.Elapsed;
Console.WriteLine("Success!");
Console.Write("It took " + ts.TotalSeconds + " seconds for the sharp C to type ");
Console.WriteLine("\"" + guess + "\"");
Console.ReadLine();
}
}
}
Python:
import random
import time
#This program generates a string of random letters and matches it with the user's string
#It does this until it's guess is the same as the user's string
#It also displays closest guess so far and time it took to guess
def generate():
# generate random letter for each char of string
for c in range(size):
guess[c] = random.choice(alpha)
def count():
# count how many letters match
same = 0
for c in range(size):
if guess[c] == solution[c]:
same += 1
return same
print("They say if you lock a monkey in a room with a typewriter and enough time,")
print("the monkey would eventually type a poem by Shakespeare")
print("Let's see how well a python does...'")
user = ""
badinput = True
while badinput:
# Make sure user only inputs letters
user = input("Enter a word\n(5 letters or less is recommended)\n")
if user.isalpha():
badinput = False
solution = list(user.lower())
size = len(solution)
guess = [""] * size
alpha = list("abcdefghijklmnopqrstuvwxyz")
random.seed()
success = False
best = 0 # largest number of correct letters so far
start = time.time() # start timer
while not success:
# if number of correct letters = length of word
generate()
correct = count()
if correct == size:
success = True
elif correct > best:
print("The best guess so far is: ", end="")
print("".join(guess))
best = correct
finish = time.time() # stop timer
speed = finish - start
print("Success!")
print("It took " + str(speed) + " seconds for the python to type ", end="")
print("\"" + "".join(guess) + "\"")
input()
Console.WriteLine
causing the output to block or some such thing. I have profiled a lot of C# programs in my day and very frequently -- well over 10% of the time -- my initial guess about the cause of a slowdown is utterly wrong. Engineers solve problems by reasoning about facts, not guesses. \$\endgroup\$