简体   繁体   中英

Iterate through a string to find matching characters and produce different emoji

How do I call contains_char from my emojified function?

I want to be able to iterate through the guess_word to see if there are any matching letters in the secret_word . If there are matching letters, the output should have green emoji boxes. If there are no matching letters, the output should have white emoji boxes. If there are letters present but they are not in the right position, the output should have yellow boxes.

def contains_char(any_length: str, single_character: str) -> bool:
    """Loop iterates through each character in string to find matching character."""
    assert len(single_character) == 1
    if single_character in any_length:
        return True 
    else:
        return False

def emojified(guess_word: str, secret_word: str) -> str:
    """A way to match letters to its corresponding emoji color output. """
    assert len(guess_word) == len(secret_word)
    WHITE_BOX: str = "\U00002B1C"
    GREEN_BOX: str = "\U0001F7E9"
    YELLOW_BOX: str = "\U0001F7E8"
    emoji_color: str = ""
    i: int = 0 
    contains_char
    while i < len(guess_word):
        if guess_word[0] == secret_word[0]:
            emoji_color += GREEN_BOX
        else:
            emoji_color += WHITE_BOX
            
        print(emoji_color)

I want the output to look like this picture below. Thank you!

图片

You are vastly overcomplicating this.

def emojified(guess_word: str, secret_word: str) -> str:
    assert len(guess_word) == len(secret_word)
    WHITE_BOX: str = "\u2B1C"
    GREEN_BOX: str = "\U0001F7E9"
    YELLOW_BOX: str = "\U0001F7E8"
    output: list = []
    this_box: str = ''
    for i, char in enumerate(guess_word):
        if i < len(secret_word) and secret_word[i] == char:
            this_box = GREEN_BOX
        elif char in secret_word:
            this_box = YELLOW_BOX
        else:
            this_box = WHITE_BOX
        output.append(this_box)
    return ''.join(output)

The assert is perhaps not the best way to handle this; Python can disable assert statements in some situations. If the check should be part of your production logic, probably refactor it to raise an exception instead.

The condition i < len(secret_word) is redundant if you make sure both strings are the same length, but I thought it safer to leave it in in case you want to relax that condition.

Appending to strings is relatively expensive, so a good practice is to collect things into a list and only join the list into a string at the end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM