def modeConflict(track, list, type): popup = tk.Toplevel() popup.title(type.capitalize() + 'Conflict') popup.configure(bg=bg) ws = popup.winfo_screenwidth() # width of the screen hs = popup.winfo_screenheight() # height of the screen initialWidth = 550 y = (hs / 2) - (297 / 2) for i in range(len(multimode(list))): initialWidth += (len(multimode(list)[i])) * 7 x = (ws / 2) - (initialWidth / 2) popup.geometry('%dx%d+%d+%d' % (initialWidth, 270, x, y)) tk.Label(popup, text=type.capitalize() + " Conflict", font=("Proxima Nova Rg", 13), fg="white", bg=bg).pack(side="top", pady=(30, 15)) tk.Label(popup, text="The search returned more than one " + type, font=("Proxima Nova Rg", 11), fg="white", bg=bg).pack(side="top", pady=(10, 10)) tk.Label(popup, text=track.artist + ' - ' + track.title, font=("Proxima Nova Rg", 11), fg="white", bg=bg).pack(side="top", pady=(0, 30)) radioFrame = tk.Frame(popup) radioFrame.config(bg=bg) radioFrame.pack() selection = tk.StringVar() selection.set(None) for i in range(len(multimode(list))): option = tk.Radiobutton(radioFrame, variable=selection, value=multimode(list)[i], command=lambda i=i: selectOption(track, multimode(list), i, selection, selectButton, type), activebackground=bg, selectcolor=bg, bg=bg, fg="white") option.deselect() option.pack(padx=(20, 0), side="left") tk.Label(radioFrame, text=multimode(list)[i], font=("Proxima Nova Rg", 11), fg="white", bg=bg).pack(side="left") selectButton = tk.Button(popup, text="Select", font=("Proxima Nova Rg", 11), state=tk.DISABLED, fg="white", bg=bg, command=popup.destroy) selectButton.pack(pady=(30, 0)) original = '' if type == "genre": original = track.genre elif type == "key": original = track.key popup.attributes("-topmost", True) popup.protocol("WM_DELETE_WINDOW", lambda track=track, popup=popup, value=original: onExit(track, value, popup, type)) popup.wait_window()
def handleTrackReport(track, audio, filename, webScrapingWindow, characters, options, initialCounter, imageCounter, images, informalTagDict): conflict = False # check year for false values if "Release_Date" in options["Selected Tags (L)"] and len(track.yearList) != 0: commonYearList = [word for word, word_count in Counter(track.yearList).most_common(5)] commonYear = commonYearList[0] if len(commonYearList) > 1: for i in range(len(commonYearList) - 1): # prioritize older years to avoid quoting re-releases if len(track.yearList) <= 5 and int(commonYearList[0]) > int(commonYearList[i + 1]) and track.yearList.count(commonYearList[0]) <= track.yearList.count(commonYearList[i + 1]) * 2: commonYear = commonYearList[i + 1] elif int(commonYearList[0]) > int(commonYearList[i + 1]) and track.yearList.count(commonYearList[0]) <= track.yearList.count(commonYearList[i + 1]) * 1.5 and track.yearList.count(commonYearList[0]) > 1: commonYear = commonYearList[i + 1] if track.release_date != str(commonYear): track.release_date = str(commonYear) conflict = True # check BPM for false values if "BPM" in options["Selected Tags (L)"] and len(track.BPMList) != 0: commonBPMList = ([word for word, word_count in Counter(track.BPMList).most_common(3)]) commonBPM = commonBPMList[0] if len(commonBPMList) > 1 and int(commonBPMList[0]) * 2 == int(commonBPMList[1]) and int(commonBPMList[0]) < 85: commonBPM = commonBPMList[1] if track.bpm != str(commonBPM): track.bpm = str(commonBPM) conflict = True if "Key" in options["Selected Tags (L)"] and len(track.keyList) != 0: if len(multimode(track.keyList)) == 1: if track.key != str(mode(track.keyList)): track.key = str(mode(track.keyList)) conflict = True else: modeConflict(track, track.keyList, "key") conflict = True if "Genre" in options["Selected Tags (L)"] and len(track.genreList) != 0: if len(multimode(track.genreList)) == 1: if track.genre != str(mode(track.genreList)): track.genre = str(mode(track.genreList)) conflict = True else: modeConflict(track, track.genreList, "genre") conflict = True # update audio tags if conflict == True or imageCounter > 0: if filename.endswith(".flac"): FLAC_conflict(audio, track, options, initialCounter, imageCounter, images, informalTagDict) elif filename.endswith(".aiff") or filename.endswith(".mp3") or filename.endswith(".wav"): ID3_conflict(audio, track, options, initialCounter, imageCounter, images, informalTagDict) elif filename.endswith(".ogg"): Vorbis_conflict(audio, track, options, initialCounter, imageCounter, images, informalTagDict) elif filename.endswith(".m4a"): M4A_conflict(audio, track, options, initialCounter, imageCounter, images, informalTagDict) if len(str(track.artist) + " - " + str(track.title)) > characters: characters = len(str(track.artist) + " - " + str(track.title)) title = str(track.artist) + " - " + str(track.title) results = "" if "Release_Date" in options["Selected Tags (L)"]: results += "\nYear: " + str(track.release_date) if "BPM" in options["Selected Tags (L)"]: results += "\nBPM: " + str(track.bpm) if "Key" in options["Selected Tags (L)"]: results += "\nKey: " + str(track.key) if "Genre" in options["Selected Tags (L)"]: results += "\nGenre: " + str(track.genre) return title, results, webScrapingWindow, characters, track.imageSelection
def part2(input_list): co2 = input_list oxy = input_list o = 0 c = 0 for i in range(len(input_list[0])): if len(co2) != 1: most = max(multimode([row[i] for row in co2])) co2 = [row for row in co2 if row[i] == most] if len(oxy) != 1: most = max(multimode([row[i] for row in oxy])) oxy = [row for row in oxy if row[i] != most] o = int(oxy[0], 2) c = int(co2[0], 2) return o * c
def part2(input): o2set = set(range(0,len(input))) co2set = set(range(0,len(input))) bit_index = 0 new_list = input[:] while len(o2set)>1: old_list = new_list[:] new_list = [] for item in o2set: new_list.append(old_list[item]) transformed = [list(map(int, i)) for i in zip(*new_list)] multimodelist = statistics.multimode(transformed[bit_index]) most = multimodelist[-1] o2set = set(range(0,len(new_list))) o2setcopy = o2set.copy() for i in o2setcopy: if (transformed[bit_index][i]!=most): o2set.remove(i) bit_index+=1 o2 = int(new_list[list(o2set)[0]],2) bit_index = 0 new_list = input[:] while len(co2set)>1: old_list = new_list[:] new_list = [] for item in co2set: new_list.append(old_list[item]) transformed = [list(map(int, i)) for i in zip(*new_list)] multimodelist = statistics.multimode(transformed[bit_index]) most = multimodelist[0] co2set = set(range(0,len(new_list))) co2setcopy = co2set.copy() for i in co2setcopy: if (transformed[bit_index][i]==most): co2set.remove(i) bit_index+=1 co2 = int(new_list[list(co2set)[0]],2) return o2 * co2
def _modes(self): """ Returns as a list. Use "def pretty_modes" below for returning strings. """ modes = multimode(self.rolls_simulation) return modes
def stats(): listNum = int(input('How many numbers in your list?:')) nums = [] for i in range(listNum): nums.append(int(input(""))) op = input('What kind of operation would you like to do?\ \nChoose between "mode, mean, gmean, hmean, median, range, stdev" : ') if op == 'mode': return statistics.multimode(nums) elif op == 'mean': return statistics.mean(nums) elif op == 'gmean': return statistics.geometric_mean(nums) elif op == 'hmean': return statistics.harmonic_mean(nums) elif op == 'median': return statistics.median(nums) elif op == 'stdev': return statistics.stdev(nums) elif op == 'range': return max(nums) - min(nums)
def commonmedicine(patients, matchindexes, k): medicine = [] count = 0 for i in matchindexes: medicine.insert(count, patients[i][6]) count += 1 modes = statistics.multimode(medicine) biggest = medicine.count(modes[0]) #TODO if (len(modes) == k): print("Each of the %d patients were given a different medication" % k) elif (biggest >= float(k / 2)): print( "Medicine %d was given to %d of the %d patients (a majority of the patients)" % (int(modes[0]), biggest, k)) elif (len(modes) == 1): print( "Medicine %d was given to %d of the %d patients (not a majority of the patients)" % (int(modes[0]), biggest, k)) else: print( "Medicines %s were each given to %d of the %d patients (not a majority of the patients)" % (modes, biggest, k))
def countLargestGroup(self, n: int) -> int: """ Elegant but not very efficient solution. 1 - multiple transition between str and int types 2 - 'multimode' is very complex method (uses sorting, grouping, etc.) """ return len(multimode(sum(map(int, str(i))) for i in range(1, n + 1)))
def calculateMode(data): global mode ints = [int(item) for item in data] modeList = statistics.multimode(ints) mode = "" for item in modeList: mode += str(item) + ", " mode = mode[:-2]
def countLargestGroup(self, n): """ :type n: int :rtype: int """ return len( statistics.multimode( sum(map(int, str(i))) for i in range(1, n + 1)))
def minK(k, distances, pointSet): closestK = [] for i in range(2 * k - 1): for index in nthMinIndex(i, distances): closestK.append(pointSet[index][1]) try: return multimode(closestK)[0] except Exception: return 0
def co2_bit_criteria(data: str): report = data.splitlines() for pos in range(len(report[0])): col = [line[pos] for line in report] target = {"0": "1", "1": "0"}[max(multimode(col))] report = [line for line in report if line[pos] == target] if len(report) <= 1: return int(report[0], 2) raise ValueError(data)
def get_mode(k_nearest_labels: list) -> int: """ this function calculate mode for k_nearest_labels The mode of a sequence of numbers is the number with the highest frequency """ k_nearest_labels = [j for i in k_nearest_labels for j in i] k_nearest_labels = multimode(k_nearest_labels) return random.choice(k_nearest_labels)
def baseline_accuracy_row(brands_list, row): preds = [] for brand in brands_list: matches = find_brands(brand, row["transcription"]) for _ in matches: preds.append(brand) # now find most common value(s) preds = statistics.multimode([s.lower().replace("-", " ") for s in preds]) correct = any(equal_brands(pred, row["brand"]) for pred in preds) return pd.Series([preds, correct], index=["bl_preds", "bl_corrects"])
def migratoryBirds(arr): """ Determines the lowest, most frequent number. Parameters: arr (list): A list of integers. Returns: integer: The minimum mode. """ return min(multimode(arr))
def vote(df: pd.DataFrame, col_name: str) -> (Union[list, str], int, int): total = df.shape[0] voted = multimode(list(df.loc[:, col_name])) voted_count = df[df[col_name] == voted[0]].shape[0] if len(voted) == 1: # single mode value voted = voted[0] return voted, voted_count, total
def singlemode(data): try: # New in Python 3.8 modes = statistics.multimode(data) except AttributeError: return statistics.mode(data) else: if len(modes) > 1: raise statistics.StatisticsError('no unique mode') else: return modes[0]
def CalcularModa( datos): #Funcion para calcular la moda mediante la libreria statics try: #Intenta MM = stats.multimode( datos ) #Dentro de MM se guarda la multimoda calculada con stats.multimode pasandole los datos M = stats.mode( datos ) #Dentro de M se guarda la moda calculada con stats.mode pasandole los datos return [["Multimoda", MM], ["Moda", M]] except: #De lo contrario arroja error print("ERROR - No se pueden ejecutar la funcion con los datos")
def top(): #Call datebase to refresh data in route movie_list = datebase() top_10 = [] temporary_list = movie_list[:] #Check of temporary_list have more positions than temporary_set. If yes that means that at least #one movie have more recommendations than other movies temporary_set = set(temporary_list) #Check of there is at least on title with more than on recommendation if len(temporary_list) != len(list(temporary_set)): if len(temporary_set) >= 10: while len(top_10) != 10: if multimode(temporary_list): # There can be more than one movie with the same number of recommendations for movie in multimode(temporary_list): number_of_recommendations = 0 #Delete all accourances from temporary_list to find another most common occurance while movie in temporary_list: number_of_recommendations += 1 temporary_list.remove(movie) top_10.append([movie, number_of_recommendations]) #Solve problem if there are for exemple all 9 movies in top_10 and multimode gives #2 or more movies to add if len(top_10) == 10: break else: #If there is less than 10 movies in the datebase: while len(top_10) != len(temporary_set): if multimode(temporary_list): for movie in multimode(temporary_list): number_of_recommendations = 0 #Delete all accourances from temporary_list to find another most common occurance while movie in temporary_list: number_of_recommendations += 1 temporary_list.remove(movie) top_10.append([movie, number_of_recommendations]) return top_10
def part_2(file_path: str) -> int: with open(file_path, "r") as f: lines = f.read().splitlines() ox, co2, l = 0, 0, len(lines[0]) ox_lines = lines for i in range(l): multimode = statistics.multimode([line[i] for line in ox_lines]) mode = multimode[0] if len(multimode) == 1 else "1" ox_lines = [line for line in ox_lines if line[i] == mode] if len(ox_lines) == 1: ox = int(ox_lines[0], 2) break co2_lines = lines for i in range(l): multimode = statistics.multimode([line[i] for line in co2_lines]) mode = multimode[0] if len(multimode) == 1 else "1" co2_lines = [line for line in co2_lines if line[i] == f"{1-int(mode)}"] if len(co2_lines) == 1: co2 = int(co2_lines[0], 2) break return ox * co2
def analyze_categorical(): result['type'] = 'categorical' mode = statistics.multimode(actual_values) m1 = mode[0] result['mode 1'] = m1 result['mode 1 %'] = actual_values.count(m1) / len(actual_values) if len(mode) > 1: m2 = mode[1] result['mode 2'] = m2 result['mode 2 %'] = actual_values.count(m2) / len(actual_values) return result
def compute_top_songs_theory_helper(theory_dictionary): """Returns theory data on a user's top songs over a given time range :param theory_dictionary: keys refer to music theory features, values refer to a list of ints about the feature in user's top songs :type theory_dictionary: dictionary :rtype: dictionary :return: a sorted dictionary with both the song IDs (key) and song names (value) """ for feature in theory_dictionary: if feature == "key" or feature == "mode": # find the multimode (all "tied" elements are added into a list) theory_dictionary[feature] = multimode(theory_dictionary[feature]) else: # find the mean, round to 2 decimals theory_dictionary[feature] = round( sum(theory_dictionary[feature]) / len(theory_dictionary[feature]), 2) return theory_dictionary
def get_total_requests_in_sqs(): """ Runs a loop to find the Request queue sizes and takes a Mode over them to get the approximate size of queue :return: Size of the request queue in int. """ try: time.sleep(1) size_values = [] for _ in range(5): size_values.append(int(mq.get_queue_size(s.REQUEST_QUEUE))) logger.info("List of queue sizes fetched from SQS cluster: " + " ".join(str(value) for value in size_values)) approx_size = multimode(size_values)[0] logger.info("Approx size of Queue: %s", approx_size) except ClientError as error: raise error else: return approx_size
def most_frequent(self): self.chain_code_mode = [] col = 0 print(self.chain_codes.shape) print(self.chain_codes.shape[1]) while (col != self.chain_codes.shape[1]): aux = self.chain_codes.transpose()[col] # print(aux) value = statistics.multimode(aux) # print(value) if (len(value) == 1): self.chain_code_mode.append(value[0]) else: rand = random.randint(0, 1) self.chain_code_mode.append(value[rand]) col = col + 1 print(self.chain_code_mode) return (self.chain_code_mode)
def get_mode(k_nearest_labels: list) -> int: """ this function calculate mode for k_nearest_labels The mode of a sequence of numbers is the number with the highest frequency (the one which repeats the most). Parameters ---------- k_nearest_labels : list matrix of data(list of lists) Retunrs ------- int mode of k_nearest_labels """ k_nearest_labels = [j for i in k_nearest_labels for j in i] k_nearest_labels = multimode(k_nearest_labels) return random.choice(k_nearest_labels)
def simple_stats(): mean_list = statistics.mean(list_of_values) print("mean_list : ", mean_list) geometric_mean_list = statistics.geometric_mean(list_of_values) print("geometric_mean_list : ", geometric_mean_list) harmonic_mean_list = statistics.harmonic_mean(list_of_values) print("harmonic_mean_list : ", harmonic_mean_list) median_list = statistics.median(list_of_values) print("median_list : ", median_list) median_low_list = statistics.median_low(list_of_values) print("median_low_list : ", median_low_list) median_high_list = statistics.median_high(list_of_values) print("median_high_list : ", median_high_list) median_grouped_list = statistics.median_grouped(list_of_values) print("median_grouped_list : ", median_grouped_list) mode_list = statistics.mode(list_of_values) print("mode_list : ", mode_list) multimode_list = statistics.multimode(list_of_values) print("multimode_list : ", multimode_list) quantiles_list = statistics.quantiles(list_of_values) print("quantiles_list : ", quantiles_list) return mean_list, geometric_mean_list, harmonic_mean_list, median_list, median_low_list, median_high_list, median_grouped_list, mode_list, multimode_list, quantiles_list
def checkio(text: str) -> str: lowertext=list(text.lower()) for x in lowertext[:]: if ord(x) < 65: lowertext.remove(x) return min(statistics.multimode(lowertext)) #END OF MY CODE, THE REST IS THEIR TESTING if __name__ == '__main__': print("Example:") print(checkio("Hello World!")) #These "asserts" using only for self-checking and not necessary for auto-testing assert checkio("Hello World!") == "l", "Hello test" assert checkio("How do you do?") == "o", "O is most wanted" assert checkio("One") == "e", "All letter only once." assert checkio("Oops!") == "o", "Don't forget about lower case." assert checkio("AAaooo!!!!") == "a", "Only letters." assert checkio("abe") == "a", "The First." print("Start the long test") assert checkio("a" * 9000 + "b" * 1000) == "a", "Long." print("The local tests are done.")
def run(): data = read_data() sales = [] for row in data: print(row) #put the print function into the loop so you can see which keys the data set has and fix an error messages #relating to a key issue --> key error sale = int(row['Sales']) sales.append(sale) total = sum(sales) minimum = min(sales) maximum = max(sales) average = mean(sales) Middepoint = median(sales) Modes = multimode(sales) SampleSpread = stdev(sales) print('Total sales: {}' .format(total)) print('Minimum sales: {}' .format(minimum)) print('Maximum sales: {}' .format(maximum)) print('Arithmetic Mean: {}' .format(average)) print('Ordinary Statistical Median: {}' .format(Middepoint)) print('Total Modes: {}' .format(Modes)) print('Sample Dispersion: {}' .format(SampleSpread))
def run(): data = read_data() covid = [] for row in data: print(row) #put the print function into the loop so you can see which keys the data set has and fix an error messages #relating to a key issue --> key error coviddeaths = int(row['6/22/20']) covid.append(coviddeaths) total = sum(covid) minimum = min(covid) maximum = max(covid) average = mean(covid) Middepoint = median(covid) Modes = multimode(covid) SampleSpread = stdev(covid) print('Total deaths: {}' .format(total)) print('Minimum deaths: {}' .format(minimum)) print('Maximum deaths: {}' .format(maximum)) print('Arithmetic Mean: {}' .format(average)) print('Ordinary Statistical Median: {}' .format(Middepoint)) print('Total Modes: {}' .format(Modes)) print('Sample Dispersion: {}' .format(SampleSpread))
for i in range(n - 1): diff.append(values[i + 1] - values[i]) diff_len = len(set(diff)) if n == 1: print(-1) elif diff_len == 1: if diff[0] == 0: works = [values[-1] + diff[0]] print(len(works)) print(*sorted(works)) else: works = [values[0] - diff[0], values[-1] + diff[0]] if n == 2: if not (values[0] + values[1]) % 2: works.append((values[0] + values[1]) // 2) print(len(works)) print(*sorted(works)) elif diff_len == 2: common, works = min(statistics.multimode(diff)), [] if common: for i in range(1, n): if values[i - 1] + common == values[i] - common: works.append(values[i - 1] + common) if len(works) > 1: works = [] print(len(works)) if works: print(*sorted(works)) else: print(0)