0

I am trying to compare digits of a string to other digits of another string. guess_str is my input turned into a string and then num_str is the randomly generated number turned into a string.

Example:

guess_str: 100

num_str: 201

How can I have it compare the two strings so that when I type 100 as guess_str it will compare to num_str showing that the number "1" that was input is part of num_str but not in the same spot?

In this I am wondering only about the second elif statement.

   num = random.randint(100,999)
   attempts = 1
   max_attempts = 10

   print(main())
   print(num)

 while attempts <= max_attempts:
  guess = int(input(f"Guess#{attempts}:\n> "))
  if guess == num:
      print("Hooray!! That is the correct number!")
    

      answer = input("Enter yes or no: ")
      if answer.lower() == "yes":
          main()
      elif answer.lower() == "no":
          print("Ok have a great day!")
          break

  else:
      guess_str = str(guess)
      num_str = str(num)
    
      for i, val in enumerate(str(num)):
          if guess_str[i] == val:
              print("Fermi".format(i))
        
          elif any(x in num_str for x in guess_str):
              print("Pico")
        
          elif guess_str != num_str:
              print("Bagels")
              break
        
    #adds attempt to game  
          else:
              attempts += 1
13
  • stackoverflow.com/questions/55543527/… Commented Apr 24 at 21:04
  • 2
    What is this code doing differently than what you want? Can you change it to a minimal reproducible example? Commented Apr 24 at 21:09
  • so when i run the program it generates a number in this case it was "204" when I input the number "477" it should come back with just Pico since the only common digit is "4" between them, but it is coming back with "Pico Pico Pico" Commented Apr 24 at 21:28
  • ` any(x in num_str for x in guess_str):` doesn't make use of i or val, and you only want it to execute once? It seems like that code shouldn't be in the loop at all unless I'm missing something. Commented Apr 24 at 21:52
  • so i went back and changed the code to the whole python script. it is supposed to be a number guessing game. the loop is per guess and i wanted it to only print "pico" once per guess where your guess has a number in the string just not in the same spot as the random number. not just once in general. for the any statement i am unsure it that is the correct function and now that im looking at it the x definitely makes no sense. sorry for the confusion its my first question, so phrasing is probably bad. Commented Apr 24 at 22:09

2 Answers 2

1

In your current code, when

guess_str = 213
num_str = 123

It will print 3 times because it should iterate through your str(num), and each time, it would print something.

Pico # i ==1, val = 1, run the first elif
Pico # i==2, val = 2, run the first elif
Fermi # i==3, val = 3, run the first if

Additionally, your attempts += 1 will never run because in your if-else logic, that 'else' branch would never happen.

I think you may want it like this

import random
def main():
    num = random.randint(100,999)
    attempts = 1
    max_attempts = 10

    print(num)
    while attempts <= max_attempts:
        guess = int(input(f"Guess#{attempts}:\n> "))
        if guess == num:
            print("Hooray!! That is the correct number!")
            

            answer = input("Enter yes or no: ")
            if answer.lower() == "yes":
                main()
            elif answer.lower() == "no":
                print("Ok have a great day!")
                break

        else:
            guess_str = str(guess)
            num_str = str(num)
            match_position = False
            match_char = False

            for i in range(len(num_str)):
                    if num_str[i] == guess_str[i]:
                        match_position = True
                        break
                    if num_str[i] in guess_str:
                        match_char = True
            
            if match_position:
                    print("Fermi")
            elif match_char:
                    print("Pico")
            else:
                    print("Bagels")

            attempts += 1
Sign up to request clarification or add additional context in comments.

Comments

1
# case 0: no character/digit is common among strings (NOT at ALL)
if all(x not in num_str for x in guess_str):
    print("Bagels")

# case 1: one or more common in both (ANY in .. IF also in ..),
#         that have same position (equal index)
elif any(guess_str.index(x) == num_str.index(x) for x in guess_str if x in num_str):
    print("Fermi")

# default: otherwise, at least a common character/digit anywhere
else:
    print("Pico")

Just like how you have used any, I've used all in first condition.

The second condition is with the same logic you have used any, to check whether some identical positions (same character, same index) exist. At the end, the conditional if x in num_str is important to filter what we get from iteration for x in guess_str: If a character from guess_str is not present in num_str we won't consider it as positional match (not common implies not identical, only the common ones can be on the same spot).

6 Comments

And what happens if guess_str='123' and num_str='456'?
@Chrispresso, Thanks for pointing out. I've corrected the code now.
Removing for-loop as "inlined" any(..) of generator-expression with condition (Fermi), inverting if with newly-introduced all() (Bagels) with left-over default in else-branch (Pico) .. 🤔️ for a Python-learner new to SO, this should be explained - code is not self-explaining, neither for what changed, nor the why.
@hc_dev, edited now. check
Fast edit removed syntax and left typos - I fixed that and tested: OK. Also elaborated comments for clarity, to let them explain the conditional case in human language. In textual explanation, added a bit to explain the purpose and effect of if condition following the generator-expression: it will not give an error, just skips the element when not present in both.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.