Is there a logical operator in python for and/or of strings?

I am trying to write a weasel code. What I have so far:

import random
import math

keys='abcdefghijklmnopqrstuvwxyz ' 

monkey='methinks it is like a weasel'

def attempt():
	attempt=''
	for i in range(len(monkey)):
		x=random.choice(keys)
		attempt+=x
	return(attempt)

library_attempts=[]
for i in range(100):
	library_attempts.append(attempt())
	
matches=[]
for i in library_attempts:
	if i[0]=="m" | i[1]=="e" or i[2]=="t" or i[3]=="h" or i[4]=="i" or i[5]=="n" or i[6]=="k" or i[7]=="s" or i[8]==" " or i[9]=="i" or i[10]=="t"\
	or i[11]==" " or i[12]=="i" or i[13]=="s" or i[14]==" " or i[15]=="l" or i[16]=="i"\
	or i[17]=="k" or i[18]=="e" or i[19]==" " or i[20]=="a" or i[21]==" " or i[22]=="w"\
	or i[23]=="e" or i[24]=="a" or i[25]=="s" or i[26]=="e" or i[27]=="l":
		matches.append(i)
		
print len(matches)

I want the or in my code to mean and/or, but I don't know how to do that. Any help would be greatly appreciated!

Dani AI

Generated

Brief recap and what to do next. wants to estimate how many random draws it takes to reach a target phrase by "locking" correct letters. correctly flagged the use of the bitwise | where a logical or belongs, and rightly pointed out the combinatorial size of the search space. The key is to pick and measure a clear process: are you counting full random-strings generated, or single random-letter draws used to fill one position at a time? Those are completely different problems.

Two processes and their expected costs

  • Full-string sampling: if the alphabet has A symbols and the target length is L, there are A^L possible strings. Expectation to hit the target by sampling whole strings uniformly at random is on the order of A^L (astronomical for realistic L).
  • Sequential lock (one letter at a time): each letter is a geometric trial with success probability 1/A, so the expected number of single-letter draws to fix one position is A. Summing over L positions gives expected draws ≈ L * A. This is why locking drastically reduces required draws compared to full-string sampling. See the geometric distribution for the expectation formula.

Example implementation (letter-by-letter locking)

import random

def trial_count(target, alphabet):
    total_draws = 0
    built = []
    for want in target:
        while True:
            total_draws += 1
            if random.choice(alphabet) == want:
                built.append(want)
                break
    return "".join(built), total_draws

# set alphabet and target appropriately

Notes and cautions

  • Be explicit what a "trial" counts (one letter vs one full string) before reporting averages.
  • Avoid storing huge lists of samples; loop and accumulate counts instead.
    Further reading: the Weasel program background (Weasel program) and the geometric distribution expectation (Geometric distribution). For operator behavior, see Python boolean operations (Python docs).

Recommended Answers

All 7 Replies

For

if i[0]=="m" | i[1]=="e"

in your code, should it be

if i[0]=="m" or i[1]=="e"

?

SNIPPED

And/or is two different things. If you want "a" or "b" then if either one is true the code is executed (the other can be false). If you want "a" and "b", the code is executed only if both are true. "And" is the same as two if() statements, "or" is the same as an if()/else() statement. Some pseudo-code:

## both have to be true
if x =="a" and x == "b" is the same as
if x == "a"
    if x == "b"
#
## either can be true
if x == "a" or x == "b" is the same as
found = False
if x == "a"
    found = True
elif x == "b"
    found = True

For

if i[0]=="m" | i[1]=="e"

in your code, should it be

if i[0]=="m" or i[1]=="e"

?

Practice Python Online
http://pyschools.com

Hmm. It doesn't seem like what I want to accomplish can be done with the syntax I am imposing.

If am trying to search over a dictionary of random strings (of length 28) and return a new list of strings which are have the the same characters in the same positions of my string monkey...haha And then I want to do this over and over again until I reach the same string as monkey generated randomly. I think I need to try something else!

You can compare the random letters word and the original word. It took 150,000 and 300,000 iterations to get a word equal to the 10 character word in the test, so expect a 28 character word to take a really, really long time.

import random

test_word = "methinks "
test_list = list(test_word)

## try 10 tries
for ctr in range(10):
    random.shuffle(test_list)
    back_to_word = "".join(test_list)
    print back_to_word
    if back_to_word == test_word:
        print "EQUAL", ctr

It is supposed to estimate the number of trials it takes to generate the target phrase:
for example once you get m randomly by a # of trials, you keep m then see how many it takes to get e randomly ect, then see how many trials it takes to get the whole phrase.
Any ideas on how to format this better? It seems easier than I am trying to go about it

Use string.lowercase() to generate a list of letters, then use
for letter in test_word:
to iterate through each letter in the word. random.choice() will choose one random letter (from string.lowercase) and compare, (print the letter and random.choice for the first few letters tried to see what is happening). Add the number of tries it took to a total tries field.

I think this is best approaced mathematically counting
(len(string.lowercase)+1)**len(target)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.