sawreals
sawreals

Reputation: 338

Convert True Values in a String to Int

list = ['JACOBIS','LIMANIS','FOXTROT']
word = input('enter a word in the list')
generatedword = (random.choice(list))

Possible Scenario When Program Run, if the user enters FOXTROT but the word was JACOBIS:

print("Your word contains 1/7 correct characters")

Possible Solutions:

if word == generatedword:
    print ("your word contains 7/7 correct characters")

Would the in operation be suitable in this scenario? For example:

print ("your word contains", len(str(generatedword)), "/7")

or

print ("your word contains", len(str(word)) in generatedword, "/7")

Upvotes: 3

Views: 94

Answers (1)

Kasravnd
Kasravnd

Reputation: 107287

First off, in is not a function it's an operator for membership checking operation.

Secondly you can not use in because you might have a word like hello and another word like he, and this is while he is in hello but the length of characters are not the same.

Instead you can use set.intersection() in order to find the common characters:

>>> a = "FOXTROT"
>>> b = "JACOBIS"

>>> len(set(a).intersection(b))
1

But note that you need to divide this by the length of set(b) for handling the words with duplicate characters.

Since this approach will give the counts based on the unique characters, if you want to get 2 for intersection of following example, you can use str.count() and sum() function like following:

>>> a = 'FOXTROT'
>>> 
>>> b = 'JACOBIS' 

>>> sum(a.count(i) for i in set(b))
2

This will give you sum of the count of all characters in first string that are in second one.

Upvotes: 2

Related Questions