Monkey Theorem - pick random letters until input string is generated
<p>I wanted to make a code resembles the infinite monkey theorem
<strong>the theorem states that:</strong> </p>

<blockquote>
  <p>a monkey hitting keys at random on a typewriter keyboard for infinite
  amount of time will almost surely type a given text such as the
  complete works of Shakespeare.</p>
</blockquote>

<p>well , suppose we replace a monkey with a python to generate one sentence of Shakespeare ? and calculate the trials</p>

<p>for example: "methinks it is like a weasel"</p>

<p>Here is what I wrote:</p>

<pre><code>def Monkey_Theorem(sentence):
    sentence.lower()
    string_letters = 'abcdefghijklmnopqrstuvwxyz'
    import random
    a = []
    l = ''
    x = 0
    trials = 0
    while x &lt; (len(sentence) - 1):
        trials += 1
        z = random.choice(string_letters)
        if z == sentence[x]:
            a.append(z)
            x += 1
        elif z == " ":
            trials -= 1
            a.append(" ")
        if x &gt; (len(sentence) - 1):
            l = ''.join(l)
            break
    return l and trials
</code></pre>

<p>I wrote this into python 2.7 IDLE , pressed enter then wrote:</p>

<pre><code>Monkey_Theorem("methinks it is like a weasel")
</code></pre>

<p>after that I pressed enter.. it moved to the next line and didn't come up with the (>>>) </p>

<p>and after sometime no result and when trying to close the IDLE with despair on my face , it says program still running</p>

<p><strong>HERE'S THE QUESTION :</strong>  </p>

<p>(A) is the while loop an infinite one ??<br>
(B) or my IDLE is slow ??<br>
(C) other cause<br>
and how to fix the reason</p>

<p><strong>One more request</strong> 
how to detect the case if I encounter this situation in the future whether it's (A) , (B) , (C)?</p>

<p>In your code, you set <code>string_letters = 'abcdefghijklmnopqrstuvwxyz'</code>. Notice that there is no space in <code>string_letters</code>, so when you have matched the entire first word <code>'methinks'</code> it is impossible to match the space after that word. So your loop continues infinitely.</p>

<p>You can solve that particular problem by adding a space to the end of the definition string of <code>string_letters</code>. But as others are pointing out, your code has other problems as well.</p>

<p>As for detecting which it is, include a way to stop your loop by a keypress or pressing ctrl+C or something similar. Then print the value of <code>trials</code> and see if it is a <em>very</em> large number. If so, you have an infinite or extremely long-running loop.</p>

python