apriori_templete
.py
keyboard_arrow_up
School
University of Michigan *
*We aren’t endorsed by this school
Course
505
Subject
Computer Science
Date
Dec 6, 2023
Type
py
Pages
5
Uploaded by DeanDragonflyPerson763
from __future__ import print_function
import sys
def apriori(dataset, min_support=0.5, verbose=False):
"""Implements the Apriori algorithm.
The Apriori algorithm will iteratively generate new candidate
k-itemsets using the frequent (k-1)-itemsets found in the previous
iteration.
Parameters
----------
dataset : list
The dataset (a list of transactions) from which to generate
candidate itemsets.
min_support : float
The minimum support threshold. Defaults to 0.5.
Returns
-------
F : list
The list of frequent itemsets.
support_data : dict
The support data for all candidate itemsets.
References
----------
.. [1] R. Agrawal, R. Srikant, "Fast Algorithms for Mining Association
Rules", 1994.
"""
C1 = create_candidates(dataset)
D = list(map(set, dataset))
F1, support_data = get_freq(D, C1, min_support, verbose=False) # get frequent
1-itemsets
F = [F1] # list of frequent itemsets; initialized to frequent 1-itemsets
k = 2 # the itemset cardinality
while (len(F[k - 2]) > 0):
Ck = apriori_gen(F[k-2], k) # generate candidate itemsets
Fk, supK
= get_freq(D, Ck, min_support) # get frequent itemsets
support_data.update(supK)# update the support counts to reflect pruning
F.append(Fk)
# add the frequent k-itemsets to the list of frequent
itemsets
k += 1
if verbose:
# Print a list of all the frequent itemsets.
for kset in F:
for item in kset:
print(""
+ "{"
+
"".join(str(i) + ", " for i in iter(item)).rstrip(', ')
+ "}"
+ ":
sup = " + str(round(support_data[item], 3)))
return F, support_data
def create_candidates(dataset, verbose=False):
"""Creates a list of candidate 1-itemsets from a list of transactions.
Parameters
----------
dataset : list
The dataset (a list of transactions) from which to generate candidate
itemsets.
Returns
-------
The list of candidate itemsets (c1) passed as a frozenset (a set that is
immutable and hashable).
"""
c1 = [] # list of all items in the database of transactions
for transaction in dataset:
for item in transaction:
if not [item] in c1:
c1.append([item])
c1.sort()
if verbose:
# Print a list of all the candidate items.
print(""
+ "{"
+ "".join(str(i[0]) + ", " for i in
iter(c1)).rstrip(', ')
+ "}")
# Map c1 to a frozenset because it will be the key of a dictionary.
return list(map(frozenset, c1))
def get_freq(dataset, candidates, min_support, verbose=False):
"""
This function separates the candidates itemsets into frequent itemset and
infrequent itemsets based on the min_support,
and returns all candidate itemsets that meet a minimum support threshold.
Parameters
----------
dataset : list
The dataset (a list of transactions) from which to generate candidate
itemsets.
candidates : frozenset
The list of candidate itemsets.
min_support : float
The minimum support threshold.
Returns
-------
freq_list : list
The list of frequent itemsets.
support_data : dict
The support data for all candidate itemsets.
"""
freq_list = []
support_data = dict()
for candidateSet in candidates:
supportCount = 0
for transaction in dataset:
if candidateSet.issubset(transaction):
supportCount += 1
support = supportCount / len(dataset)
if support >= min_support:
freq_list.append(candidateSet)
support_data[candidateSet] = support
return freq_list, support_data
def apriori_gen(freq_sets, k):
"""Generates candidate itemsets (via the F_k-1 x F_k-1 method).
This part generates new candidate k-itemsets based on the frequent
(k-1)-itemsets found in the previous iteration.
The apriori_gen function performs two operations:
(1) Generate length k candidate itemsets from length k-1 frequent itemsets
(2) Prune candidate itemsets containing subsets of length k-1 that are
infrequent
Parameters
----------
freq_sets : list
The list of frequent (k-1)-itemsets.
k : integer
The cardinality of the current itemsets being evaluated.
Returns
-------
candidate_list : list
The list of candidate itemsets.
"""
n = len(freq_sets)
if n<2: # Minimum 2 frequent itemsets needed to generate candidates
return []
# generate all possible candidate itemsets
candidate_set = set()
for i in range(0, n-1): # iterate through each element
for j in range(i+1, n): # and try to combine it with every element after it
commonElems = freq_sets[i].intersection(freq_sets[j])
if len(commonElems) >= k-2: # if k-2 of the items in the sets match
newCandidate = freq_sets[i].union(freq_sets[j]) # combine the sets
to make a length k itemset
candidate_set.add(newCandidate) # add that itemset to the list of
candidates
# find candidate itemsets which have k-1 length subsets that are infrequent
invalidCandidates = set()
for candidate in candidate_set:
for elem in candidate:
k1subset = candidate.difference({elem}) # generate every possible k-1
subset
subsetIsFrequent = False
for freqItemset in freq_sets: # check that every k-1 subset is frequent
if k1subset == freqItemset:
subsetIsFrequent = True
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
Related Questions
Using binary search approach, write a python function named update_record, which takes the following inputs:
1: students_records – Nested List of Tuples. Each tuple of the list represents student's data.
2: ID – An ID of a student whose data has to be updated
3: record_title – type of data that has to be updated
4: data – A new data that should replace record_title data and update the record of students' data associated to specific ID.
If ID is given as the data to be updated, then return a message that ID cannot be updated.
If ID is not found in students_records, then return a message that Record not found.
NOTE: The type of record_title input can be "ID", "Email", "Mid1" or "Mid2". Please use the same spelling for these types in your code, because the same have been used in test cases.
Test cases are attached below:
student_records = '[("aa02822", "ea02822", 80, 65),("ea02822", "ea02822@st.habib.edu.pk", 80, 65),("fa08877", "fa08877@st.habib.edu.pk", 66, 67),("gh04588",…
arrow_forward
Prompt: In python, modify the function below to plot a Gaussian distribution.
Code:
import matplotlib.pyplot as plt
import random
import numpy as np
from scipy.stats import norm
import seaborn as sns
def clipped_hist(df, clip_threshold):
newData = [x for x in df if x < clip_threshold]
return newData
np.random.seed(30)
data = [random.gauss(0, 1) for i in range(24)]
data_len1 = len(data)
clip_threshold = 1.0
data = clipped_hist(data, clip_threshold)
data_len2 = len(data)
title = "The values clipped = " + str(data_len1 - data_len2) + " The value clipping threshold = " + str(clip_threshold)
plt.hist(data)
plt.title(title)
plt.show()
arrow_forward
By python
arrow_forward
Recamán's sequence
def recaman(n):
Compute and return the first n terms of the Recamán's sequence, starting from the term a1 = 1.Note how the definition for the current next element depends on whether a particular number is already part of the previously generated part of the sequence. To let your function execute in a speedy fashion even when generating a sequence that contains millions of elements, you should use a set to keep track of which values are already part of the previously generated sequence. This way you can generate each element in constant time, instead of having to iterate through the entire previously generated list. The better technique that saves time by using more memory can create this list arbitrarily far in linear time, and should therefore be fast even for millions of elements, at least until it runs out of memory.
n
Expected result
10
[1, 3, 6, 2, 7, 13, 20, 12, 21, 11]
1000000
(a list of million elements whose last five elements are [2057162,1057165,…
arrow_forward
The setting: Daily Winners
An arcade owner asks you for a program to help them out. They want to increase
interest in daily high score winners at each of their arcade game machines, so at the
end of every day they want and to publish a list of players who have gotten the highest
score on that game.
They also want to give a prize to the player who has gotten the most high scores on
different machines for the day. Your program should give a prize to that player - if no
one has gotten more than one high score, choose a winner from the winner's list
randomly.
Write a function that takes in a list of scores from an arcade machine:
[[1, 5, 3, 8, 3], [20, 5], [16, 17, 18]]
And a list of players:
["Rahim", "Avano", "Louisa"]
The first set of scores in the list of scores belongs to the first player in the list of players,
the second list of scores to the second player in the list of players, and so on.
Your function should sum each players' list of scores, and add the player with the
highest…
arrow_forward
IntSet unionWith(const IntSet& otherIntSet) const// Pre: size() + (otherIntSet.subtract(*this)).size() <= MAX_SIZE// Post: An IntSet representing the union of the invoking IntSet// and otherIntSet is returned.// Note: Equivalently (see postcondition of add), the IntSet// returned is one that initially is an exact copy of the// invoking IntSet but subsequently has all elements of// otherIntSet added.// IntSet intersect(const IntSet& otherIntSet) const// Pre: (none)// Post: An IntSet representing the intersection of the invoking// IntSet and otherIntSet is returned.// Note: Equivalently (see postcondition of remove), the IntSet// returned is one that initially is an exact copy of the// invoking IntSet but subsequently has all of its elements// that are not also elements of otherIntSet removed.// IntSet subtract(const IntSet& otherIntSet) const// Pre: (none)//…
arrow_forward
Q_8.
Given an array of integers, write a PHP function to find the maximum element in the array.
PHP Function Signature:
phpCopy code
function findMaxElement($arr) { // Your code here }
Example: Input: [10, 4, 56, 32, 7] Output: 56
You can now implement the findMaxElement function to solve this problem. Let answer.
Answer asap. . !.
arrow_forward
Function Name: odd_even_diagParameters: a 2D list (list of lists)Returns: list of lists
Description: Given a 2-dimensional matrix (list of lists) with any size (n*n), modify it according to the following rules:
Find the sum of the main diagonal.
If the sum is an odd number, change all the values of the given matrix (except the main diagonal) to 0.
If the sum is an even number, change all the values of the given matrix (except the main diagonal) to 1.
Return the resulting matrix.
Example 1:If argument is:
[[1, 2], [4, 3]]
odd_even_diag should return:
[[1, 1], [1, 3]]
because the sum 1 + 3 is even.
Example 2:If argument is:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
odd_even_diag should return:
[[1, 0, 0], [0, 5, 0], [0, 0, 9]]
because the sum 1 + 5 + 9 is odd.
arrow_forward
Q/Complete the following code in Python (Biometrics for Voice Recognition)import osimport numpy as npfrom pyAudioAnalysis import audioBasicIO, audioFeatureExtraction, audioTrainTestfrom pydub import AudioSegment# Function to capture and save voice samplesdef capture_voice_samples(num_samples, speaker_name):os.makedirs("speakers", exist_ok=True)for i in range(num_samples):input("Press Enter and start speaking...")os.makedirs(f"speakers/{speaker_name}", exist_ok=True)audio = audioBasicIO.read_audio_file(f"speakers/{speaker_name}/sample_{i + 1}.wav")audio = AudioSegment.from_wav(f"speakers/{speaker_name}/sample_{i + 1}.wav")audio.export(f"speakers/{speaker_name}/sample_{i + 1}.wav", format="wav")print(f"Sample {i + 1} saved for {speaker_name}")# Function to extract features from voice samplesdef extract_features():speakers = [d for d in os.listdir("speakers") if os.path.isdir(os.path.join("speakers", d))]all_features = []all_labels = []for i, speaker in enumerate(speakers):features =…
arrow_forward
Up for the count
def counting_series (n):
The Champernowme word 1234567891011121314151617181920212223., also known as the
counting series, is an infinitely long string of digits made up of all positive integers written out in
ascending order without any separators. This function should return the digit at position n of the
Champernowne word. Position counting again starts from zero for us budding computer scientists.
Of course, the automated tester will throw at your function values of n huge enough that those who
construct the Champernowne word as an explicit string will run out of both time and space long
before receiving the answer. Instead, note how the fractal structure of this infinite sequence starts
with 9 single-digit numbers, followed by 90 two-digit numbers, followed by 900 three-digit
numbers, and so on. This observation gifts you a pair of seven league boots that allow their wearer
skip prefixes of this series in exponential leaps and bounds, instead of having to crawl…
arrow_forward
Use FDR to contruct and in Python. Aslo test the module by using Unit Testings.
arrow_forward
#Solve it with C programing
Suppose, you are working as a Data Entry Operator in a company. You have created a dataset that contains the names of N employees. Then your supervisor wants you to look for a particular employee by name. (Consider, every name in the data set is unique).Now your task is to write a program which will help you to find out the name which your supervisor is looking for.If found then print a message "Matched" otherwise print "Not Matched". (N.B: Without quotation)
The first line of input will take an integer (N) which indicates the number of names in the dataset. Then the second line will take N space-separated strings. The third line of input will take another string as search value.
Sample input:5rabbe sharif shazzad polash tutulsharif
Sample output:Matched
Sample input:4jahid nishat rasel shakibmunna
Sample output:Not Matched
arrow_forward
Up for the count def counting_series(n):
The Champernowne word 1234567891011121314151617181920212223... is an infinitely long string of digits made up of all positive integers written in ascending order without any separators between the individual numbers. This function should return the integer digit that lies in the position n of the Champernowne word, position count again starting from zero as usual.
Of course, the automated tester will give your function values of n large enough that anybody trying to solve this problem by explicitly constructing the series as a string would run out of time and space long before receiving the answer. Instead, you should observe that the structure of this infinite sequence is quite straightforward, as it starts with 9 single-digit numbers, followed by 90 two-digit numbers, followed by 900 three-digit numbers, and so on. Such a predictably self-similar structure allows you to skip over prefixes of this series in exponentially widening leaps and…
arrow_forward
Up for the count
def counting_series(n):
The Champernowne word 1234567891011121314151617181920212223... is an infinitely long string of digits made up of all positive integers written in ascending order without any separators between the individual numbers. This function should return the integer digit that lies in the position n of the Champernowne word, position count again starting from zero as usual.Of course, the automated tester will give your function values of n large enough that anybody trying to solve this problem by explicitly constructing the series as a string would run out of time and space long before receiving the answer. Instead, you should observe that the structure of this infinite sequence is quite straightforward, as it starts with 9 single-digit numbers, followed by 90 two-digit numbers, followed by 900 three-digit numbers, and so on. Such a predictably self-similar structure allows you to skip over prefixes of this series in exponentially widening leaps and…
arrow_forward
PYTHON DATASET given
x = np.array([i*np.pi/180 for i in range(60,300,4)]) np.random.seed(10) #Setting seed for reproducibility y = 4*x + 7 + np.random.normal(0,3,len(x))
Write a function inspired by sklearn’s polynomial preprocessing: (https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.PolynomialFeatures.html) your function should have: degree and include bias parameters only. For this assignment, assume that input is a 1-dimensional numpy array. For example, if an input sample is np.array([a, b]), the degree-2 polynomial features with "include_bias=True" are [1, a, b, a2, b2].
arrow_forward
Question R .Full explain this question and text typing work only We should answer our question within 2 hours takes more time then we will reduce Rating Dont ignore this line
arrow_forward
Please show the code for each part of this assignment using python in a jupyter notebook. The data file previoulsy used that is referenced in the first part is included
arrow_forward
I am trying to write swap functions in C language.
arrow_forward
In c++Write a program that first inputs rows and columns to apply the multiplication operation ontwo matrices. Matrices (MxN Dimensional Arrays) must be created using DynamicArrays.Note: Take care of any data validation if applicable
arrow_forward
link to MINST code: https://www.dropbox.com/s/i21pedejv0sknnq/MINST.pdf?dl=0
1) Add a confusion matrix to the MNIST code example from the link provided. Set the epochs parameter to 5. Explain which entry of the matrix yields the number of ones (the number 1) that are falsely recognized as eights (the number 8). (If you use indices in your explanation, use the Python index notation, i.e., start at zero.) Run your code a few times. Is the confusion matrix always the same? Briefly explain.
arrow_forward
from typing import List, Tuple, Dict
from poetry_constants import (POEM_LINE, POEM, PHONEMES, PRONUNCIATION_DICT, POETRY_FORM_DESCRIPTION)
# ===================== Provided Helper Functions =====================
def transform_string(s: str) -> str: """Return a new string based on s in which all letters have been converted to uppercase and punctuation characters have been stripped from both ends. Inner punctuation is left untouched.
>>> transform_string('Birthday!!!') 'BIRTHDAY' >>> transform_string('"Quoted?"') 'QUOTED' >>> transform_string('To be? Or not to be?') 'TO BE? OR NOT TO BE' """
punctuation = """!"'`@$%^&_-+={}|\\/,;:.-?)([]<>*#\n\t\r""" result = s.upper().strip(punctuation) return result
def is_vowel_phoneme(phoneme: str) -> bool: """Return True if and only if phoneme is a vowel phoneme. That is, whether phoneme ends in a 0, 1, or 2.
Precondition:…
arrow_forward
Assign letter grades
O solutions submitted (max: 1)
In the attached spreadsheet, you are given homework grades of 25 students.
Sheet 1 (hw1) stores the first homework grades, Sheet 2 (hw2) is the second homework grades and so on.
Use either xlsread() or readmatrix() to import the given data into Matlab. Once you have the data in Matlab;
1- Create separate arrays for each homework, name them as hw1, hw2, hw3, hw4, hw5
2- Create an average grade array named hwAvg. Store the average homework grade in hwAvg using the below weights
Homework 1, 2: each 15%
Homework 3, 4 : 20%
Homework 5: 30%
3- Create an array named letterGrade to store letter grades, this will be an array of strings.
• 4- Preallocate the letterGrade array. Make sure it has the same length as hwAvg array.
5- Assign letter grades from hwAvg array using the grading policy shown below
100 - 90 : A
<90 - 80 : B
<80 - 70:C
<70 - 60 : D
<60
:F
It is recommended that you download the file, see what it looks like, figure the steps…
arrow_forward
This is a task that needs to be done in matlab
arrow_forward
Sort function
false
true
is used in
MATLAB to
arrange
elements
from larger to
smaller
While loop
function is
used in case
of no number
of repetitions
is defined
To delete
data in
workspace,
we can use
clc command
Length
function is
used to know
the size of
matrix in
MATLAB
arrow_forward
String inquiredItem and integer numData are read from input. Then, numData alphabetically sorted strings are read from input and each string is appended to a vector. Complete the FindMiddle() function:
If inquiredItem is alphabetically before middleValue (the element at index middleIndex of the vector), output "Search lower half" and recursively call FindMiddle() to find inquiredItem in the lower half of the range.
Otherwise, output "Search upper half" and recursively call FindMiddle() to find inquiredItem in the upper half of the range.
End each output with a newline.
Click here for example Ex: If the input is:
ill 8 gif gum ill old pen pit pun ten
then the output is:
Search lower half Search upper half ill is found at index 2
Note: string1 < string2 returns true if string1 is alphabetically before string2, and returns false otherwise.You can only change the line "Your code goes here".
''
#include <iostream>#include <vector>#include <string>using namespace…
arrow_forward
python: answer in one line of code if possible, please
def traditions_dict(adict): """ Question 6 Given a dictionary that maps a person to a list of their favorite GT traditions, return a dictionary with the value being the list sorted by the last letter of each tradition. If two traditions have the same last letter, sort by the first letter.
HINT: This will require the use of lambda functions
Args: adict (dict) Returns: dict
>>> traditions_dict({"Jacob": ["The Horse", "Stealing the t", "Midnight Bud"], "Athena": ["Mini Five-Hundred", "Freshman Cake Race", "Buzzweiser Song"], "Liv": ["Freshman Cake Race", "George P. Burdell", "Buzzweiser Song"]})
{'Jacob': ['Midnight Bud', 'The Horse', 'Stealing the t'], 'Athena': ['Mini Five-Hundred', 'Freshman Cake Race', 'Buzzweiser Song'], 'Liv': ['Freshman Cake Race', 'Buzzweiser Song', 'George P. Burdell']}
>>>…
arrow_forward
can you wite the in pyth ,please?
arrow_forward
InterpolationAssignment DescriptionMeike, our climate scientist, was very happy with the program you wrote to calculate the maximum temperature drop. Now she has the following problem; in a series of measurements shediscovers one data point is missing, but not which one. She does know that the measurementsshow a constant increase.Write a function, interpolate(list), that completes a given series. Provide as output the indexbehind which the element should be inserted and the value. You can assume that the measurements are natural numbers and that the input consists of at least 3 measurements. You can assumethat both the first and the last data point have not been droppedP.S. Meike is in a hurry; your algorithm must run in O(log n) time.ExampleInput Output 1 Output 2[1, 2, 4] 1 3[3, 7, 11, 19] 2 15NotesMake sure to turn in your code with the filename “Interpolation.py”. If you turn it in withany other name it will fail the tests. This is due to instead of this assignment giving you an…
arrow_forward
Write a function verifsort that accepts a list as a parameter, check if the list elements are sorted and returns: 1 - if the list is sorted in ascending order, 2 – if the list is sorted in descending order, and 0 – if the list is not sorted.
Write a function listsort which accepts a list as a parameter, and sorts it in ascending order. You can use any standard sorting algorithm, but don’t use built-in sort methods and functions. The function must sort and return the list.
Write a script that asks user to enter 10 integer numbers, creates a list from those numbers, then calls verifsort function to detect if this list is sorted, prints message (list is sorted or list is not sorted) and if it’s not sorted then calls listsort function and prints the sorted list after listsort
arrow_forward
Solve using integer programming
arrow_forward
STRING-ARRAY
C program that scans a single char and prints out only the index/indexes of the character. If there are several matches, separate them by a single line.
INPUT- scans a single char
SAMPLE:Sample String: TheQuickBrownFoxJumpsOverTheLazyDogInput= TOutput= 0 26
arrow_forward
List pressure_data contains integers read from input, representing data samples from an experiment. Initialize variable sum_passed with 0. Then, for each element in pressure_data that is both at an odd-numbered index and greater than 65:
Output 'Index ', followed by the element's index, ': ', and the element's value.
Increase sum_passed by each such element's value.
# Read input and split input into tokenstokens = input().split()
pressure_data = []for token in tokens: pressure_data.append(int(token))
print(f'All data: {pressure_data}')
''' Your code goes here '''
print(f'Sum of selected elements is: {sum_passed}')
arrow_forward
MATLAB: Create function files that will:generate sequence y(n) = x1(n) + x2(n)[y,n] = sigadd(x1,n1,x2,n2)
arrow_forward
SEE MORE QUESTIONS
Recommended textbooks for you
COMPREHENSIVE MICROSOFT OFFICE 365 EXCE
Computer Science
ISBN:9780357392676
Author:FREUND, Steven
Publisher:CENGAGE L
Related Questions
- Using binary search approach, write a python function named update_record, which takes the following inputs: 1: students_records – Nested List of Tuples. Each tuple of the list represents student's data. 2: ID – An ID of a student whose data has to be updated 3: record_title – type of data that has to be updated 4: data – A new data that should replace record_title data and update the record of students' data associated to specific ID. If ID is given as the data to be updated, then return a message that ID cannot be updated. If ID is not found in students_records, then return a message that Record not found. NOTE: The type of record_title input can be "ID", "Email", "Mid1" or "Mid2". Please use the same spelling for these types in your code, because the same have been used in test cases. Test cases are attached below: student_records = '[("aa02822", "ea02822", 80, 65),("ea02822", "ea02822@st.habib.edu.pk", 80, 65),("fa08877", "fa08877@st.habib.edu.pk", 66, 67),("gh04588",…arrow_forwardPrompt: In python, modify the function below to plot a Gaussian distribution. Code: import matplotlib.pyplot as plt import random import numpy as np from scipy.stats import norm import seaborn as sns def clipped_hist(df, clip_threshold): newData = [x for x in df if x < clip_threshold] return newData np.random.seed(30) data = [random.gauss(0, 1) for i in range(24)] data_len1 = len(data) clip_threshold = 1.0 data = clipped_hist(data, clip_threshold) data_len2 = len(data) title = "The values clipped = " + str(data_len1 - data_len2) + " The value clipping threshold = " + str(clip_threshold) plt.hist(data) plt.title(title) plt.show()arrow_forwardBy pythonarrow_forward
- Recamán's sequence def recaman(n): Compute and return the first n terms of the Recamán's sequence, starting from the term a1 = 1.Note how the definition for the current next element depends on whether a particular number is already part of the previously generated part of the sequence. To let your function execute in a speedy fashion even when generating a sequence that contains millions of elements, you should use a set to keep track of which values are already part of the previously generated sequence. This way you can generate each element in constant time, instead of having to iterate through the entire previously generated list. The better technique that saves time by using more memory can create this list arbitrarily far in linear time, and should therefore be fast even for millions of elements, at least until it runs out of memory. n Expected result 10 [1, 3, 6, 2, 7, 13, 20, 12, 21, 11] 1000000 (a list of million elements whose last five elements are [2057162,1057165,…arrow_forwardThe setting: Daily Winners An arcade owner asks you for a program to help them out. They want to increase interest in daily high score winners at each of their arcade game machines, so at the end of every day they want and to publish a list of players who have gotten the highest score on that game. They also want to give a prize to the player who has gotten the most high scores on different machines for the day. Your program should give a prize to that player - if no one has gotten more than one high score, choose a winner from the winner's list randomly. Write a function that takes in a list of scores from an arcade machine: [[1, 5, 3, 8, 3], [20, 5], [16, 17, 18]] And a list of players: ["Rahim", "Avano", "Louisa"] The first set of scores in the list of scores belongs to the first player in the list of players, the second list of scores to the second player in the list of players, and so on. Your function should sum each players' list of scores, and add the player with the highest…arrow_forwardIntSet unionWith(const IntSet& otherIntSet) const// Pre: size() + (otherIntSet.subtract(*this)).size() <= MAX_SIZE// Post: An IntSet representing the union of the invoking IntSet// and otherIntSet is returned.// Note: Equivalently (see postcondition of add), the IntSet// returned is one that initially is an exact copy of the// invoking IntSet but subsequently has all elements of// otherIntSet added.// IntSet intersect(const IntSet& otherIntSet) const// Pre: (none)// Post: An IntSet representing the intersection of the invoking// IntSet and otherIntSet is returned.// Note: Equivalently (see postcondition of remove), the IntSet// returned is one that initially is an exact copy of the// invoking IntSet but subsequently has all of its elements// that are not also elements of otherIntSet removed.// IntSet subtract(const IntSet& otherIntSet) const// Pre: (none)//…arrow_forward
- Q_8. Given an array of integers, write a PHP function to find the maximum element in the array. PHP Function Signature: phpCopy code function findMaxElement($arr) { // Your code here } Example: Input: [10, 4, 56, 32, 7] Output: 56 You can now implement the findMaxElement function to solve this problem. Let answer. Answer asap. . !.arrow_forwardFunction Name: odd_even_diagParameters: a 2D list (list of lists)Returns: list of lists Description: Given a 2-dimensional matrix (list of lists) with any size (n*n), modify it according to the following rules: Find the sum of the main diagonal. If the sum is an odd number, change all the values of the given matrix (except the main diagonal) to 0. If the sum is an even number, change all the values of the given matrix (except the main diagonal) to 1. Return the resulting matrix. Example 1:If argument is: [[1, 2], [4, 3]] odd_even_diag should return: [[1, 1], [1, 3]] because the sum 1 + 3 is even. Example 2:If argument is: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] odd_even_diag should return: [[1, 0, 0], [0, 5, 0], [0, 0, 9]] because the sum 1 + 5 + 9 is odd.arrow_forwardQ/Complete the following code in Python (Biometrics for Voice Recognition)import osimport numpy as npfrom pyAudioAnalysis import audioBasicIO, audioFeatureExtraction, audioTrainTestfrom pydub import AudioSegment# Function to capture and save voice samplesdef capture_voice_samples(num_samples, speaker_name):os.makedirs("speakers", exist_ok=True)for i in range(num_samples):input("Press Enter and start speaking...")os.makedirs(f"speakers/{speaker_name}", exist_ok=True)audio = audioBasicIO.read_audio_file(f"speakers/{speaker_name}/sample_{i + 1}.wav")audio = AudioSegment.from_wav(f"speakers/{speaker_name}/sample_{i + 1}.wav")audio.export(f"speakers/{speaker_name}/sample_{i + 1}.wav", format="wav")print(f"Sample {i + 1} saved for {speaker_name}")# Function to extract features from voice samplesdef extract_features():speakers = [d for d in os.listdir("speakers") if os.path.isdir(os.path.join("speakers", d))]all_features = []all_labels = []for i, speaker in enumerate(speakers):features =…arrow_forward
- Up for the count def counting_series (n): The Champernowme word 1234567891011121314151617181920212223., also known as the counting series, is an infinitely long string of digits made up of all positive integers written out in ascending order without any separators. This function should return the digit at position n of the Champernowne word. Position counting again starts from zero for us budding computer scientists. Of course, the automated tester will throw at your function values of n huge enough that those who construct the Champernowne word as an explicit string will run out of both time and space long before receiving the answer. Instead, note how the fractal structure of this infinite sequence starts with 9 single-digit numbers, followed by 90 two-digit numbers, followed by 900 three-digit numbers, and so on. This observation gifts you a pair of seven league boots that allow their wearer skip prefixes of this series in exponential leaps and bounds, instead of having to crawl…arrow_forwardUse FDR to contruct and in Python. Aslo test the module by using Unit Testings.arrow_forward#Solve it with C programing Suppose, you are working as a Data Entry Operator in a company. You have created a dataset that contains the names of N employees. Then your supervisor wants you to look for a particular employee by name. (Consider, every name in the data set is unique).Now your task is to write a program which will help you to find out the name which your supervisor is looking for.If found then print a message "Matched" otherwise print "Not Matched". (N.B: Without quotation) The first line of input will take an integer (N) which indicates the number of names in the dataset. Then the second line will take N space-separated strings. The third line of input will take another string as search value. Sample input:5rabbe sharif shazzad polash tutulsharif Sample output:Matched Sample input:4jahid nishat rasel shakibmunna Sample output:Not Matchedarrow_forward
arrow_back_ios
SEE MORE QUESTIONS
arrow_forward_ios
Recommended textbooks for you
- COMPREHENSIVE MICROSOFT OFFICE 365 EXCEComputer ScienceISBN:9780357392676Author:FREUND, StevenPublisher:CENGAGE L
COMPREHENSIVE MICROSOFT OFFICE 365 EXCE
Computer Science
ISBN:9780357392676
Author:FREUND, Steven
Publisher:CENGAGE L