AlgoExpert - ProgrammingExpert

AlgoExpert - ProgrammingExpert

Register & Get access to index
Status
Not open for further replies.

Satoru Gojo

Well-known member
Moderator
Uploader
Jun 6, 2022
2,199
396,776
82
Satoru Gojo submitted a new resource:

AlgoExpert - ProgrammingExpert - An unrivaled platform to learn to code. The fastest way to become a Software Engineer.

pe-social-logo.png

What is ProgrammingExpert?​

Streamlined Platform​

Learning to code is undeniably daunting. ProgrammingExpert gives you the simplest, most streamlined platform, with everything you need to learn programming easily and stress-free.
Learn more.

Comprehensive Curriculum​

There's learning to code, and then there's actually learning to code. The latter requires an...

Read more about this resource...
 

Satoru Gojo

Well-known member
Moderator
Uploader
Jun 6, 2022
2,199
396,776
82

Programming Fundamentals --- Codes & Practices​


1 Random Number Guesser​


Write a program that asks the user to enter two integers representing the start and the end of a range. The program should then generate a random number within this range (inclusively) and ask the user to guess numbers until they guess the randomly generated number. Once the user guesses the random number, the program should tell them how many attempts it took them to guess it.


Your program needs to ensure that the range of numbers given is valid. For example, if the user enters a number for the end of the range that is less than the start of the range your program needs ask them to enter a valid number. Your program must also handle any other errors that might occur, like the user entering a string instead of an integer.


Note: You may assume the start of the range will never be negative (i.e. you don’t need to handle negative values).


Your program must use the same prompts and output as shown in the sample output below.


Sample Output 1​

Code:
You don't have permission to view the code content. Log in or register now.

Sample Output 2​

Code:
You don't have permission to view the code content. Log in or register now.

Sample Output 3​

Code:
You don't have permission to view the code content. Log in or register now.
SOLUTION

Code:
You don't have permission to view the code content. Log in or register now.

2 Caesar Cipher​


Write a function that accepts a string and returns the caesar cipher encoding of that string according to a secondary input parameter named offset.


The caesar cipher encoding of a string involves shifting each character in the string a set number of positions previous in the alphabet. For example, if you were performing a caesar cipher of the string “tim” with offset = 2 you would get “rgk”. “t” is shifted two positions to “r”, “i” is shifted two positions to “g” and “m” is shifted two positions to “k”.


In the situation where the shift of a character results in it being a position before “a” the positions wrap and the next character should be “z”. For example, the caesar cipher of “ab” with offset = 2 would be “yz”.


offset will always be a positive integer that is no greater than 26 and the input string will only contain lowercase letters.


Sample Input #1​


string = "hello" offset = 3


Sample Output #1​


"ebiil"


Sample Input #2​


string = "apple" offset = 5


Sample Output #2​


"vkkgz"


Solution

Code:
You don't have permission to view the code content. Log in or register now.

3 Sort Employees


Write a function that accepts a list of lists that contain the name, age and salary of specific employees and also accepts a string representing the key to sort employees by. Your function should return a new list that contains the lists representing each employee sorted in ascending order by the given key.


The string parameter named sort_by will always be equal to one of the following values: “name”, “age” or “salary”.


See the sample input and output below for a detailed example.


Sample Input #1

Code:
You don't have permission to view the code content. Log in or register now.

Sample Output #1

Code:
You don't have permission to view the code content. Log in or register now.

Sample Input #2

Code:
You don't have permission to view the code content. Log in or register now.

Sample Output #2

Code:
You don't have permission to view the code content. Log in or register now.

Sample Input #3

Code:
You don't have permission to view the code content. Log in or register now.
Sample Output #3

Code:
You don't have permission to view the code content. Log in or register now.

Solution 1

Code:
You don't have permission to view the code content. Log in or register now.
Solution 2

Code:
You don't have permission to view the code content. Log in or register now.

4 Longest Unique Words​


Write a function that accepts a list of strings that represent words and a positive integer n, representing the number of words to return. Your function should return a new list containing the n longest unique words from the input list. Words are unique if they only appear one time in the input list.


There will always be exactly n words to return and you may return the words in any order.


Note: all strings in the input list will not contain any special characters or spaces.


See the sample input and output below for a detailed example.


Sample Input #1​


words = [ 'Longer', 'Whatever', 'Longer', 'Ball', 'Rock', 'Rocky', 'Rocky' ] n = 3


Sample Output #1​

Code:
You don't have permission to view the code content. Log in or register now.
Solution 1

Code:
You don't have permission to view the code content. Log in or register now.

Solution 2

Code:
You don't have permission to view the code content. Log in or register now.

5 Pairs Sum To Target​


Write a function that accepts two lists (list1 and list2) of integers and a target integer named target. Your function should return all pairs of indices in the form [x, y] where list1[x] + list2[y] == target. In other words, return the pairs of indices where the sum of their values equals target.


list1 and list2 will always have the same number of elements and you may return the pairs in any order.


Sample Input #1​

Code:
You don't have permission to view the code content. Log in or register now.

Sample Output #1​

Code:
You don't have permission to view the code content. Log in or register now.
Solution

Code:
You don't have permission to view the code content. Log in or register now.

6 Create Strings From Characters

Write a function that accepts a dictionary called frequencies and two strings named string1 and string2. The frequencies dictionary contains character keys and integer values, the value associated with each character represents its frequency. Your function should return 0, 1 or 2 according to the cases below.


Your function should return 2 if the frequency of characters in the dictionary is sufficient to create both string1 and string2 without reusing any characters.
Your function should return 1 if the frequency of characters in the dictionary is sufficient to create either string1 or string2 without reusing any characters.
Your function should return 0 if the frequency of characters in the dictionary is not sufficient to create either string1 or string2 without reusing any characters.
Sample Input #1

Code:
You don't have permission to view the code content. Log in or register now.

Sample Output #1

Code:
You don't have permission to view the code content. Log in or register now.

Sample Input #2

Code:
You don't have permission to view the code content. Log in or register now.
Sample Output #2

Code:
You don't have permission to view the code content. Log in or register now.
 

Satoru Gojo

Well-known member
Moderator
Uploader
Jun 6, 2022
2,199
396,776
82

Object-Oriented Programming --- Codes & Practices​


Inventory Class​

Write an Inventory class, as defined below, that handles the management of inventory for a company. All instances of this class should be initialized by passing an integer value named max_capacity that indicates the maximum number of items that can be stored in inventory. Your Inventory class will need to store items that are represented by a name, price and quantity.
Your class should implement the following methods.
  • add_item(name, price, quantity): This method should add an item to inventory and return True if it was successfully added. If adding an item results in the inventory being over capacity your method should return False and omit adding this item to the inventory. Additionally, if an item with the passed name already exists in inventory this method should return False to indicate the item could not be added.
  • delete_item(name): This method should delete an item from inventory and return True if the item was successfully deleted. If there is no item with the passed name this method should return False.
  • get_most_stocked_item(): This method should return the name of the item that has the highest quantity in the inventory, and return None if there are no items in the inventory. You may assume there will always be exactly one item with the largest quantity, except for the case where the inventory is empty.
  • get_items_in_price_range(min_price, max_price): This method should return a list of the names of items that have a price within the specified range (inclusively).
Note: you may assume all input/arguments to your class will be valid and the correct types. For example, the max_capacity will always be greater than or equal to 0 and a valid integer.
See below for an example of how the Inventory class should behave.
Code:
You don't have permission to view the code content. Log in or register now.

Solution
Code:
You don't have permission to view the code content. Log in or register now.

Student Class​

Write a Student class, as defined below, that keeps track of all created students.
Your class should implement the following methods, class variables and properties:
  • An instance attribute called name.
  • A property called grade that returns the grade of that student. Trying to set the grade should raise a ValueError if the new grade is not a number between 0 and 100.
  • A static method called calculate_average_grade(students) that accepts a list of Student objects and returns the average grade for those students. If there are no students in the list, it should return -1.
  • A class variable called all_students that stores all of the student objects that have been created in a list.
  • A class method named get_average_grade() which returns the average grade of all created students.
  • A class method named get_best_student() which returns the student object with the best grade out of all the currently created students. If there are no students created this method should return None. You may assume there will always be one student with the best grade, except in the case where there are no students created.
See below for an example of the behavior of the Student class.
Code:
You don't have permission to view the code content. Log in or register now.

Solution
Code:
You don't have permission to view the code content. Log in or register now.

Geometry Inheritance​

Create 4 classes: Polygon, Triangle, Rectangle and Square. The Triangle and Rectangle class should be subclasses of Polygon, and Square should be a subclass of Rectangle.
Your Polygon class should raise a NotImplementedError when the get_area() and get_sides() methods are called. However, it should correctly return the perimeter of the polygon when get_perimeter() is called. Treat the Polygon class as an abstract class.
Your Triangle class should have a constructor that takes in 3 arguments, which will be the lengths of the 3 sides of the triangle. You may assume the sides passed to the constructor will always form a valid triangle.
Your Rectangle class should have a constructor that takes in 2 arguments, which will be the width and height of the Rectangle.
Your Square class should have a constructor that takes in 1 argument, which will be the length of each side of the Square.
Your Triangle and Rectangle classes should both implement the following methods:
  • get_sides(): This method returns a list containing the lengths of the sides of the shape.
  • get_area(): This method returns the area of the polygon.
Your Square class should only have an implementation for its constructor, and rely on the Rectangle superclass for implementations of get_sides() and get_area().
Note: To calculate the area of a triangle given three side lengths (x, y and z) you can use the following formula. First calculate the semi perimeter s using: s = (x + y + z) / 2. Then calculate the area A using: A = math.sqrt(s * (s - x) * (s - y) * (s - z)).
See below for an example of how these classes should behave.
Code:
You don't have permission to view the code content. Log in or register now.

Solution
Code:
You don't have permission to view the code content. Log in or register now.

Deck Class​

Create a Deck class that represents a deck of 52 playing cards. The Deck should maintain which cards are currently in the deck and never contain duplicated cards. Cards should be represented by a string containing their value (2 - 10, J, Q, K, A) followed by their suit (D, H, C, S). For example, the jack of clubs would be represented by “JC” and the three of hearts would be represented by “3H”.
Your Deck class should implement the following methods:
  • shuffle(): This method shuffles the cards randomly, in place. You may use the random.shuffle() method to help you do this.
  • deal(n): This method removes and returns the last n cards from the deck in a list. If the deck does not contain enough cards it returns all the cards in the deck.
  • sort_by_suit(): This method sorts the cards by suit, placing all the hearts first, diamonds second, clubs third and spades last. The order within each suit (i.e. the card values) does not matter. This method should sort the cards in place, it does not return anything.
  • contains(card): This method returns True if the given card exists in the deck and False otherwise.
  • copy(): This method returns a new Deck object that is a copy of the current deck. Any modifications made to the new Deck object should not affect the Deck object that was copied.
  • get_cards(): This method returns all the cards in the deck in a list. Any modifications to the returned list should not change the Deck object.
  • len(): This method returns the number of the cards in the Deck.
Your deck should always start with exactly 52 cards that are distributed across 4 suits and 13 values where there are no duplicate cards.
See below for an example of how the Deck class should behave.
Code:
You don't have permission to view the code content. Log in or register now.

Solution
Code:
You don't have permission to view the code content. Log in or register now.

FileSystem Implementation​

In this question, you need to implement a very simplistic FileSystem class that mimics the way that your own computer’s FileSystem works. A FileSystem starts empty with only a root node which will always be a directory.
A FileSystem is a tree-like structure composed of nodes, each of which is either a File or Directory.
Files are simplest and only have name and contents as attributes; which correspond to the name of the file and its contents, respectively. Files also have a write method, which sets the contents of that file to the argument passed in. Additionally, files override the len dunder method which returns the number of characters in the contents of that file.
Directories have a name and a children attribute. children is a dictionary that stores the name of its children nodes as keys, and the nodes themselves as the values of that dictionary. Directories also have the add and delete methods which are used to add or delete nodes from its children dictionary.
For your convenience, the str methods of each class have been overridden so that you may debug your FileSystem more easily.
Your task is to implement the following methods on the FileSystem class:
  • create_directory(path): This method should create a Directory inside the FileSystem at the location specified. For instance, create_directory(“/dir1”) should create a directory as a child of the root of the filesystem called “dir1”. Running create_directory(“/dir1/dir2”) should create another directory, dir2, inside the one that was just created. If the path is malformed or the operation is impossible, it should raise a ValueError.
  • create_file(path, contents): This method should create a new file at the desired path, with the contents passed in. If the operation is impossible, it should raise a ValueError.
  • read_file(path): This method should return the contents of the file at the path parameter. If no such file exists, it should raise a ValueError.
  • delete_directory_or_file(path): This method should delete the node located at path. It should work on files and directories alike, and should raise a ValueError if that file does not exist.
  • size(): This method should return the number of characters across all files in your filesystem.
  • _find_bottom_node(node_names): This is a private helper method of the FileSystem class that takes in a list of node names and should traverse the filesystem downwards until the last node in the list. For instance, calling this with [“a”, “b”, “c”] should first look for a node a inside the root node of the filesystem, then for a node b inside node a, and then return the node c which should be a child of node b.
Note: for all methods that accept a path parameter you will need to first validate that path and then parse it. The path will be a string, and from that string you’ll need to do one of the following:
  • Obtain the directory object used to create a new directory or file inside of.
  • Obtain the directory object used to delete a directory or file.
  • Obtain the file object to read the contents of.
This is non-trivial because you may need to distinguish between the name of the new node create and the path where this node should be created.
See below for an example of how these classes should behave.
Code:
You don't have permission to view the code content. Log in or register now.

Solution
Code:
You don't have permission to view the code content. Log in or register now.
 

Satoru Gojo

Well-known member
Moderator
Uploader
Jun 6, 2022
2,199
396,776
82

Advanced Programming -- Codes & Practices​


Positive Even Squares​


Write a function that accepts any number of positional arguments, all of which you may assume will be lists of integers. Your function should filter all of these lists such that they only contain even positive integers and combine all of the lists into one list of integers. Your function should then modify the combined list such that it contains the squares of all of the elements and return that list.


Use a combination of the map, filter and lambda functions/keywords to modify the lists.


See the sample input for an example.


Sample Input #1​

Code:
You don't have permission to view the code content. Log in or register now.

Sample Output #1​

Code:
You don't have permission to view the code content. Log in or register now.
Solution

Code:
You don't have permission to view the code content. Log in or register now.

Integer Sum​


Write a function named integer_sum that accepts any number of positional arguments, which are assumed to be integers. This function should return the sum of all of these integers.


To handle invalid input (arguments that are not integers) you must write the following decorators and use them to decorate the integer_sum function.


  • flatten_lists: this decorator should flatten any list arguments for the decorated function by extracting their elements and passing them as individual arguments instead of the list. For example, if [1, 2, True] is an argument, then 1, 2 and True should be extracted and passed as arguments instead of the list to the decorated function.
  • convert_strings_to_ints: this decorator should convert any string arguments that are valid integers to integers and pass them to the decorated function. Any string that is not a valid integer should be removed as an argument to the decorated function.
  • filter_integers: this decorator should remove any argument that is not an integer and call the decorated function with only integer arguments.

You may assume all arguments passed to integer_sum will be of type float, int, str or list.


Sample Input #1​

Code:
You don't have permission to view the code content. Log in or register now.

Sample Output #1​

Code:
You don't have permission to view the code content. Log in or register now.
Solution

Code:
You don't have permission to view the code content. Log in or register now.

Generate String​


Write a generator that accepts a string and an integer called frequency and generates a sequence as follows: string[0] * frequency + string[1] * frequency + … + string[-2] * frequency + string[-1] * frequency. Your generator should not store this string, it should generate the next element in the sequence each time its next method is called.


You should create this generator in both a functional and class based way. Your functional generator should be named generate_string and your class based generator (a.k.a iterator) should be named GenerateString.


You may assume that frequency >= 0.


Sample Input #1​

Code:
You don't have permission to view the code content. Log in or register now.

Sample Output #1​

Code:
You don't have permission to view the code content. Log in or register now.
Solution

Code:
You don't have permission to view the code content. Log in or register now.

Thread Safe Counter​


Write a WordCounter class that is meant to be able to count words in large texts, so that a user of that class can quickly calculate how many times a specific word occurs in a string.


WordCounter should implement the following methods:


  • process_text(text) should take in a string, text, and update the internal attributes of WordCounter in a thread-safe manner. You may assume naively that text.split(" ") is good enough to return the list of words in the passed text.
  • get_word_count(word) should take in a string, word, and check how many times that word has been seen in all the texts that this WordCounter has processed. If this word has never been seen, you should return 0.

NOTE: This class must be thread-safe; meaning that many threads should be able to use the WordCounter at the same time, and the calculations must remain accurate as if only a single thread was using the instance of WordCounter.


NOTE: You may not use the Counter class of the collections standard library.

Code:
You don't have permission to view the code content. Log in or register now.
Solution

Code:
You don't have permission to view the code content. Log in or register now.

Asynchronous Fetcher​


Write a BatchFetcher class that is meant to fetch lots of records from a database very quickly.


Your constructor takes in a database object that has an async method called async_fetch. This method takes a record identifier (or record_id) and returns whatever the database has in storage for that record.


BatchFetcher should implement the async method fetch_records, which takes in a list, record_ids, and should return the list of records corresponding to those record_ids.

Code:
You don't have permission to view the code content. Log in or register now.

Solution

Code:
You don't have permission to view the code content. Log in or register now.


Code:
You don't have permission to view the code content. Log in or register now.
 
Status
Not open for further replies.

Latest resources