Coding D2 Assessment

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Answer: Override the get_context_data method in the DetailView

On your product detail page you would like to show other products that are similar to the one that the customer is currently viewing. You are using a DetailView to get all of the data for the main product. Where is the best place to get the extra data about other products to store in the context for the template?

Answer: The car has the color blue, but the database has color green

Assume that you just wrote a Car model class and now you are playing around with it in the python shell tobtest it out. Read the code below and then answer the question about the state of car at the end. >>> car = Car( ... manufacture="honda", .... model="CR-V", .... year=2013, .... color="green" ... ) >>> car.save() >>> car.color = "blue" What is the state of car?

Answer: A subclass of DetailView

Consider this code. class Author(models.Model): name = models.CharField(max_length=200) class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey( Author, related_name="books", on_delete=models.CASCADE ) You are creating a page that will show the details about a single book and will also show a list of all books by the same author. Which of the following class-based views will work best?

Answer: throw an error

Consider this code. class CarUpdateView(UpdateView): model = Car template_name = "car/edit.html" success_url = reverse_lazy("cars_list") # You commented this out for some reason # fields = ["make", "model", "year"] If the fields attribute is commented out or not included, as shown in the code above, Django will do what?

Answer: [[0, 1], [2, 3], [4, 5]]

Def partition(list, size): chunks = [ ] in_progress = [ ] for item in list: if len(in_progress) == size: chunk.append(in_progress) in_progress = [ ] in_progress.append(item) return chunks input = [0, 1, 2, 3, 4, 5, 6] result = partition(input, 2) print(result) What will print(result) line print to the terminal?

Answer: name = models.CharField()

Django is complaining that one of the fields below is missing a required parameter: class Thing(models.Module): name = models. Charfield() created_date = models.DateField() number = models.PositiveIntegerField() email = models.EmailField() Which field is it?

Answer: render(request, "things/puzzle.html", {"result": result, "puzzle":puzzle})

Given this code where the check_for_solution function checks to see if the person has solved the puzzle, and the prepare_puzzle function sets up the puzzle to be shown in the template: def puzzle(request): result = None if request.method == "POSt": results = check_for_solution(request) puzzle = prepare_puzzle() return____________________________ Which of the following lines will make both result and puzzle available in the template?

Answer: To assign the current user as the post author

Given this code: class BlogPostCreateView(CreateView): model = BlogPost template_name = "blog_post/new.html" fields = ["title", "content", "data"] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) What is the purpose of overriding the form_valid method?

Answer: weather_data

Given this code: class StoreDetailView(DetailView): model = Store template_name = "stores/detail.html" context_object_name = "the_store" def get_context_data(self, **kwargs) context = super().get_context_data(**kwargs) store_location = context["the_store"].get_location() weather_data = WeatherData.get(store_location) context["weather_data"] = weather _data return context Inside of the template, what "variable" would you use to access the weather information?

Answer: If the request is a POST and the form is valid, creates a new Widget

Given this code: def mystery(request): if request.method == "POST": from = WidgetForm(request.POST) if form.is_valid(): name = form.cleaned_data["name"] widget = Widget.objects.create(name=name) return redirect(widget) else: from = WidgetForm() context = { "form": form } return render(request, "template.html", context) What does it do?

Answer: def add_all(*numbers): # your code here sum = 0 for number in numbers: sum += number return sum

Implement the function add_all( ) which returns the sum of all of its arguments. Sample Inputs/outputs *Numbers. Output (none). 0 3. 3 1, 2, 3 6

Answer: def divide_bill(bill, num_diners, tip=0.2): # your code here total = bill * (1 + tip) #-hide return total / num_diners #-hide

Implement the function divide_bill which will return the amount due for each diner given: a total bill, number of diners, and the desired tip amount. bill num_diners tip output 10 4 0.0 2.5 10 4 0.1 2.75 30 5 0.2 7.2

Answer: comment_set

Notice in the code below, that the related_name parameters was not provided in ForeignKeyField class Comment(models.Model): content = models.TextField() blogpost = models.ForeignKeyField(BlogPost, on_delete=models.CASCADE) What will be the "related" name on the BlogPost model for the collection of Comment instances for that BlogPost model?

Answer: def pair_up(items): # your code here pair = [ ] pair0 = items[::2] pair1 = items[1::2] for idx in range(len(pair1)): pairs.append([pair0[idx], pair1[idx]]) return pairs def pair_up(items): pairs = [ ] # Loop through the indexes of the items for index, item in enumerate(items): # If the index + 1 is less than the length # If the index is even if index % 2 == 0: if index + 1 < len(items): # Make a pair pair = [items[index], items[index + 1]] # Append the pair to the pairs list pairs.append(pair) return pairs def pair_up(items): pairs = [ ] # Looping through 2 at a time using range for index in range(0, len(items), 2): # If index + 1 is inside the list if index + 1 < len(items): # add the current index and the index + 1 item to the pair pair = [items[index], items[index + 1]] # Append the pair to the pairs list pairs.append(pair) return pairs

Please complete the pair_up function below so that it takes a list of items and returns a list of pairs of consecutive items. Here's an example: input = [1,2,3,4,5,6,7] pair_up(input) # Returns [[1,2], [3,4], [5,6]] Note: since there were an odd number of items, the 7 didn't have a partner to pair with, so it was excluded Think through this problem. • What gets returned for an empty list? • Can you do this with a single if statement? • Can you do this with a for loop?

Answer: def mean(numbers): if len(numbers) == 0: return float('nan') _sum = sum(numbers) return _sum/len(numbers)

The following function is falling the unit tests with a divide by zero error when called like this: number = [] mean(numbers) # —> ZeroDivisionError: division by zero If this situation is detected, It should return float('nan') Update the code below to handle this situation and pass the falling unit test.

Answer: def unique_elements(items): # your code here uniques = {} for item in items: uniques[item] = 1 return list(uniques.keys()) def unique_elements(items): new_items = [] for item in items: if item not in new_items: new_items.append(item) return new_items

The function below takes a list of items and returns a copy of the list with all of the duplicate items removed in the same order that they were encountered in the list. Examples: Input. Output []. [] [1,2]. [1,2] [1,1,2]. [1,2] [1,2,1]. [1,2] [2,1,1]. [2,1] [1,1,1]. [1]

Answer: def join_strings(strings, separator=" "): # your code here if len(strings) == 0: return " " output = strings[0] for string in strings[1:]: output += separator + string return output

The join_strings returns a single string that is the concatenation of all the input strings, separated by the separator if supplied. Example: join_strings(["aaa", "bbb", "ccc"], "--") # Returns "aaa- -bbb- -ccc" Think through this problem. • What gets returned for an empty list? • Can you do this with a single if statement? • Can you do this with a for loop?

Answer: def last_item(list): if len(list) == 0: return None last_item = list[-1] return last_item

There are a couple of problems with the last_item function. • It is supposed to return the last item of the list passed in through the list parameter • If the list parameter contains an empty list, then it should return None Update the code below so that it passes its unit tests

Answer: def c_to_f(degrees_celsius): #your code here return degrees_celsius * 9 / 5 + 32 #-hide

This function converts temperature measured in degrees Celsius to degrees Fahrenheit. Here are two examples: C F 0. 32 100. 212 The formula is: F = (C * 9/5) + 32

Answer: def read_delimited(line, separator=","): # your code here values = line.split(separator) return values

This function must take a string that is composed of values that are separated by some "delimiter" character, like a comma. It will return an array of the values in the string with the delimiter removed. Here is an example: input = "1, 2, 3, 4" read_delimited(input). # —> ["1", "2", "3", "4"] If input is an empty string, the result should be a list with a single empty string in it: [" "] Please refer to the split method for strings to see how to do this. Please complete the read_delimited function here.

Answer: def is_multiple_of(number, base): # your code here If int(number) != number or int(base) != base: return False return number % base == 0

This function returns True if number is an integer multiple of base where number and base are both integers. If base is an integer multiple of number, then number/base is an integer. Here are some examples: Number. Base. Output. Reason 6. 1.5. False. 1.5 is not an () integer 6. 2. True. 6 is a multiple (). of 2 6. 3. True. 6 is a multiple (). of 3 6. 4. False. 6 is not a multiple of 4 You can test if the number in a variable is an Integer by using the int function to turn the value into an integer, then seeing if it equals the original value, like this. if int(x) == x: # Then, x is an integer You can use the modulo operator % to check to see what the remainder of division is. If the remainder is 0, then the second number evenly divides the first number. x = 10 y = 2 print(x % y) # Prints 0 x = 10 y = 3 print(x % y) # Prints 1 x = 10 y = 4 print(x % y) # Prints 2 x = 10 y = 5 print(x % y) # Prints 0

Answer: def find_shipment_weight(shipment): # your code here total_weight = 0 for item in shipment: total_weight += item["product_weight_pounds"] * item["quantity"] return total_weight

This function takes a list of items in a shipment and calculates the total weight of the shipment. Below is an example shipment list in Python: shipment = [ { "products_name": "can of soup", "products_weight_pounds": 3.4, "quantity": 3, }, ] The total weight for the example above would be 3 x 3.4 = 10.2 Here's an example with two items: shipment = [ { "product_name": "beans", "product_weight_pounds": 2, "quantity": 5, }, { "product_name": "rice", "product_weight_pounds": 1.5, "quantity": 7, }, ] The total weight for this shipment is: (2 x 5) + (1.5 x 7) = 20.5 If the shipment is empty, then the function should return 0. Think though this problem. It may seem complex but you can do this. • What gets returned for an empty list? • Can you do this with a single if statement? • Cann you do this with a for loop?

Answer: def find_longest(strings): # your code here longest = None max_length = 0 for string in strings: length = len(string) if length > max_length: max_length = length longest = string return longest

This function takes a list of strings and returns the longest string in the list. Note: The input data will have only one longest string. Here are some examples: Strings Output [ ]. None ["a"]. "a" ["a", "bbb", "cc"]. "bbb" Think through this problem. It may seem complex, but you can do this. • What gets returned for an empty list? • Can you do this with a single if statement? • Can you do this with a for loop?

Answer: def join(items): result = " " for item in items: result += str(item) return result

This function works when items only has strings in it, but falls if there are any non-string things. The function should make sure that each item in items is converted to a string before concatenating it to the result. Fix the code below to handle non-string items.

Answer: def shift_cipher(message, shift): # your code here encrypted_message = " " for index in range(len(message)): char = message[index] ascii = ord(char) encrypted_message += chr(ascii + shift) return encrypted_message

This pseudo-encryption method works by shifting each letter in a message a fixed amount, so for example: shift_cipher("b", 1) #--> "c" shift_cipher("b", 2) #—> "d" shift_cipher("b", -1) # —> "a" shift_cipher("bbc", 1) —> "ccd" shift_cipher("bbc, -1) —> "aab" shift_cipher("bbc, 3) —> "eef" Can you implement this 2000 year old cipher? You can use the ord built-in method to turn a character into its corresponding number. You can use the chr built-in method to turn a number into its corresponding character. Think through this problem. It may seem complex, but you can do this. • What gets returned for an empty string? • Can you do this with a single if statement? • Can you do this with a for loop? ord("a") # Returns 97, the integer value "a" chr(97) # Return "a" chr(98). # Return "b"

Answer: Override the form_valid method in the view

You are using a CreateView to add a page to your site that allows a user to create a new game. It almost works. The game is getting created, but it is not associated to the user that created it. Where is the best place to set the current user as the person that created that Game instance?

Answer: pets/urls.py

You just created a new view for your Django app named pets for your Django project named vet_office. Now you have to tell Django what URL path to use for the view. Where does this code go?

Answer: auto_now=True

You would like to add a last_update field to a model you are working on. You would like for the field to get updated every time there is any change to the record. Adding which parameter to your DateTimeField will accomplish this goal?

Answer: add LoginRequiredMixin as the first entry in the view's inheritance list

Your website has a page that you would like to make availability only to logged-in users. The view for the page is implemented using a class view. Which of these Django tools is the best tool for the job?

Answer: Deletion of the related blogpost

class Comment(models.Model): content = models.TextField() blogpost = models.ForeignKeyField(Blogpost, on_delete=models.CASCADE) author = models.ForeignKeyField(User, on_delete=models.PROJECT) Which of the following actions would cause a comment to be deleted?

Answer: 1

def count_matches(items, param2=None): matches = [ ] for item in items: if(item.get("color") == param2): matches.append(item) return len(matches) input = [ {"background": "green", "size": 5, "color": "blue"}, {"background": "yellow", "size": 5, "color": "green"}, {"background": "blue", "size": 25, "color": "green"}, {"background": "yellow", "size": 5, "weight": "light"}, ] result = count_matches(input) print(result) What will the print(result) line print to the terminal?

Answer: 100

from datetime import datetime class Invoice: def __init__(self, customer_name, amount, invoice_date): self.customer_name = customer_name self.amount_due = amount self.invoice_date = invoice_date def amount_due(invoices, days=30): past_due = 0 for invoice in invoices: if (datetime.now( ) - invoice.invoice_date).days > days: return past_due invoices = [ Invoice("Raul", 25.00, datetime(2010, 4, 15)), Invoice("Poli", 50.00, datetime(2029, 11, 5)), Invoice("Don", 75.00, datetime(2012, 7, 17)), Invoice("Anne", 100.00, datetime(2035, 6, 17)) ] result = amount_due(invoices, 90) print(result) What will the print(result) line print to the terminal?


Kaugnay na mga set ng pag-aaral

Chapter 1 - Cultural Anthropology

View Set

Chapter 17: Plate Tectonics Test

View Set

ATI Pharmacology Made Easy 4.0 "Pain and Inflammation", Pharm Pain and Inflammation

View Set

French Revolution, World Revolution

View Set

Chapter 13: The Nursing Role in Promoting Nutritional Health During Pregnancy

View Set