#πŸ”’ OMDb and Dad Jokes Mashup

44 messages Β· Page 1 of 1 (latest)

graceful thicket
#

Please help me with Get Jokes for a Long Word from the Plot Description and Put it All Together part

warped abyssBOT
#

@graceful thicket

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.

coarse scaffold
#

Okay, I'm just looking at the longest word and the jokes part. Do you have your joke fetching code completed?

coarse scaffold
#

Describe your current line of thinking and where you get stuck along that.

graceful thicket
#

when i grade my submission it shows like this

#

i need to get 100 percent to pass the course

coarse scaffold
#

Okay, so you've written code for 4 and 5?

graceful thicket
coarse scaffold
#

When posting code, please provide it as text. Please restrict the use of images to when there is a need to show graphical information.

#

!code

warped abyssBOT
#
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.

#

Hey @graceful thicket!

It looks like you pasted Python code without syntax highlighting.

Please use syntax highlighting to improve the legibility of your code and make it easier for us to help you.

To do this, use the following method:
```py
print('Hello, world!')
```

This will result in the following:

print('Hello, world!')```
You can **edit your original message** to correct your code block.
graceful thicket
#

def get_jokes(plot: str, verbosity=0) -> tuple[str, list[str]]:
    """Returns a tuple containing the longest word for which jokes were found
    and the joke itself. Break ties for longest word using the order in `plot`.
    Make sure that you strip punctuation from the word before you search for a joke.
    
    Parameters
    ----------
    plot : str
        The plot of a movie.
    
    verbosity : int (optional)
        If 0, no output is printed. If 1, some output is printed about which words were tried.
        Defaults to 0.
    
    Returns
    -------
    tuple[str, list[str]]
        A tuple containing the word that was used to search for a joke and a list of two joke strings.
    """
    
    words = plot.split()
    words = [re.sub(r'[^\w\s]', '', w) for w in words]
    words.sort(key=len, reverse=True)

    for word in words:
        if verbosity > 0:
            print(f"Trying word: {word}")
        
        jokes = get_joke_data(word)  
        if jokes:  
            return word, jokes
    return None, None

def get_joke_data(word):
    joke_database = {
        "dreams": [
            "I'm tired of following my dreams. I'm just going to ask them where they are going and meet up with them later.",
            "Dreams don't work unless you do!"
        ],
        "cat": [
            "Why did the cat sit on the computer? To keep an eye on the mouse!",
            "What do you call a pile of kittens? A meowtain!"
        ]
    }
    return joke_database.get(word, [])
coarse scaffold
#

I am puzzled by the verbosity parameter.

graceful thicket
#

for debugging or for getting more insights

coarse scaffold
#

Wait, I see.

#

You've been asked to return a tuple of (a string and a list of strings).

#

Why are you returning None, None?

#

Wait, I see it.

#

Sorry, I'm still playing catchup.

#

What you've done there is correct.

graceful thicket
#

okay

coarse scaffold
#

Your get_jokes function looks okay, though, and this isn't your fault, the type hinting should probably reflect the failure case of None, None.

#

My preference would be to raise an exception rather than return something out of type like that.

#

Anyway, that's on the question formulation, not you.

#

You don't appear to actually be communicating with the API.

graceful thicket
#
import re

def get_jokes(plot: str, verbosity=0) -> tuple[str, list[str]]:
    words = plot.split()
    words = [re.sub(r'[^\w\s]', '', w) for w in words]

    words.sort(key=len, reverse=True)

    for word in words:
        if verbosity > 0:
            print(f"Trying word: {word}")

        jokes = get_joke_data(word)
        if jokes:
            return word, jokes

    raise ValueError("No jokes found for any word in the plot.")

def get_joke_data(word):
    joke_database = {
        "dreams": [
            "I'm tired of following my dreams. I'm just going to ask them where they are going and meet up with them later.",
            "Dreams don't work unless you do!"
        ],
        "cat": [
            "Why did the cat sit on the computer? To keep an eye on the mouse!",
            "What do you call a pile of kittens? A meowtain!"
        ]
    }
    return joke_database.get(word, [])
coarse scaffold
#

Sorry, I should have been clear. I was not making a suggestion for your to alter your code to raise an exception in this case, as the rubric states that None, None should be returned in the event a joke cannot be found.

#

But I do like this a little better.

graceful thicket
#

You have failed this test due to an error. The traceback has been removed because it may contain hidden tests. This is the exception that was thrown:

AssertionError: The longest word for which jokes were found is incorrect with input 'The cat attended_for_the_first_time the class.'

coarse scaffold
#

Again, you do not appear to be communicating with the API that they've provided.

#

I would expect you should be.

#

Is there a reason you're not?

#

Or at least going through this caching thing you're being asked to.

warped abyssBOT
#

Hey @graceful thicket!

It looks like you're trying to paste code into this channel.

Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.

To do this, use the following method:
```py
print('Hello, world!')
```

This will result in the following:

print('Hello, world!')```
You can **edit your original message** to correct your code block.
graceful thicket
#
import re
import requests

def get_jokes(plot: str, verbosity=0) -> tuple[str, dict]:
    words = plot.split()
    words = [re.sub(r'[^\w\s]', '', w) for w in words]

    words.sort(key=len, reverse=True)

    for word in words:
        if verbosity > 0:
            print(f"Trying word: {word}")

        jokes = get_joke_data(word)
        if jokes:
            return word, {'results': [{'joke': joke} for joke in jokes]}

    raise ValueError("No jokes found for any word in the plot.")

def get_joke_data(word):
    api_url = f"https://icanhazdadjoke.com/search?term={word}&limit=2"
    
    headers = {"Accept": "application/json"}
    
    try:
        response = requests.get(api_url, headers=headers)
        response.raise_for_status()

        joke_data = response.json()

        return [joke['joke'] for joke in joke_data.get('results', [])]
    
    except requests.exceptions.RequestException as e:
        print(f"Error fetching jokes: {e}")
        return []

plot = "I had dreams of a cat."
result = get_jokes(plot, 1)
print(result)

assert result[0] == "dreams"
assert (
    result[1]['results'][0]['joke']
    == "I'm tired of following my dreams. I'm just going to ask them where they are going and meet up with them later."
)
coarse scaffold
#

The question does refer to a requests_with_caching, but we'll let that go for now.

#

I believe the question wants you to return a specific thing.

#

for get_joke_data

warped abyssBOT
#
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.