#๐ help
246 messages ยท Page 1 of 1 (latest)
@idle mortar
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.
this is the output
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
the words shouldnt be lower case only the letter
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")
I can see in the example that some of the words do have upper
i know but the task explicitly says case sensitive
if it was case sensitive, why would you convert the letter to lower then?
good point
yes, but it also stops the function at that point
a function will never proceed past its return
yes that aswell, so where should i put the not found
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?
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
Hey @idle mortar!
```py
print('Hello, world!')
```
This will result in the following:
print('Hello, world!')```
no?
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"
ok, is the new code valid?
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'"
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?
try it and see
when i run it in vs code i get no input?
you would need to call the function with some arguments still
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)
you're not printing
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)
wow this is very complicated for me at the moment
make sure you've given them all a proper attempt first though
ye i have, it made me stuck
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
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)
Hey @idle mortar!
```py
print('Hello, world!')
```
This will result in the following:
print('Hello, world!')```
i dont know how to do that
Read this embedded message
so '''
with backticks
amd at the end?
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
What issues do you get when you try and run it through the tester?
Can you show the full error
Do you understand what a dict's "keys" and "values" are?
ok, so when you do for student in students, what do you think student is?
and what are the keys in the students dictionary?
the grades
reverse
so what is student then?
yes
grade
yes, so i should do student['alice']
no, strings don't have keys
How do you look up a value in a dict?
menu = {'burger': 9.99, 'fries': 3.99, 'drink': 1.99}
you want a function?
if I have this, how do I get the price of fries?
by indexing?
show me the syntax
menu['fries']
perfect
!e
menu = {'burger': 9.99, 'fries': 3.99, 'drink': 1.99}
for item in menu:
print(item)
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 | burger
002 | fries
003 | drink
if I'm looping through this dict, I only get the keys
how would I get the prices then?
use the index of the keys
again, show me
menu['fries'[0]]
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?
item[0]
menu
item
menu[item]
yes ๐
!e
menu = {'burger': 9.99, 'fries': 3.99, 'drink': 1.99}
for item in menu:
print(menu[item])
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 | 9.99
002 | 3.99
003 | 1.99
when we loop through a dict, it only accesses the keys
if we want the value, we need dict_name[key_name]
so students[student]
yes ๐
no grade_dict[student] as i am adding it to the new dictonary
you still need students[student] to access the grade of the dict you're looping through
everything else you had was perfect
the only line you needed to change was grade = ...
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
i see i need to work ahrd
harder
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
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)
:white_check_mark: Your 3.14 eval job has completed with return code 0.
{'A': 2, 'B': 1, 'C': 1}
lots of different ways to solve things ๐
ye i see, but i think i firstly need to grasp a single way than build upon it
yeah, that's ok
I find I learn the most when I already have the solution, and then I can see other approaches
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
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
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
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
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
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
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
you can easily create the file for testing, it's just a few lines
I do also need to get going shortly ๐
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?
parts will show a split of the data in each line
remove everything else, just do print(parts)
for line in file:
line = line.strip()
parts = line.split(',')
print(parts)
ok, so what does that tell you?
there is only 0 index
You expected it to be name and value
yes
but why? You tried splitting it
cause it is in a list
split always returns a list
oh
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?
ye a dictonary was my thought
what does split do?
split each data by a delimiter
and which delimiter did you choose?
are there any , in the line?
tab? or which would be the best use
yes?
!e
text1 = 'hello world'
print(text1.split())
text2 = 'hello world'
print(text2.split())
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 | ['hello', 'world']
002 | ['hello', 'world']
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
ok
This is what debugging is. You need to connect the dots on why things didn't work out the way you thought
so what should i do just like you spli()
there was clearly an issue with the split
so that's a good time to maybe improve your understanding of how split works
yes
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
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.