-1
import random, string

goal='methinks it is like a weasel'

def simulation(length):
   return ''.join(random.choice('abcdefghijklmnopqrstuvwxyz ') for i in range(length))

def score(stri):
    if stri==goal:
        print(100)
    else:
        print(0)

n=0
stri='abcd'
while score(stri) != 100:
      n += 1
      stri = simulation(28)
print(n)

For the final while loop, as long as score(stri) not equal to 100, it'll iterate and accumulate n, correct? Then I'll printout the accumulated n , when score(stri) happened to equal 100.

But I got results like:

0
0
0
0
0
0
...

Obviously it's always outputing 'n=0'; it's because this is global variable?

But I then tried extremely easy while loop:

n=0
while n <= 5:
    n += 1
print(n)

It's successfully outputs 6

I don't know why my first code goes wrong, guess while loop gets sth wrong because of def()?

LookIntoEast
  • 8,048
  • 18
  • 64
  • 92
  • Because you aren't returnining anything from `score`, you are just printing, and thus `score` returns `None`. And `None != 100` will always evaluate to false. – juanpa.arrivillaga Mar 24 '17 at 00:00
  • Please continue with whatever tutorial you are using, and read the part about functions rather than asking this sort of fundamental question. – TigerhawkT3 Mar 24 '17 at 00:02
  • For the record, this example code you've given is, for all intents and purposes, an infinite loop. You have 27 options for each of 28 values, and each of the 28 values must match `goal` for the loop to end. The odds of that happening by chance (ignoring the issue of cycles in PRNG output which may reduce the odds to 0) are 1 in 27 ** 28. If your RNG was truly random (never cycles), it would still be over 132 bits of work before you had even a 50% chance of reaching your goal. For comparison, AES128 is considered impossible to brute force, and that's only 128 bits of work. This is >10x harder. – ShadowRanger Mar 24 '17 at 00:26

1 Answers1

0

You need to return from score instead of printing:

def score(stri):
    if stri == goal:
        return 100
    else:
        return 0

This is failing herewhile score(stri) != 100: because when you call the function score it is only printing (displaying output) and not returning a value to be used in the while loop condition.

tknickman
  • 4,285
  • 3
  • 34
  • 47