#๐Ÿ”’ help

246 messages ยท Page 1 of 1 (latest)

humble basinBOT
#

@idle mortar

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.

idle mortar
#

this is the output

round edge
#

You're converting the letter to lowercase but not the words too

#

you also don't need the 2nd loop

#

you can return "Not Found" after the first loop

#

oh and your indentation is off. You're returning within the loop

idle mortar
#

the words shouldnt be lower case only the letter

round edge
#
def find_longest_word_with_letter(words, letter):
    Long_word = ""
    new_letter = letter.lower()
    for word in words:
        if new_letter in word:
            if len(word) > len(Long_word):
                Long_word = word
        return Long_word  # This returns after the first cycle of the loop
    for word in words:
        if letter not in word:
            return("Not found")
round edge
idle mortar
#

i know but the task explicitly says case sensitive

round edge
#

no, it says case insensitive

idle mortar
#

oh

#

my bad

round edge
#

if it was case sensitive, why would you convert the letter to lower then?

idle mortar
#

good point

round edge
#

the main issue is your return in the loop

#

do you understand what return does?

idle mortar
#

yes it gives a value

#

i see i put it inside the loop

round edge
#

yes, but it also stops the function at that point

#

a function will never proceed past its return

idle mortar
#

yes that aswell, so where should i put the not found

round edge
#

after the loop, you should do a check. If long_word is still "", then it means you didn't find a match

#

do you know about ternary expressions?

idle mortar
#

def find_longest_word_with_letter(words, letter):
Long_word = ""
new_letter = letter.lower()
for word in words:
if new_letter in word.lower():
if len(word) > len(Long_word):
Long_word = word
if Long_word == "":
return ("Not found")
return Long_word

humble basinBOT
#

Hey @idle mortar!

Please edit your message to use a code block

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

This will result in the following:

print('Hello, world!')```
idle mortar
#

no?

round edge
#

A ternary expression is basically an if/else in 1 line

#
return long_word if long_word != "" else "Not Found"

#

this basically says "If we found a long word, return it, otherwise, return Not Found

#

we can technically even simplify it by removing the != ""

#
return long_word if long_word else "Not Found"
idle mortar
#

ok, is the new code valid?

round edge
#

no, your "not found" return should not be in the loop either

#

any return inside the loop is saying "return after we check the first word"

#

so you're basically saying "if the first word does not have the letter, return 'not found'"

idle mortar
#

ye my bad, bad indentation

#

def find_longest_word_with_letter(words, letter):
Long_word = ""
new_letter = letter.lower()
for word in words:
if new_letter in word.lower():
if len(word) > len(Long_word):
Long_word = word
if Long_word == "":
return ("Not found")
return Long_word

#

now?

round edge
#

try it and see

idle mortar
#

when i run it in vs code i get no input?

round edge
#

you would need to call the function with some arguments still

idle mortar
#

def find_longest_word_with_letter(words, letter):
Long_word = ""
new_letter = letter.lower()
for word in words:
if new_letter in word.lower():
if len(word) > len(Long_word):
Long_word = word
if Long_word == "":
return ("Not found")
return Long_word

user_words = ["apple", "banana", "cherry", "date"]
user_letter = "a"
longest_word = find_longest_word_with_letter(user_words, user_letter)

round edge
#

you're not printing

idle mortar
#

my bad

#

could you also help me with a couple more?

round edge
#

Also if you want to see some fun ways python can simplify logic, this would be my solution

def find_longest_word_with_letter(words, letter):
    words = [word for word in words if letter.lower() in word.lower()]
    return '' if not words else max(words, key=len)
idle mortar
round edge
#

it's not as scary as it looks at first ๐Ÿ˜‰

#

but sure I can help with a few more

idle mortar
round edge
#

make sure you've given them all a proper attempt first though

idle mortar
#

ye i have, it made me stuck

round edge
#

Let's see what you tried

#

can you also make sure you paste it with syntax highlighting? It can be hard to read code otherwise

idle mortar
#

def count_grade_frequency(students):
grade_dict = {}
for student in students:
grade = student['grade']
if grade in grade_dict:
grade_dict[grade] += 1
else:
grade_dict[grade] = 1
return grade_dict

students = {"Alice": "A", "Bob": "B", "Charlie": "A", "Dana": "C"}
grade_frequency = count_grade_frequency(students)

humble basinBOT
#

Hey @idle mortar!

Please edit your message to use a code block

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

This will result in the following:

print('Hello, world!')```
humble basinBOT
#
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.

round edge
idle mortar
#

so '''

round edge
#

with backticks

idle mortar
#

amd at the end?

round edge
#

```

#

at the start and end

#

```py
<put code here>
```

idle mortar
#
def count_grade_frequency(students):
    grade_dict = {}
    for student in students:
        grade = student['grade']
        if grade in grade_dict:
            grade_dict[grade] += 1
        else:
            grade_dict[grade] = 1
    return grade_dict

students = {"Alice": "A", "Bob": "B", "Charlie": "A", "Dana": "C"}
grade_frequency = count_grade_frequency(students)
#

ye

round edge
#

What issues do you get when you try and run it through the tester?

idle mortar
#

typeerror

#

on line 4

round edge
#

Can you show the full error

idle mortar
round edge
#

Do you understand what a dict's "keys" and "values" are?

idle mortar
#

yes, key is the thing that holds values

#

so like apple : 20

round edge
#

ok, so when you do for student in students, what do you think student is?

idle mortar
#

will be the key then

#

no value

round edge
#

and what are the keys in the students dictionary?

idle mortar
#

the grades

round edge
#

no they aren't

#

look again

idle mortar
#

reverse

round edge
#

so what is student then?

idle mortar
#

alice = key, grade = value

#

value

round edge
#

yes

idle mortar
#

grade

round edge
#

and you're trying to do student['grade']

#

"Alice"['grade'] doesn't really make sense

idle mortar
#

yes, so i should do student['alice']

round edge
#

no, strings don't have keys

idle mortar
#

they dont?

#

i didnt know

round edge
#

How do you look up a value in a dict?

#
menu = {'burger': 9.99, 'fries': 3.99, 'drink': 1.99}
idle mortar
#

you want a function?

round edge
#

if I have this, how do I get the price of fries?

idle mortar
#

by indexing?

round edge
#

show me the syntax

idle mortar
#

menu['fries']

round edge
#

perfect

#

!e

menu = {'burger': 9.99, 'fries': 3.99, 'drink': 1.99}

for item in menu:
    print(item)
humble basinBOT
round edge
#

if I'm looping through this dict, I only get the keys

#

how would I get the prices then?

idle mortar
#

use the index of the keys

round edge
#

again, show me

idle mortar
#

menu['fries'[0]]

round edge
#

not quite

#

item is our keys

#

the loop is accessing all the keys of the dict

#

we look things up in a dict using keys

#

and item is the key

#

so how would I use it then?

idle mortar
#

item[0]

round edge
#

item is not a dict

#

what is our dict here?

idle mortar
#

menu

round edge
#

yes

#

and what is our key?

idle mortar
#

item

round edge
#

ok

#

put them together

idle mortar
#

menu[item]

round edge
#

yes ๐Ÿ™‚

idle mortar
#

so it loops through each value

#

of the keys

round edge
#

!e

menu = {'burger': 9.99, 'fries': 3.99, 'drink': 1.99}

for item in menu:
    print(menu[item])
humble basinBOT
round edge
#

if we want the value, we need dict_name[key_name]

idle mortar
#

so students[student]

round edge
#

yes ๐Ÿ™‚

idle mortar
#

no grade_dict[student] as i am adding it to the new dictonary

round edge
#

you still need students[student] to access the grade of the dict you're looping through

idle mortar
#

ok

#

now i need to add it to grade dict

#

so grade_dict[grade]

round edge
#

everything else you had was perfect

#

the only line you needed to change was grade = ...

idle mortar
#

ok

#

next

#

hehe

round edge
#

now, there is actually 2 things you could do to simplify this more

#

you can loop through a dict's values instead of keys

#
def count_grade_frequency(students):
    grade_dict = {}
    for grade in students.values():
        if grade in grade_dict:
            grade_dict[grade] += 1
        else:
            grade_dict[grade] = 1
    return grade_dict
#

using students.values()

#

so that saves a line of code

#

we don't actually need the keys here at all

#

the other thing we can do is use something called "setdefault"

#

which is a really nice dictionary method that lets us set the value of new keys, but ignore them if they already exist

idle mortar
#

harder

round edge
#
def count_grade_frequency(students):
    grade_dict = {}
    for grade in students.values():
        grade_dict.setdefault(grade, 0)
        grade_dict[grade] += 1
    return grade_dict
#

so it all simplifies to this

idle mortar
round edge
#

if we really wanted to simplify, we could use collections.Counter

#

!e

from collections import Counter 

def count_grade_frequency(students):
    return dict(Counter(students.values()))

students = {"Alice": "A", "Bob": "B", "Charlie": "A", "Dana": "C"}
grade_frequency = count_grade_frequency(students)
print(grade_frequency)
humble basinBOT
round edge
#

lots of different ways to solve things ๐Ÿ™‚

idle mortar
round edge
#

I find I learn the most when I already have the solution, and then I can see other approaches

idle mortar
#

ye i see that aswell but i need to understand aswell what im looking at

#
def compute_totals_summary(filename):
    new_dict = {}

    with open(filename, 'r') as file:
        for line in file:
            line = line.strip()
            if not line: 
                continue
            parts = line.split()
            name = parts[0]
            value = int(parts[1])
            if name in new_dict:
                new_dict[name] += value
            else:
                new_dict[name] = value

    total = 0
    minimum = None
    maximum = None

  
    for num in new_dict.values():
        total += num
        if minimum is None or num < minimum:
            minimum = num
        if maximum is None or num > maximum:
            maximum = num

    average = total / len(new_dict) 

   
    return (new_dict, minimum, maximum, f"{average:.1f}")
#

this code is ai parts of it so i want to do it without ai

round edge
#

Open a new file and write as much of it as you can without ai

#

There's no way for me to tell what you know and what you don't know or what you wrote or didn't write

#

if you want to write it without ai, then start over

idle mortar
#
def compute_totals_summary(filename):
    new_dict = {}

    with open (filename, 'r') as file:
        for line in file:
            line = line.strip()
            if not line:
                continue
            parts = line.split(',')
            name = parts[0]
            value = int(parts[1])
            new_dict[name] = value

        total = 0
        minimum = 100
        

        for num in new_dict.values():
            total += num

        for num in new_dict.values():
            if num < minimum:
                minimum = num

        average = total / len(new_dict)
        
    return (f"{new_dict}, {total}, {minimum}, {average:.1f}")


#

this was my original one

round edge
#

Ok, so think about what you need to change

#

I really like using print to debug things

#

constantly print out values so you understand what's happening in the code

idle mortar
#

no

#
def compute_totals_summary(filename):
    new_dict = {}
    with open (filename, 'r') as file:
        for line in file:
            line = line.strip()
            parts = line.split(',')
            name = parts[0]
            value = int(parts[1])
            new_dict[name] = value
        total = 0
        minimum = 100
        average = 0
        for num in new_dict.values():
            total += num
        for num in new_dict.values():
            if num < minimum:
                minimum = num
        average = total / len(new_dict)
        new_average = float(average)
    return (f"{new_dict}, {total}, {minimum}, {new_average:.1f}")a


``` this was the original
round edge
#

my point still stands

#

Here's how I debug

#

print out a variable in your code

#

before you run the code, think about what you expect that value to be

#

then run it. If the value is not what you expected, then there's an issue with your logic or understanding

idle mortar
#

the thing is the file i need i dont have it is a example in a task for me to only write the code, and the task to give me the input

round edge
#

you can easily create the file for testing, it's just a few lines

#

I do also need to get going shortly ๐Ÿ™

idle mortar
#

no

#

..

#

this is the first error

#

on value = int(parts[1])

round edge
#

ok, so parts isn't what you expect

#

try print(parts) and see what it is

#

what do you think print(parts) will show you?

idle mortar
#

parts will show a split of the data in each line

round edge
#

ok, so try it

#

run the code and see if it matches what you think

idle mortar
#

it gives me list index out of range

#

so is it possibly not enough to index?

round edge
#

remove everything else, just do print(parts)

#
for line in file:
    line = line.strip()
    parts = line.split(',')
    print(parts)
idle mortar
#

['Alice 10']
['Bob 5']
['Alice 3']
['Charlie 7']

#

this is parts

round edge
#

ok, so what does that tell you?

idle mortar
#

there is only 0 index

round edge
#

You expected it to be name and value

idle mortar
#

yes

round edge
#

but why? You tried splitting it

idle mortar
#

cause it is in a list

round edge
#

split always returns a list

idle mortar
#

oh

round edge
#

but you expected it to give you a list of 2 items, and it only gave you a list of 1 item

#

so why didn't it split correctly?

idle mortar
#

ye a dictonary was my thought

round edge
#

what does split do?

idle mortar
#

split each data by a delimiter

round edge
#

and which delimiter did you choose?

idle mortar
#

, / etc

#

,

round edge
#

are there any , in the line?

idle mortar
#

no

#

so the split didnt work

round edge
#

so maybe you need a different delimiter...?

idle mortar
#

tab? or which would be the best use

round edge
idle mortar
#

yes?

round edge
#

!e

text1 = 'hello world'
print(text1.split())

text2 = 'hello      world'
print(text2.split())
humble basinBOT
round edge
#

when you don't provide a delimiter, it splits on "whitespace"

#

which means it treats all groupings of space as a single space

#

whitespace includes spaces, tabs, and newlines

idle mortar
#

ok

round edge
#

This is what debugging is. You need to connect the dots on why things didn't work out the way you thought

idle mortar
#

so what should i do just like you spli()

round edge
#

there was clearly an issue with the split

#

so that's a good time to maybe improve your understanding of how split works

round edge
#

split() with no argument

#

Also sorry but I must go now!

#

Good luck

#

Keep this process up. Print something, compare result, see where it fails

humble basinBOT
#
Python help channel closed using Discord native close action

This help channel has been closed. 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.