2

I have a simple question regarding a issue present in a personal project of mine. I have a hang man game im creating in python for fun and the hidden word originally presents the user in the following method; say the word was hello, it would be '^^^^^', as every character is replaced by '^'. Now im trying to write a function that counts the amount of characters displayed in set string, so say i have a, and p guessed in apples and i now have the following view, 'app^^^',

Now heres my problem, I want to return a true or false boolean statement if more then half of the characters have been displayed so examples below; 'app^^^' = true because atleast 1/2 was displayed; therefore the return = true but like, 'a^^^^^' = false, not 1/2 of the chars were displayed,

tbh i feel bad not posting anything but i came up with an idea of how to do it; so i felt like if i could len(app^^^) but remove the count of '^' then if the count is greater then half of the len(app^^^) without '^' removed, return true, else; return false. I believe it could work but not sure how to do it, thanks again guys.

4

3 に答える 3

4

文字を数える代わりに、文字を数えます^

s = 'app^^^'

if s.count('^') >= len(s) / 2:
    # Half of the characters are `^`s
else :
    # Less than half ...
于 2012-10-19T03:27:42.317 に答える
1

思いついたソリューションを実装するコードは次のようになります。

def is_half_revealed(s):
    return len(s.rstrip('^')) / float(len(s)) * 2 >= 1

ただし、文字列を直接確認するのではなく、「回答のどの程度が明らかにされているか」を格納するデータが、ユーザーに表示される文字列とは別になるように、コードを再構築することを検討する必要があります。

于 2012-10-19T03:33:10.063 に答える
0

より一般的な解決策

def percent_solved(s):
    return 100 - s.count("^") * 100 / len(s)

if percent_solved(s) >= 50:
    ...
于 2012-10-19T05:16:19.800 に答える