Today I have decided to check whether I can pass the first homework from SoftUni OOP with Python, through a live coding session. I have not read the problem before the video, thus I may say it took me exactly 18 minutes to solve it live (probably would have taken me around 10, if I was not talking during the video). Still, it is an interesting problem, if you are starting with OOP, so I have decided to put it here as well:
This is how the problem was given:
Create a class called Programmer. Upon initialization it should receive name (string), language (string), skills (integer). The class should have two methods:
- watch_course(course_name, language, skills_earned)
- If the programmer’s language is the equal to the one on the course increase his skills with the given one and return a message “{programmer} watched {course_name}”.
- Otherwise return “{name} does not know {language}”.
- change_language(new_language, skills_needed)
- If the programmer has the skills and the language is different from his, change his language to the new one and return “{name} switched from {previous_language} to {new_language}”.
- If the programmer has the skills, but the language is the same as his return “{name} already knows {language}”.
- In the last case the programmer does not have the skills, so return “{name} needs {needed_skills} more skills” and don’t change his language
This is my solution, from the video:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
class Programmer: def __init__(self, name, language, skills): self.name = name self.language = language self.skills = skills def watch_course(self, course_name, language, skills_earned): if self.language == language: self.skills += skills_earned return f'{self.name} watched {course_name}' else: return f'{self.name} does not know {language}' def change_language(self, new_language, skills_needed): if self.skills >= skills_needed: if new_language == self.language: return f'{self.name} already knows {new_language}' else: previous_language = self.language self.language = new_language return f'{self.name} switched from {previous_language} to {new_language}' else: needed_skill = skills_needed - self.skills return f'{self.name} needs {needed_skill} more skills' programmer = Programmer("John", "Java", 50) print(programmer.watch_course("Python Masterclass", "Python", 84)) print(programmer.change_language("Java", 30)) print(programmer.change_language("Python", 100)) print(programmer.watch_course("Java: zero to hero", "Java", 50)) print(programmer.change_language("Python", 100)) print(programmer.watch_course("Python Masterclass", "Python", 84)) |
I hope you enjoyed it! 🙂