#🔒 help for nerdle type game

218 messages · Page 1 of 1 (latest)

boreal bison
#

why there is a error in line 0
i have no idea what's happen...
and the deadline is 21/10

steady kernelBOT
#

@boreal bison

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

gleaming pilot
#

You will need to show your code or nobody will be able to help you.

boreal bison
#

here is the screen shot

#

@gleaming pilot
i really need your help🫠

gleaming pilot
#

You need to print out the value of postfix just before the eval call.

boreal bison
#

def cal(guess):
parts = guess.split("=")
if len(parts) != 2 or "=" in parts[1]:
print("Invalid equation")
return "Invalid equation"
LHS = parts[0].strip()
RHS = parts[1].strip()
try:
result_LHS = eval(LHS)
except Exception as e:
return f"Invalid LHS: {e}"
if str(result_LHS) == RHS:
return "True"
else:
print("Invalid equation: LHS is not equal to RHS")
return "Invalid equation"

gleaming pilot
#

!code

steady kernelBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

boreal bison
#

the original code is this
but it cant handle the BODMAS rule
so....
i seek help from chatGPT
and this happen.🫠

gleaming pilot
#

chatgpt is a terrible way to get advice. It doesn't know anything.

boreal bison
#

yeah
so i seek help here

gleaming pilot
#

Please format the above code as shown above. To preserve the indenting and punctuation.

boreal bison
#

ok

gleaming pilot
#

As I mentioned before, we need to see the string you're passing to eval or we have no idea what the eval doesn't like.

#

So put a print() before the eval to show the string.

boreal bison
gleaming pilot
#

This is totally different code!

boreal bison
#

def givehint(guess, word, guess_num):
    correct_letters = {letter for letter, correct in zip(guess, word) if letter == correct}
    available_hints = [char for char in word if word not in correct_letters]
    if available_hints:
        hint = random.choice(available_hints)
        position = word.index(hint)
        if position+1 == 1:
            pot = "st"
        elif position+1 == 2:
            pot = "nd"
        elif position+1 == 3:
            pot = "rd"
        else:
            pot = "th"
        print("The", position + 1, pot, "word on the answer is", hint, "!")
    else:
        print("No more unique hints available.")```
boreal bison
gleaming pilot
#

We only do one probem at atime.

boreal bison
#

...

#

ok

#

we should improve the chatGPT code
or just add BODMAS rule to the logic of original code?

#

i have no idea what's happening of the chatGPT code

gleaming pilot
#

You should be writing the code yourself. That way you at least know what you were trying to do.

boreal bison
#

determine is the LHS of equation is equal to the RHS
by define the hierarchy of * and / be 2 , + and - be 1
the logic will first calculate higher hierarchy

#

is this concept legit?

gleaming pilot
#

Yes. This is the convention for written arithmetic expressions. Multiplication and division bind more tightly than addition and subtraction. So that 3 * 4 + 1 is 13 and not 15.

#

Python expressions also obey this convention.

#

The chatgpt code reads an expression from the user and breaks it apart on the = character getting a left hand side and a right hand side.

#

Then it evals the left hand side as a Python expression, letting Python do all the work.

boreal bison
#

im from HK
im sorry that i cant catch up ur pace

gleaming pilot
#

The try/except here:

try:
    result_LHS = eval(LHS)
except Exception as e:
    ...

evaluates LHS as a Python expression and places the result in the result_LHS variable.

#

The try/except is for when the expression is not valid Python. Python raises an exception when that occurs, and the except is what should happen is an exception is raised.

#

It is important to print() the string you gave to eval() along with the exception so that you can see what Python tried to evaluate.

gleaming pilot
boreal bison
#
def main(guess_num):
    # Pre-process
    word = get_random_word()
    print(word)
    # Process (main loop)
    while guess_num < 7:
        guess = str(input(f"\nGuess {guess_num}: "))
        if guess == "hint":
            givehint(guess, word,guess_num)
            guess_num += 1
        else:
            val_result = validation(guess)
            cal_result = cal(guess)
            print(cal_result)
            if val_result == "true" and cal_result == "True" :
                show_guess(guess, word)
                guess_num += 1
        if guess == word:
            print("you are correct!")
            break
    else:
        game_over(word)
#

this is the main loop

gleaming pilot
#

We're back to the hint problem?

boreal bison
#

my bad

boreal bison
#

the user will input : 12+48=60

gleaming pilot
#

Ok. After the code splits this up into LHS and RHS, print them out. TO make sure that they're as you expect.

boreal bison
#

and the cal() will spilt it into
Guess 1: 12+48=60
12+48
60
True
Correct letters: +, =
Misplaced letters: 1, 4
Wrong letters: 0, 2, 6, 8

gleaming pilot
#

A core part of debugging is checking that what you thought was happening is what is actually happening. often by printing various values as you go.

boreal bison
#

so what should i do rn?

gleaming pilot
#

You're feeding expressions to your hint code. What's this got to do with the first piece of code?

#

You've got two pieces of code.
One reads a nerdle type equation. Like 12+48=60.
The other reads a guess word and compares it to some target word.

boreal bison
gleaming pilot
#

Well we should work on just one problem.

boreal bison
#

ok

gleaming pilot
#

Pick one.

boreal bison
#

there are 3 aim i want to done today
1.BODMAS rule
2.rich
3.hint

#

and i think the BODMAS rule is the most inportant

gleaming pilot
#

Ok.

#

1: Where'd the code you have come from?
2: what was the specification of the BODMAS problem?

boreal bison
#

user input 10/2+3=8
the result is Invalid equation: LHS is not equal to RHS

gleaming pilot
#

Can you paste in the code you ran to get the above output?

boreal bison
#

the homework just call me to do a nerdle variable of this tutorial
https://nerdlegame.com/
https://realpython.com/python-wordle-clone/

In this step-by-step project, you'll build your own Wordle clone with Python. Your game will run in the terminal, and you'll use Rich to ensure your word-guessing app looks good. Learn how to build a command-line application from scratch and then challenge your friends to a wordly competition!

boreal bison
# gleaming pilot Can you paste in the code you ran to get the above output?
def cal(guess):
    parts = guess.split("=")
    if len(parts) != 2 or "=" in parts[1]:
        print("Invalid equation")
        return "Invalid equation"

    LHS = parts[0].strip()
    print(LHS)
    RHS = parts[1].strip()
    print(RHS)

    try:
        result_LHS = eval(LHS)
    except Exception as e:
        return f"Invalid LHS: {e}"

    if str(result_LHS) == RHS:
        return "True"
    else:
        print("Invalid equation: LHS is not equal to RHS")
        return "Invalid equation"
gleaming pilot
#

Well, nerdle is the one where people guess an equation from some oncomplete template?

#

Ok, let's walk through this code. You wrote this?

boreal bison
#

yes

gleaming pilot
#

Ok, so you know what the parts do then, however correctly or incorrectly?

boreal bison
#

i just dry run 1 time to show you the logic?

gleaming pilot
#

On the theme of printing things out, in the else: part at the end you should print out what result_LHS actually is. So that you can see what it might not be considered correct.

gleaming pilot
boreal bison
#

user input:12+48=60
spilt to:
LHS= 12+48
RHS= 60
eval the LHS
12+48
to 60
LHS == RHS
output true

gleaming pilot
#

Seems legit.

#

So let's take your failing example then: 10/2+3=8

boreal bison
#

ok

gleaming pilot
#

What do you expect it to do? Like your dry run above.

boreal bison
#

i want to first define the by define the hierarchy of * and / be 2 , + and - be 1

gleaming pilot
#

Ok. So on that basis, what operations happen in the LHS?

#

I was thinking like your dry run above:

user input:10/2+3=8
spilt to:
LHS= 10/2+3
RHS= 8
eval the LHS
10/2+3
to 8
LHS == RHS
output true

This is the logic you expect?

boreal bison
#

wait
did the eval() support BODMAS ?

gleaming pilot
#

And that is your clue!
See you have: 8
and 8.0 ?

#

eval() does support BOSMAS.

#

You have the value 8 from both sides.

boreal bison
#

bruhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

gleaming pilot
#

But see that they are printed differently?

boreal bison
#

i debug the BODMAS for an hour

#

.......

gleaming pilot
#

Aye. And you didn't, technically, need to. because eval() does BODMAS for you.

#

So back to why it fails.

#

Let's say the equation is correct. And that eval() does not raise an exception, so you get a result in result_LHS.

boreal bison
#

maybe int()?

#

but it need to support decimal

gleaming pilot
#

That would fix this problem. It is close to the actual bug.

#

Yeah.

#

So: the rsult was 8.0.

#

The RHS isn't a number though, is it. It's a string, the string "8".

#

This is why you tested str(result_LHS) == RHS.

#

But what you actually want to test is a numeric comparison. Are these 2 numbers equal?

boreal bison
#

so delete str()?

gleaming pilot
#

Yes.

#

But then you will always get a false test, because numbers and strings are never equal.

boreal bison
#

FFFFFFFFFFFFFFFFFFFFF
i just wasted an hour

#

🫠

gleaming pilot
#

That is the way with debugging.

#

So what you want to know is: do both sides of the equation evaluate to the same number?

#

That suggests that you should also compute:

result_RHS = eval(RHS)
#

and then compare result_LHS == result_RHS

boreal bison
#

why you need to eval the RHS?

gleaming pilot
#

To turn it into a number. It is a string.

boreal bison
#

oh
that does make sense

gleaming pilot
#

Here's me doing some of this interactively:

>>> LHS = '10/2+3'
>>> RHS = '8'
>>> LHS
'10/2+3'
>>> RHS
'8'
>>> result_LHS = eval(LHS)
>>> result_LHS
8.0
>>> result_LHS == RHS
False
>>> 8.0 == '8'
False
>>> result_RHS = eval(RHS)
>>> result_RHS
8
>>> 8.0 == 8
True
>>> result_LHS == result_RHS
True
#

See how the numbers are equal. Even though one is a float (8.0) and one is an int (8).

boreal bison
#

praise god
thank you so much

#

IT WORK!!!!!

gleaming pilot
#

Do you see how the logic works here?

#

Does my interactive example above make what's going on more clear?

boreal bison
#

yup
before: str == number
after : num == num

gleaming pilot
#

Correct.

#

Well, actually.....

#

Before you went str(result_LHS) == RHS.

#

That's str == str

#

But it doesn't work, because one str is '8.0' and the other str is '8'. And they are not the same.

#

But if you evaluate both side, you get two numbers. And they do compare as equal.

boreal bison
#

ok lets face the hint problem?

gleaming pilot
#

If you like. I'm going to have to leave at some point.

boreal bison
#

ohh......
i'll close this help when i finish the hint problem

#

the logic is by randomly choose a digit from answer and is not guessed by the user

#

maybe i should add another variable and store all the previous digit?

#

and not choose those letter?

gleaming pilot
#

Well, it looks like your givehint function is correct.

#

I assume the code which calls it is not doing what you want.

boreal bison
#

wdym?

gleaming pilot
#

Actaully, maybe it isn' correct. Your code which computes the available_hints seems wrong.

#

You test word in correct_letters, but I think you want to test char in correct_letters?

boreal bison
#

it's from chatGPT

gleaming pilot
#

Oh.Do you understand it then?

boreal bison
#

i know what to do in the logic

#

maybe dry run?

gleaming pilot
#

Then you need to check if the code is a correct implementation of the logic.

#

If you want a dry run, by all means do it.

#

But also, as with the other problem: print the values of correct_letters and available_hints to see if they are as you expect.

boreal bison
#

correct_letters = every letter that the user input that is correct in both position and value by comparing to answer

available_hints = every letter of the answer that is not in correct_letters

if there is have an available hints,

randomly choice a letter in available_hints

and mark the position of the hint by word.index(hint)

gleaming pilot
#

Yes, that logic sounds correct.

#

Is that what you see happen?

boreal bison
gleaming pilot
#

But consider your statement: "available_hints = every letter of the answer that is not in correct_letters"
This is correct.

But look at the code:

available_hints = [char for char in word if word not in correct_letters]

The first char is "every letter". "in word" is for char in word (where these letters come from).
But it is supposed to be testing if the letter is not in correct_letters. That's char.
But it actually checks word not in correct_letters. It's testing the wrong value.

#

Also, you should print guess and word. (Just looking at your correct_letters print, which prints an empty set.)

boreal bison
gleaming pilot
#

Your description of available_hints was "available_hints = every letter of the answer that is not in correct_letters". Which is correct.

But the code is not correct.

#

It picks among the characters from word those for which this test is true: word not in correct_letters.

#

But it should be checking: char not in correct_letters.

#

Because you're picking the chars which are not in correct_letters. But the code as written does not look at char, it looks at word.

#

Part of the problem here is that this mistake is easy to make because Python does not have a "character" type. It only has strings, and characters are just strings with just one character in them. So you can ask if a string like word is in a set of individual characters (correct_letters) and the language won't complain. It just will always give you a false result.

boreal bison
#

so the target of the randomly choice is wrong?

gleaming pilot
#

No, the way you compute available_hints is wrong.

#

But also: print out guess and word at the start of the function:

print("guess", guess)
print("word", word)

That will tell you more about what you should expect in the following results, and also if you're even calling the function with what you should be calling it.

boreal bison
gleaming pilot
#

So you're really typing hint as your guess, when the word you are trying to match is 3*4-11=1 ?

#

And not a guess like 3*4?

boreal bison
#

yup

gleaming pilot
#

ok then

boreal bison
#
def main(guess_num):
    # Pre-process
    word = get_random_word()
    print(word)
    # Process (main loop)
    while guess_num < 7:
        guess = str(input(f"\nGuess {guess_num}: "))
        if guess == "hint":
            givehint(guess, word,guess_num)
            guess_num += 1
        else:
            val_result = validation(guess)
            cal_result = cal(guess)
            print(cal_result)
            if val_result == "true" and cal_result == "True" :
                show_guess(guess, word)
                guess_num += 1
gleaming pilot
#

Oh....

#

So hint is a special instruction.

boreal bison
#

yes

#

if the user input hint
it will show hint
else
it will go through the normal process

gleaming pilot
#

I would write the guess= stuff a little differently. The input from the user should go into some other variable, because as things are you're overwriting the guess variable, and giving a hint based on the guess being the string "hint".

Try something like this:

entry = input(f"\nGuess {guess_num}: ")
if entry == "hint":
    givehint(guess, word, guessnum)
else:
    guess = entry
    val_result = ....... # as before

This way you don't store what the user types in guess until you've made sure it is not the special instruction.

#

I'd also set guess = "" up the top before the loop. So that it has a value if the very first thing the user types is "hint".

boreal bison
#

that does make different
it add another lock of the input

gleaming pilot
#

"lock"?

boreal bison
#

to ensure the input

gleaming pilot
#

Ok.

#

(Also, you don't need str(input(......)). The return from input() is always a string.)

boreal bison
#

oh i didnt knew that b4

gleaming pilot
#

That's why you'll see things which ask for a number go something like number = int(input("give me a number: ")). They're taking the string from input() and converting it to an int.

boreal bison
#

ohhh

#

so now i should create a list to store all the location of previous hint
and if the position = word.index(hint)
is equal to the list
do it again
else
output the hint

#

is this legit?

gleaming pilot
#

It would work. Until you have used all the hint positions. Then it might pick forever and never find an unused hint position.

#

If the length of the list of previously-hinted-positions was equal to the lngth of word then you know that all positions have been offered as hints.

boreal bison
gleaming pilot
#

... and if the answer were shorter than 6?

boreal bison
#

i download all the nerdle ans from github

gleaming pilot
#

I'm just saying that I wouldn't rely on the limit on the number of guesses preventing this situation (all hints used) from happening.

#

Or I would check that the guess limit was in fact less than the length of the current answer.

boreal bison
#

also the validation(guess) function make sure user must input a equation that len(guess) ==8

#
acceptables= set('1234567890+-*/=')
guess_num = 1
def validation(guess) :
    if guess not in acceptables:
        if guess != "hint":
            if any(digit not in acceptables for digit in guess):
                print ("You cant do anything but arithmetical operations!")
            elif len(guess) != 8 :
                print ("you can only input a equation length is 8")
            elif guess.find("=") == -1 :
                print("invaild equation, please enter again.")
            else :
                return "true"
gleaming pilot
#

You should be able to drop the if guess != "hint": because you should not call validation is the user entered hint. And, indeed, guess should not be set to hint.

#

But this: guess not in acceptables isn't the right test. You want to ask: are all the letters in guess present in acceptable.

#

But in Python an in test is actually a substring search.

>>> "abc" in "abcdef"
True
>>> "cab" in "abcdef"
False

What you actaully need to do is check very character in guess individually against acceptable.

boreal bison
#

i want to make sure:
1.input is present in acceptable
2.length of input is equal to 8
3.there are must be a equal sign in the equation
if all those statement is true
output val_result to "true"

gleaming pilot
#

However, acceptable is a set. This means that you can do something simpler: make a set of the latters from guess, and subtract acceptable. If anything is left, then those letters were not in acceptable.

#

So something like:

guess_letters = set(guess)
if guess_letters - acceptable:
    ... the guess contains unacceptable letters ...
boreal bison
gleaming pilot
#

Yes, both are fine.

#

Do you understand how the second version works?

boreal bison
#

yup the set meant every symbol in the set is in acceptables

gleaming pilot
#

Yes. That is the same approach I'm suggesting above to compute guess_letters.

#

Once you have a set of the letters in guess, you can subtract the set of acceptable characters.

#

That gets you a set of the unacceptable letters from guess.

#

If that set is not empty, there were unacceptable letters.

#

Thus the if-statement above.

boreal bison
#

thanks for ur help
my brain was exhausted
i cant handle it no more
i just want to take a dinner and take a rest
friend request sent🫡
thanks sooooo much for ur help
my python teacher are also using chatGPT to finish this project bruh☠️

gleaming pilot
#

I am rolling my eyes. It is possible your python teacher is nearly as new to python as you are.

#

Taking a brwak is a good idea. So is sleep.

#

BTW, the if-statement above is using a feature of Python.

#

In Python we have this notion of "truthy" and "falsey" values: values which test as true or false in an if. (Or a while.)

#

In Python, containers like lists, tuples and sets are "truthy" if they are not empty, and "falsey" is they are empty.

#

So the:

if guess_letters - acceptable:

produces a new set, and if that set if not empty it is "truthy".

#

It is like testing:

if len(guess_letters - acceptable) > 0:
#

Just for later. Take a break. Ifyou're in Hong Kong I'[m 3 hours ahead of you. I'll be going to sleep.

boreal bison
#

friend request sent🫡

gleaming pilot
#

Going offline.

steady kernelBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.