Python university exam,

Course Queries Competitions/Entrance Exams 2 years ago

0 2 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating

Posted on 16 Aug 2022, this text provides information on Competitions/Entrance Exams related to Course Queries. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (2)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago

I have to create a function able to calculate the average of products built by various lines of production in a range of time.

EXAMPLE:

input = [('line1', 0, 5), ('line1', 0, 6), ('line2', 0, 3), ('line1', 0, 5), ('line3', 0, 4), ('line2', 0, 9), ('line3', 0, -1), ('line2', 0, 9), ('line2', 0, 10), ('line3', 0, 12), ('line1', 0, 1), ('line3', 0, 16)]

output = {'line1': 4.25, 'line2': 7.75, 'line3': 7.75}

I cannot calculate the average of each line because i don't know how to determine the period between two days.

EDIT: I'm sorry, i think i haven't explained the problem well. This is not an actual exam, it's a previous exam given by my professor to train.

profilepic.png
manpreet 2 years ago

 

You need to group your data by the line:

import itertools
input = [('line1', 0, 5), ('line1', 0, 6), ('line2', 0, 3), ('line1', 0, 5), ('line3', 0, 4), ('line2', 0, 9), ('line3', 0, -1), ('line2', 0, 9), ('line2', 0, 10), ('line3', 0, 12), ('line1', 0, 1), ('line3', 0, 16)]
new_result = {a:[c for *_, c in b] for a, b in itertools.groupby(sorted(input, key=lambda x:x[0]), key=lambda x:x[0])}
final_result = {a:round(sum(b)/float(len(b)), 2) for a, b in new_result.items()}

Output:

{'line1': 4.25, 'line3': 7.75, 'line2': 7.75}

Edit: simpler option with collections.defaultdict:

from collections import defaultdict
d = defaultdict(list)
for a, _, b in input:
  d[a].append(b)

final_result = {a:round(sum(b)/float(len(b)), 2) for a, b 
                                                    
                                                    
0 views   0 shares

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.