PROBLEM SET 8: COOKIE JAR | SOLUTION (CS50 PYTHON)

  Рет қаралды 22,447

Dors Coding School

Dors Coding School

Күн бұрын

Пікірлер: 34
@DorsCodingSchool
@DorsCodingSchool Жыл бұрын
👨‍💻 Learn How to Code with Private Classes - www.dorscodingschool.com/coachingplans ❓Having a hard time with CS50, FreeCodeCamp or Odin Project? Practice with our exclusive free coding platform: www.codingdors.com/ 🎯 Are You A Coding Expert? Take Our Free Quiz and Find Out - www.dorscodingschool.com/quiz
@joswinpreetham1278
@joswinpreetham1278 Жыл бұрын
Though your code passes all checks, it is slightly wrong. I guess we shouldn't use _capacity in the init method as any subsequent object.capacity calls method will not go through the error checking.
@hardikchojar9361
@hardikchojar9361 Жыл бұрын
Right however if you remove the underscore you will get an Attribute error, may I know how you could you fix that as well? Thanks 😊
@EatDrinkCook
@EatDrinkCook 8 ай бұрын
@@hardikchojar9361 To fix that you need to add setter
@YallLieBad
@YallLieBad 6 ай бұрын
just wanted to say this is the fist video iv been able to watch in a while were i don't need help in fact i already submitted and i just wanted to see if i am understanding classes. so far your videos have been a huge help thank you.
@PurpleDovee
@PurpleDovee 5 ай бұрын
HOOW ??? why does my code give errors tho class Jar: def __init__(self, capacity: int = 12): if capacity < 0: raise ValueError("Capacity cannot be negative") self._capacity = capacity self._count = 0 def __str__(self): if self._count >= 1: return '🍪' * self._count else: return 'zero cookies' def deposit(self, n: int): if n < 0: raise ValueError('Cannot deposit negative cookies') if n + self._count > self._capacity: raise ValueError('Cookies exceeded the capacity') self._count += n def withdraw(self, n: int): if n < 0: raise ValueError('Cannot withdraw negative cookies') if self._capacity < n: raise ValueError('Exceeded jar size.') elif self._count < n: raise ValueError(f'Insufficient cookies. You only have {self._count} cookies') self._count -= n @property def capacity(self): return self._capacity @property def size(self): return self._count def main(): try: capacity_input = int(input('Enter Capacity [Default : 12]: ') or 12) jar_instance = Jar(capacity_input) print(jar_instance) deposit_input = int(input('Enter number of cookies to DEPOSIT: ')) jar_instance.deposit(deposit_input) print(jar_instance) withdraw_input = int(input('Enter number of cookies to WITHDRAW: ')) jar_instance.withdraw(withdraw_input) print(jar_instance) capacity_op = jar_instance.capacity print(f'The capacity is {capacity_op}') size_op = jar_instance.size print(f'The current size is {size_op}') except ValueError as e: print(e) if __name__ == '__main__': main()
@penteronto
@penteronto Жыл бұрын
class Jar: def __init__(self, capacity=12) -> None: self.capacity = capacity self.size = 0 def __str__(self) -> str: return f"{'🍪'*self.size}" def deposit(self, n: int) -> None: self.size += n def withdraw(self, n: int) -> None: self.size -= n @property def capacity(self) -> int: return self._capacity @capacity.setter def capacity(self,capacity: int) -> None: if capacity < 0: raise ValueError("Invalid capacity of the jar") self._capacity = capacity @property def size(self) -> int: return self._size @size.setter def size(self,size: int) -> None: if size < 0: raise ValueError("Too few cookies") if size > self.capacity: raise ValueError("Too many cookies") self._size = size
@mossnter5435
@mossnter5435 Жыл бұрын
Dziękuje Panie Piotrze, dzięki Panu zrozumiałem jak zastosować checking w setterze Miłego dnia :)
@JavierTejeda-o5b
@JavierTejeda-o5b Жыл бұрын
class Jar: def __init__(self, capacity = 12): self._capacity = capacity self._size = 0 def __str__(self): return "🍪"*self._size def deposit(self, n): self._size += n def withdraw(self, n): self._size -= n @property def capacity(self): return self._capacity @capacity.setter def capacity(self, value): if value < 0: raise ValueError ("Capacity cannot be negative") @property def size(self): return self._size @size.setter def size(self, value): if value > self._capacity or value < 0: raise ValueError ("The number of cookies is over/under the capacity of the jar")
@kevinklein2562
@kevinklein2562 Жыл бұрын
Hi there. How are you able to modifired a "self.size" parameter in the __init__ function - if there is only a parameter for (self, capacity)? Isn't it true you can only define the parameters that are listed?
@hetdesai832
@hetdesai832 Жыл бұрын
Apparently, that is not true. You can define additional parameters in a class, that are not explicitly passed to the __init__ method. But these attributes will have the same values for all instances of that class, as these are initialized manually, rather than through the constructor
@federicosmandelli9706
@federicosmandelli9706 Жыл бұрын
Why in the init function you don’t add also size=0?
@MoneyViKK
@MoneyViKK Жыл бұрын
How do I get the cookie to show up like this ("🍪🍪🍪") in my text editor it shows up like an outline. How do I fix it. I was trying to paste it, but it's actually printing the cookie..
@RonWaller
@RonWaller Жыл бұрын
Highlight cookie in the instructions and paste it into your code. Then set as a string character.
@prashansa-shrestha
@prashansa-shrestha Жыл бұрын
def withdraw(self,n): self._size-=n if n>self._size: raise ValueError("You want to withdraw more cookies than there are in the jar!") this is my withdraw method but it doesnt pass the cs50 check, the error is: :( Jar's withdraw method removes cookies from the jar's size expected exit code 0, not 1
@federicoelevazo3622
@federicoelevazo3622 2 жыл бұрын
Hi Giovanna, I am still confused with self.capacity. Why is it that it got an error without the underscore and when you added the underscore, why should we need to put underscore to both instances of self.capacity? I am stuck with these objects and methods thing :(
@DorsCodingSchool
@DorsCodingSchool 2 жыл бұрын
It's something that you must use when working with classes. I highly recommend you reading about classes in Python on w3schools.com
@invalid.reference
@invalid.reference Жыл бұрын
It's because you can't have functions and variables in a class with the same names. Under the @property decorator, using def(), you are defining a function called capacity. That will collide with the variable self.capacity, since functions and variables can't have duplicate names in a class.
@laishrammanao1467
@laishrammanao1467 Жыл бұрын
same here bro
@devlean
@devlean 2 жыл бұрын
Giovana, no meu projeto final eu preciso fazer um teste de todas as funções que escrevi? Fiz um sisteminha no terminal de controle de estoque e utilizei bastante função, porém estou na dúvida se vou precisar fazer um teste com todas elas ou se apenas 3 testes já são suficientes.
@DorsCodingSchool
@DorsCodingSchool 2 жыл бұрын
Muito legal! No projeto final você não precisa testar todas as funções, apenas 3 já são suficientes (:
@elhamhosseini1248
@elhamhosseini1248 Жыл бұрын
how to test this class for the case when it returns ValueError?
@jasperlee4750
@jasperlee4750 2 жыл бұрын
Hi Giovana~ I just finished my cookie jar before watching the video, but I still have some questions about using setter in this case. In my program, I used setter decorator to set value for size and capacity. However, I found some functions like deposit and withdraw couldn’t use the setter decorator because they didn’t have to use getter. So my first question is, do you recommend using setter in this case? And how do I use setter decorator in deposit and withdraw functions ?
@DorsCodingSchool
@DorsCodingSchool 2 жыл бұрын
We’d love to help you more. Did you know you can join our Free Discord Group and get help from me and from people around the world that are also learning how to code? dorscodingschool.com/discord
@aigerimabseit816
@aigerimabseit816 2 жыл бұрын
are both "n" and "self. size" means # of cookies?
@DorsCodingSchool
@DorsCodingSchool 2 жыл бұрын
It depends on the case. If it is the first time you're adding cookies, n will be the same as self.size. But if it already has cookies, they won't be the same thing. By the way, we have a Telegram Group to help people learn how to code and where you can connect with learners from all over the world. Over there you can ask any question about programming and you can easily get your questions answered within 24 hours. Besides that, you will have access to our membership with more than 400 problems made by us to ease your learning curve and 2 hours of group coaching every week! Check www.dorscodingschool.com/products
@aigerimabseit816
@aigerimabseit816 2 жыл бұрын
thanks @@DorsCodingSchool
@gamelifer234
@gamelifer234 Жыл бұрын
Great guide. I wonder if you can explain more why converting self.capacity to self._capacity make it work. What does that _ mean in this context.
@DorsCodingSchool
@DorsCodingSchool Жыл бұрын
The leading underscore, _, indicates to users they need not modify this value directly. _capacity should only be set through the capacity setter. Notice how the capacity property simply returns that value of _capacity, our class attribute that has presumably been validated using our capacity setter. When a user calls jar.capacity, they’re getting the value of _capacity through our capacity “getter”. We’d love to help you more. Did you know you can join our Free Discord Group and get help from me and from people around the world that are also learning how to code? dorscodingschool.com/discord
@invalid.reference
@invalid.reference Жыл бұрын
It's because you can't have functions and variables in a class with the same names. Under the @property decorator, using def(), you are defining a function called capacity. That will collide with the variable self.capacity, since functions and variables can't have duplicate names in a class.
@EatDrinkCook
@EatDrinkCook 8 ай бұрын
It's not correct to use self._capacity in __init__() function, David explained that on the lecture, you must add the setter and put there your self._capacity like it was on the lecture.
@Baseballbat95
@Baseballbat95 6 ай бұрын
Do we need to do that for capacity and size? or just capacity
@EatDrinkCook
@EatDrinkCook 6 ай бұрын
@@Baseballbat95 for both capacity and size
@reamageorge9648
@reamageorge9648 Жыл бұрын
thank you
PROBLEM SET 8: SEASONS OF LOVE | SOLUTION (CS50 PYTHON)
23:05
Dors Coding School
Рет қаралды 20 М.
Правильный подход к детям
00:18
Beatrise
Рет қаралды 11 МЛН
VIP ACCESS
00:47
Natan por Aí
Рет қаралды 30 МЛН
How Strong Is Tape?
00:24
Stokes Twins
Рет қаралды 96 МЛН
Леон киллер и Оля Полякова 😹
00:42
Канал Смеха
Рет қаралды 4,7 МЛН
PROBLEM SET 7: NUMB3RS | SOLUTION (CS50 PYTHON)
16:11
Dors Coding School
Рет қаралды 17 М.
CS50P - Lecture 8 - Object-Oriented Programming
2:47:42
CS50
Рет қаралды 611 М.
PROBLEM SET 6: PIZZA PY | SOLUTION (CS50 PYTHON)
17:08
Dors Coding School
Рет қаралды 13 М.
Caroline Polachek - Welcome To My Island [Official Music Video]
3:57
Caroline Polachek
Рет қаралды 3,5 МЛН
PROBLEM SET 5: TESTING MY TWTTR | SOLUTION (CS50 PYTHON)
11:34
Dors Coding School
Рет қаралды 24 М.
PROBLEM SET 1: DEEP THOUGHT | SOLUTION (CS50 PYTHON)
13:28
Dors Coding School
Рет қаралды 23 М.
PROBLEM SET 7: WORKING 9 TO 5 | SOLUTION (CS50 PYTHON)
24:49
Dors Coding School
Рет қаралды 24 М.
PROBLEM SET 1: MATH INTERPRETER | SOLUTION (CS50 PYTHON)
12:33
Dors Coding School
Рет қаралды 28 М.
Handle Cookies in Python Requests
13:50
NeuralNine
Рет қаралды 12 М.
PROBLEM SET 6: CS50 P-SHIRT | SOLUTION (CS50 PYTHON)
19:12
Dors Coding School
Рет қаралды 22 М.
Правильный подход к детям
00:18
Beatrise
Рет қаралды 11 МЛН