Home > Enterprise >  Simon Says challenge activity
Simon Says challenge activity

Time:09-23

I am brand new to coding and working my way through an intro class via Zybooks. This challenge activity is asking me to add one point to user_score for every letter that is a match and break the loop when there is a mismatch. Simon_pattern and user_pattern are both input. This is the code I have so far:

user_score = 0
simon_pattern = input()
user_pattern  = input()


for character in simon_pattern:
    for input in user_pattern:
        if input == character:
            user_score  = 1
            continue
        
    if input != character:
        break
    
print('User score:', user_score)

The code works, but the returned value is wrong. Given simon_pattern ='RRGBRYYBGY'and user_pattern = 'RRGBBRYBGY' the output should be User Score: 4, but my User Score is coming out as 3.

I'm not quite sure what part of my code needs fixing and unfortunately zybooks does not give you any hints. Thanks in advance for the help of this awesome community!!

CodePudding user response:

Hi and welcome to coding! A few notes: Notice how the input() function is used to gather input from the user? Because of this, it is considered a keyword and it is bad practice to name your variables input, because it will overwrite the reference to the function.

Now considering your problem. Instead of a nested loop I would use a single for lop and check the characters at each index within both strings. If they match, add a point. Otherwise, break the loop. You also want to stop the loop if it goes beyond the number of characters in either pattern. One trick for that is to find the minimum length between both patterns. The min function is useful for this.

user_score = 0
simon_pattern = input()
user_pattern  = input()


length = min(len(simon_pattern), len(user_pattern))

for i in range(length):
    if user_pattern[i] == simon_pattern[i]:
        user_score  = 1
    else:
        break
        

print('User score:', user_score)

CodePudding user response:

This should work :

user_score = 0
simon_pattern = input()
user_pattern  = input()


for simon_character, user_character in zip(simon_pattern, user_pattern):
    if simon_character == user_character:
        user_score  = 1
    else:
        break

print('User score:', user_score)

Be careful not to redefine the Python keywords such as input or print for example. The rest of your program could be modified if you need to reuse these functions

  • Related