Example #1
0
def main():
    """ Count the number of prime numbers less than two million and time
    how long it takes. Compares the performance of different algorithms
    """
    from get_positive_number_from_user import get_positive_num

    player_int = int(get_positive_num())
    timer = Stopwatch()
    print()
    print(format(' TimeIt - is_prime() ', '*^70'))
    timer.start() 
    print('{0} Is prime?: {1}'.format(player_int, is_prime(player_int)))
    timer.stop()
    print('Time taken = {0:.6f} Seconds'.format(timer.elapsed()))
    
    print()
    print(format(' TimeIt - prime_generator() ', '*^70'))
    timer.start()
    prime_gen_obj = prime_generator(0, player_int)
    timer.stop()
    print('{0} primes between 0 -> {1}'.format(
        len([t for t in prime_gen_obj]), player_int))
    print('Time taken = {0:.6f} Seconds'.format(timer.elapsed()))
    
    print()
    print(format(' TimeIt - primes_list_comprehension() ', '*^70'))
    timer.start()
    primes_list = primes_list_comprehension(player_int)
    timer.stop()
    print('{0} primes under {1}'.format(len(primes_list), player_int))
    print('Time taken = {0:.6f} Seconds'.format(timer.elapsed()))
    
    print()
def compare_LCS(seq1, seq2):
    """ Computes the longest common subsequence of seq 1 and seq2 in
        two different ways and compares the execution times of the two
        approaches. """
    timer_std = Stopwatch()  # Each function has its own stopwatch
    timer_memo = Stopwatch()  # to keep track of elapsed time independently
    timer_std.start()  # Time the standard LCS function
    subseq_std = LCS(seq1, seq2)
    timer_std.stop()
    timer_memo.start()  # Time the memoized LCS function
    subseq_memo = LCS_memoized(seq1, seq2)
    timer_memo.stop()
    # Report results
    print(seq1)
    print(seq2)
    print(subseq_std, len(subseq_std),
          '(Standard: {:f})'.format(timer_std.elapsed()))
    print(subseq_memo, len(subseq_memo),
          '(Memoized: {:f})'.format(timer_memo.elapsed()))
    print()
    # Show the computed longest common subsequences
    highlight(seq1, subseq_std)
    highlight(seq2, subseq_std)
    print()
    highlight(seq1, subseq_memo)
    highlight(seq2, subseq_memo)

    return timer_std.elapsed(), timer_memo.elapsed()
Example #3
0
def sieve(n):
    """
    Generates all the prime numbers from 2 to n - 1.
    n - 1 is the largest potential prime considered.
    Algorithm originally developed by Eratosthenes.
    """

    timer = Stopwatch()
    timer.start()   # Record start time

    # Each position in the Boolean list indicates
    # if the number of that position is not prime: 
    # false means "prime," and true means "composite."
    # Initially all numbers are prime until proven otherwise
    nonprimes = n * [False]  # Global list initialized to all False

    count = 0    

    # First prime number is 2; 0 and 1 are not prime
    nonprimes[0] = nonprimes[1] = True

    # Start at the first prime number, 2.
    for i in range(2, n):
        # See if i is prime
        if not nonprimes[i]:
            count += 1
            # It is prime, so eliminate all of its 
            # multiples that cannot be prime
            for j in range(2*i, n, i):
                nonprimes[j] = True
    # Print the elapsed time
    timer.stop()
    print("Count =", count, "Elapsed time:", timer.elapsed(), "seconds") 
Example #4
0
def sieve(n):

    """ Generates all the prime numbers from 2 to n - 1.
        n - 1 is the largest potential prime considered.
        Algorithm originally developed by Eratosthenes.
    """
    timer = Stopwatch()
    # Record start time
    timer.start()

    # Each position in the Boolean list indicates
    # if the number of that position is not prime:
    # false means "prime," and true means "composite."
    # Initially all numbers are prime until proven otherwise

    nonprimes = n * [False]

    count = 0

    nonprimes[0] = nonprimes[1] = True

    # Start at the first prime number, 2.
    for i in range(2, n):
        if not nonprimes[i]:
            count += 1

            for j in range(2*i, n, i):
                nonprimes[j] = True
    timer.slop()
    print('Count =', count, 'Elapsed time', timer.elapsed(), 'seconds')
class CountingStopwatch2:
    """ This counting stopwatch uses composition instead of 
        inheritance. """
    def __init__(self):
        # Create a stopwatch object to keep the time
        self.watch = Stopwatch()
        # Set number of starts to zero
        self._count = 0

    def start(self):
        # Count this start message unless the watch already is running
        if not self.watch._running:
            self._count += 1
        # Delegate other work to the stopwatch object
        self.watch.start()

    def stop(self):
        # Delegate to stopwatch object
        self.watch.stop()

    def reset(self):
        # Let the stopwatch object reset the time
        watch.reset()
        # Reset the count
        self._count = 0

    def elapsed(self):
        # Delegate to stopwatch object
        return self.watch.elapsed()

    def count(self):
        return self._count
def test_searches(lst):
    from stopwatch import Stopwatch
    timer = Stopwatch()
    # Find each element using ordered linear search
    timer.start()  # Start the clock
    n = len(lst)
    for i in range(n):
        if ordered_linear_search(lst, i) != i:
            print("error")
    timer.stop()  # Stop the clock
    print("Linear elapsed time", timer.elapsed())
    # Find each element using binary search
    timer.reset()  # Reset the clock
    timer.start()  # Start the clock
    n = len(lst)
    for i in range(n):
        if binary_search(lst, i) != i:
            print("error")
    timer.stop()  # Stop the clock
    print("Binary elapsed time", timer.elapsed())
Example #7
0
def count_primes(n):
    """ Generates all the prime numbers from 2 to n - 1.
    n - 1 is the largest potential prime considered.
    """
    timer = Stopwatch()
    timer.start()

    count = 0
    for val in range(2, n):
        root = round(sqrt(val)) + 1
        # Try all potential factors from 2 to the square root of n
        for trial_factor in range(2, root):
            if val % trial_factor == 0:
                break
            else:
                count +=1
    timer.stop()
    print('Count =', count, 'Elapsed time: ', timer.elapsed(), 'seconds')
Example #8
0
def analyse(word: str) -> WordInfo:
    timer = Stopwatch()
    timer.start()

    pronounciation = to_romanji(word)
    syllables = to_roman_syllables(word)

    warnings = detect_problems(word)  # Detect english characters etc.

    phonetic_approx = approximate_word_phonetic(word, alpha=0.1)

    syntactic_approx = approximate_word_syntactical(word, alpha=0.5)

    timer.stop()
    time = timer.elapsed()

    return WordInfo(word, pronounciation, syllables, warnings, time,
                    phonetic_approx, syntactic_approx)
Example #9
0
def count_primes(n):
    """
    Generates all the prime numbers from 2 to n - 1.
    n - 1 is the largest potential prime considered.
    """
    timer = Stopwatch()  
    timer.start()          # Record start time

    count = 0
    for val in range(2, n):
        root = round(sqrt(val)) + 1
        # Try all potential factors from 2 to the square root of n
        for trial_factor in range(2, root):
            if val % trial_factor == 0:  # Is it a factor?
                break                  # Found a factor
        else:
            count += 1                 # No factors found

    timer.stop()    # Stop the clock
    print("Count =", count, "Elapsed time:", timer.elapsed(), "seconds")
Example #10
0
                "state": last_state,
                "action": action,
                "next_state": ob,
                "reward": reward,
                "end_ep": done
            })

        agent.learn(buffer)
        epsilon_greedy_evolution.append(agent.epsilon_greedy)
        print("Train epoch {}/{} sum reward={} epsilon_greedy={:.4f}".format(
            i, MIN_EPOCH, sum_reward, agent.epsilon_greedy))

    learning_timer.stop()
    # Close the env and write monitor result info to disk
    env.close()

    print("Learning time: {:.2f}s".format(learning_timer.elapsed()))
    plt.plot(reward_evolution)
    plt.title(
        "Évolution des récompenses obtenues par l'agent au cours des itérations"
    )
    plt.xlabel("Itérations")
    plt.ylabel("Récompense")
    plt.show()
    plt.plot(epsilon_greedy_evolution)
    plt.title("Évolution de epsilon greedy au cours des itérations")
    plt.xlabel("Itérations")
    plt.ylabel("Epsilon greedy")
    plt.show()
    print(buffer)
    print(sampling(buffer, 4))