def main(): fileInteraction = FileIO() # Create instances of FileIO and UserIO userInteraction = UserIO() userInteraction.printWelcomeMessage() # Print the welcome message fileInteraction.getInfoFromFile() # Get the infro from the file ageArray = fileInteraction.getAgeArray() # Retreive the variablies required from the file countryArray = fileInteraction.getCountryArray() firstNationalityArray = fileInteraction.getFavNationalityArray() secondNationalityArray = fileInteraction.getSecondFavNationalityArray() thirdNationalityArray = fileInteraction.getThirdFavNationalityArray() genderArray = fileInteraction.getGenderArray() nationalityArray = fileInteraction.getNationalityArray() spicyArray = fileInteraction.getSpicyArray() userInteraction.getInitialInformation() # Get the user's information age = userInteraction.getAgeRange() # Retreive the variables required from the user country = userInteraction.getLocation() favourites = userInteraction.getFoodFavorites() firstFavourite = favourites[0] secondFavourite = favourites[1] thirdFavourite = favourites[2] gender = userInteraction.getGender() nationality = userInteraction.getNationality() spicy = userInteraction.getSpicy() sortClass = Sort(gender, nationality, age, spicy, favourites, country, genderArray, nationalityArray, ageArray, spicyArray, countryArray, firstNationalityArray, secondNationalityArray, thirdNationalityArray) recommendations = sortClass.getRankings() # Sort the recommendations and then get the rankings from the class userInteraction.displayRecommendations(recommendations) # Display the recommendations
def main(): # sample data n = 10000 lst = list() # generate random array for i in xrange(n): lst.append(random.randint(1, n*10)) # lst = np.random.random_integers(1, 10000000, 1000000) # sort() lstcopy = list(lst) t1 = time.time() lstcopy.sort() t2 = time.time() print("Calculation of python sort() took " + str(t2-t1) + " seconds") # mergesort lstcopy = list(lst) t1 = time.time() lstcopy = Sort.mergesort(lst) t2 = time.time() print("Calculation of Sort.mergesort() took " + str(t2-t1) + " seconds") # quicksort lstcopy = list(lst) t1 = time.time() lstcopy = Sort.quicksort(lst) t2 = time.time() print("Calculation of Sort.quicksort() took " + str(t2-t1) + " seconds")
def test_five_unordered(self): on_test = arr_five_unordered[:] Sort.selection_sort(on_test) self.assertEqual(len(on_test), len(arr_five_ordered)) for new, old in zip(on_test, arr_five_ordered): self.assertEqual( new, old, "{} is not equal to {}".format(on_test, arr_five_ordered))
def test_sort_list_string(): items = ['bob', 'joe', 'jane', 'isabelle'] Sort.heapsort(items) assert (items[0] == 'bob') assert (items[1] == 'isabelle') assert (items[2] == 'jane') assert (items[3] == 'joe')
def test_single(self): on_test = arr_singleton[:] Sort.selection_sort(on_test) self.assertEqual(len(on_test), len(arr_singleton)) for new, old in zip(on_test, arr_singleton): self.assertEqual( new, old, "{} is not equal to {}".format(on_test, arr_singleton))
def test_three_reversed(self): on_test = arr_three_reversed[:] Sort.bubble_sort(on_test) self.assertEqual(len(on_test), len(arr_three_ordered)) for new, old in zip(on_test, arr_three_ordered): self.assertEqual( new, old, "{} is not equal to {}".format(on_test, arr_three_ordered))
def test_three_repeat(self): on_test = arr_three_repeat[:] Sort.selection_sort(on_test) self.assertEqual(len(on_test), len(arr_three_repeat)) for new, old in zip(on_test, arr_three_repeat): self.assertEqual( new, old, "{} is not equal to {}".format(on_test, arr_three_repeat))
def testHeapify(self): # Test that the root node is sorted to the left child data = [1, 9, 5] Sort._heapify(data, 0, 3) self.assertEqual(data, [9, 1, 5]) # Test that the root node is sorted to the bottom left grand-child data = [1, 5, 9, 1, 3, 2] Sort._heapify(data, 0, 6) self.assertEqual(data, [9, 5, 2, 1, 3, 1])
def test_sort_list_numbers(): items = [5, 4, 2, 3, 1, 6] Sort.heapsort(items) assert (items[0] == 1) assert (items[1] == 2) assert (items[2] == 3) assert (items[3] == 4) assert (items[4] == 5) assert (items[5] == 6)
def testMerge(self): # Test that the two sub-arrays created from an even number of items are properly merged data = [1, 9, 2, 2] Sort._merge(data, 0, 1, 3) self.assertEqual(data, [1, 2, 2, 9]) # Test that the two sub-arrays created from an off number of items are properly merged data = [3, 9, 2, 1, 7] Sort._merge(data, 0, 2, 4) self.assertEqual(data, [1, 3, 7, 9, 2])
def testMergeSort(self): # Test that the list is properly sorted when using an even number of items data = [1, 5, 9, 1, 3, 2] Sort.mergeSort(data) self.assertEqual(data, [1, 1, 2, 3, 5, 9]) # Test that the list is properly sorted when using an odd number of items data = [1, 5, 9, 1, 3, 2, 7] Sort.mergeSort(data) self.assertEqual(data, [1, 1, 2, 3, 5, 7, 9])
def Sorting_t(a,b): c=[] d=[] for i in a: ct=timeit.timeit(lambda: s.merge(b[:i]),number=10 ) c.append(ct) dt=timeit.timeit(lambda : s.QuickSort(b[:i]), number=10) d.append(dt) Show_graph(a,[c,d], ['Merge sort', 'Quick sort']) plt.title('Sorting time') plt.show()
def test_sort_list_string(): items = Array(4) items[0] = 'bob' items[1] = 'joe' items[2] = 'jane' items[3] = 'isabelle' Sort.heapsort(items) assert (items[0] == 'bob') assert (items[1] == 'isabelle') assert (items[2] == 'jane') assert (items[3] == 'joe')
def test_sciEql(self): """! Testing of sciEql method """ num1, num2 = 1.77, 1.84 self.assertEqual(False, Sort.sciEql(num1, num2)) num3, num4 = 2.09, 2.09 self.assertEqual(True, Sort.sciEql(num3, num4)) num5, num6 = 3, 1 self.assertEqual(False, Sort.sciEql(num5, num6)) num7, num8 = 0.9155658, 0.9155650 self.assertEqual(True, Sort.sciEql(num7, num8)) num9, num10 = 10, 19 self.assertEqual(False, Sort.sciEql(num9, num10))
def test_sciCmp(self): """! Testing of sciCmp method """ num1, num2 = 1.77, 1.84 self.assertEqual(1.84, Sort.sciCmp(num1, num2)) num3, num4 = 2.09, 2.09 self.assertEqual(0, Sort.sciCmp(num3, num4)) num5, num6 = 3, 1 self.assertEqual(3, Sort.sciCmp(num5, num6)) num7, num8 = 0.9155658, 0.9155650 self.assertEqual(0, Sort.sciCmp(num7, num8)) num9, num10 = 10, 19 self.assertEqual(19, Sort.sciCmp(num9, num10))
def test_checkAvailable(self): """! Testing of checkAvailable method """ tst1 = [1, 2, 3, 4, 5, 6, 4] self.assertEqual(False, Sort.checkAvailable(tst1)) tst2 = [0, 2, 3, 4, 5, 6, 1] self.assertEqual(False, Sort.checkAvailable(tst2)) tst3 = [1, 2, 3, 4, 5, 6] self.assertEqual(True, Sort.checkAvailable(tst3)) tst4 = [-10, -8, -6, -7] self.assertEqual(True, Sort.checkAvailable(tst4)) tst5 = [1.0, 2.0, 1.5, 3, 5, 6, 4] self.assertEqual(True, Sort.checkAvailable(tst5))
def linear_rank_select(generation, fitness_values, pop_size): new_generation = [] sorted_gen, sorted_fitness = Sort.sort(generation, fitness_values) ranks = [] selection_prob = [] for x in range(len(fitness_values)): ranks += [x + 1] sum_of_ranks = np.sum(ranks) #print(sum_of_ranks) for x in range(len(ranks)): selection_prob += [round(ranks[x] / sum_of_ranks, 2)] max_range = selection_prob[len(selection_prob) - 1] #print(max_range) while pop_size > len(new_generation): rand = round(random.uniform(0, max_range), 2) for individual in range(len(sorted_gen)): for x in range(len(fitness_values)): if selection_prob[x] == rand: new_generation += [sorted_gen[individual]] #print(rand) #print(selection_prob) #print(new_generation) return new_generation
def getSortsDebutCombat(lvl): """@summary: charge les sorts de combat @return: List <Sort> """ # pylint: disable=unused-argument sortsDebutCombat = [] sortsDebutCombat.append( Sort.Sort( "Ebrité", 0, 0, 0, 0, [ EffetEtatSelf( EtatEffetSiLance( "Tournée Générale si lancé", 0, -1, EffetRetPM( 3, 1, cibles_possibles="Ennemis", cibles_possibles_direct="Tonneau Incapacitant", zone=Zones.TypeZoneCercle(1)), "Tournée Générale")), ], [], 0, 99, 99, 0, 0, "cercle", False, chaine=False)) return sortsDebutCombat
def __init__(self, database, options, user): """ Create the Timeline object that produces the report. The arguments are: database - the GRAMPS database instance options - instance of the Options class for this report user - instance of gen.user.User() This report needs the following parameters (class variables) that come in the options class. filter - Filter to be applied to the people of the database. The option class carries its number, and the function returning the list of filters. sortby - Sorting method to be used. """ Report.__init__(self, database, options, user) self._user = user menu = options.menu self.filter = menu.get_option_by_name('filter').get_filter() sort_func_num = menu.get_option_by_name('sortby').get_value() sort_functions = _get_sort_functions(Sort.Sort(database)) self.sort_name = sort_functions[sort_func_num][0] self.sort_func = sort_functions[sort_func_num][1] self.calendar = config.get('preferences.calendar-format-report')
def triggerAvantSubirDegats(self, cibleAttaque, niveau, totalPerdu, typeDegats, attaquant): """@summary: Un trigger appelé pour tous les états du joueur attaqué lorsque des dommages vont être subits. Redistribue une partie des dégâts qui vont être subit au corps-à-corps sur la zone définit. @cibleAttaque: le joueur qui va subir les dégâts @type: joueur @niveau: La grille de jeu @type: Niveau @totalPerdu: Le total de vie que le joueur va subir. @type: int @typeDeg: Le type de dégâts qui va être subit @type: string @attaquant: Le joueur à l'origine de l'attaque @type: Personnage""" if cibleAttaque.team != attaquant.team: distance = abs(attaquant.posX-cibleAttaque.posX) + \ abs(attaquant.posY-cibleAttaque.posY) if distance == 1: if typeDegats.lower() in ["terre", "eau", "air", "feu", "neutre"]: retour = int( ((self.pourcentage/100)*totalPerdu) + cibleAttaque.doRenvoi) sortContre = \ Sort.Sort("Contre", 0, 0, 0, 1, [EffetDegats(retour, retour, typeDegats, zone=Zones.TypeZoneCercle(self.tailleZone), cibles_possibles="Ennemis", bypassDmgCalc=True)], [], 0, 99, 99, 0, 0, "cercle", False) sortContre.lance(cibleAttaque.posX, cibleAttaque.posY, niveau, attaquant.posX, attaquant.posY)
def getSorts(lvl): """@summary: charge les sorts de combat @return: List <Sort> """ # pylint: disable=unused-argument sorts = [] sorts.append( Sort.Sort( "Protection du Lapino", 0, 3, 0, 8, [ EffetEtat(EtatBouclierPerLvl("Protection du lapino", 0, 1, 73), cibles_possibles="Allies|Lanceur") ], [], 0, 99, 99, 0, 0, "cercle", False, description="""Applique un bouclier de 72% du lvl de la cible.""")) return sorts
def getSorts(lvl): """@summary: charge les sorts @return: List <Sort> """ # pylint: disable=unused-argument sorts = [] sorts.append( Sort.Sort("Rappel", 0, 0, 0, 0, [ EffetEchangePlace(zone=Zones.TypeZoneInfini(), cibles_possibles_direct="Lanceur", cibles_possibles="Cra", pile=False), EffetTue(zone=Zones.TypeZoneInfini(), cibles_possibles_direct="Cra", cibles_possibles="Lanceur", pile=False) ], [], 0, 99, 99, 0, 0, "cercle", False, chaine=False)) return sorts
def getSorts(lvl): """@summary: charge les sorts de combat @return: List <Sort> """ # pylint: disable=unused-argument sorts = [] sorts.append( Sort.Sort( "Synchronisation", 0, 0, 0, 0, [ EffetDegats(100, 130, "feu", zone=Zones.TypeZoneCercleSansCentre(4), cibles_possibles="Ennemis|Lanceur", etat_requis_cibles="Telefrag"), EffetEtat(EtatBoostCaracFixe("Synchronisation", 0, 1, "PA", 2), zone=Zones.TypeZoneCercleSansCentre(4), cibles_possibles="Allies|Lanceur", etat_requis_cibles="Telefrag") ], [], 0, 99, 99, 0, 0, "cercle", False, chaine=False)) return sorts
def add_menu_options(self, menu): """ Define the options for the menu. """ category_name = _("Tool Options") self.__filter = FilterOption(_("Filter"), 0) self.__filter.set_help(_("Select the people to sort")) menu.add_option(category_name, "filter", self.__filter) self.__filter.connect('value-changed', self.__filter_changed) self.__pid = PersonOption(_("Filter Person")) self.__pid.set_help(_("The center person for the filter")) menu.add_option(category_name, "pid", self.__pid) self.__pid.connect('value-changed', self.__update_filters) self.__update_filters() sort_by = EnumeratedListOption(_('Sort by'), 0) idx = 0 for item in _get_sort_functions(Sort.Sort(self.__db)): sort_by.add_item(idx, item[0]) idx += 1 sort_by.set_help(_("Sorting method to use")) menu.add_option(category_name, "sort_by", sort_by) sort_desc = BooleanOption(_("Sort descending"), False) sort_desc.set_help(_("Set the sort order")) menu.add_option(category_name, "sort_desc", sort_desc) family_events = BooleanOption(_("Include family events"), True) family_events.set_help(_("Sort family events of the person")) menu.add_option(category_name, "family_events", family_events)
def getSorts(lvl): """@summary: charge les sorts de début de combat @return: List <Sort> """ # pylint: disable=unused-argument sorts = [] sorts.append( Sort.Sort( "Beuverie", 0, 0, 0, 15, [ EffetAttire(8, cibles_possibles="Ennemis"), EffetAttire( 8, cibles_possibles="Allies", etat_requis_cibles="Saoul") ], [], 0, 99, 1, 0, 0, "ligne", True, chaine=False)) return sorts
def test_sort_array_numbers(): items = Array(6) items[0] = 5 items[1] = 4 items[2] = 2 items[3] = 3 items[4] = 1 items[5] = 6 Sort.heapsort(items) assert (items[0] == 1) assert (items[1] == 2) assert (items[2] == 3) assert (items[3] == 4) assert (items[4] == 5) assert (items[5] == 6)
def getSorts(lvl): """@summary: charge les sorts de début de combat @return: List <Sort> """ # pylint: disable=unused-argument sorts = [] sorts.append( Sort.Sort("Bambou Malchanceux", 0, 0, 0, 1, [ EffetEtat(EtatBoostCaracFixe("Bambou Malchanceux", 0, 1, "tacle", -23)) ], [], 0, 1, 1, 0, 0, "ligne", True, description="Retire du tacle à la cible pour 1 tour.") ) sorts.append( Sort.Sort("Coup de Bambou", 0, 2, 0, 1, [ EffetEtat(EtatBoostCaracFixe("Coup de Bambou", 0, 2, "pui", -70)), EffetEtat(Etat("Affaibli", 0, 2)), ], [], 0, 1, 1, 3, 0, "ligne", True, description="Retire de la puissance à la cible et lui applique l'état affaibli.") ) return sorts
def getSortsDebutCombat(lvl): """@summary: charge les sorts de début combat @return: List <Sort> """ # pylint: disable=unused-argument sortsDebutCombat = [] sortsDebutCombat.append( Sort.Sort("Réduction des dégâts alliés", 0, 0, 0, 0, [ EffetEtatSelf( EtatModDegPer("Réduction des dégâts alliés", 0, -1, 50, provenance="Allies")) ], [], 0, 99, 99, 0, 0, "cercle", False)) sortsDebutCombat.append( Sort.Sort("Soin si subit", 0, 0, 0, 0, [ EffetEtatSelf( EtatEffetSiSubit("Soigne allié qui l'attaque", 0, -1, EffetSoinSelonSubit(100), "Soin de fiole", "cible", "attaquant", "", "Allies")) ], [], 0, 99, 99, 0, 0, "cercle", False)) sortsDebutCombat.append( Sort.Sort("Explose", 0, 0, 0, 0, [ EffetEtatSelf( EtatEffetSiMeurt( "Explose", 0, -1, EffetDegats(22, 26, "Terre", zone=Zones.TypeZoneCercleSansCentre(2)), "Soin de fiole", "lanceur", "mouru")) ], [], 0, 99, 99, 0, 0, "cercle", False)) sortsDebutCombat.append( Sort.Sort("Trop de stimulation!", 0, 0, 0, 0, [ EffetEtatSelf( EtatEffetSiNouvelEtat("Meurt si stimulé", 0, -1, EffetTue(), "Meurt si stimulé", "porteur", "Stimulé")) ], [], 0, 99, 99, 0, 0, "cercle", False)) return sortsDebutCombat
def run(self): """ Perform the actual extraction of information. """ menu = self.options.menu self.filter = menu.get_option_by_name('filter').get_filter() sort_func_num = menu.get_option_by_name('sort_by').get_value() self.sort_desc = menu.get_option_by_name('sort_desc').get_value() self.fam_events = menu.get_option_by_name('family_events').get_value() sort_functions = _get_sort_functions(Sort.Sort(self.db)) self.sort_name = sort_functions[sort_func_num][0] self.sort_func = sort_functions[sort_func_num][1] self.sort = Sort.Sort(self.db) with DbTxn(_("Sort event changes"), self.db, batch=True) as trans: self.db.disable_signals() family_handles = self.sort_person_events(trans) if len(family_handles) > 0: self.sort_family_events(family_handles, trans) self.db.enable_signals() self.db.request_rebuild()
def __init__(self, database, options, user): """ Create the DescendantReport object that produces the report. The arguments are: database - the GRAMPS database instance options - instance of the Options class for this report user - a gen.user.User() instance This report needs the following parameters (class variables) that come in the options class. gen - Maximum number of generations to include. name_format - Preferred format to display names dups - Whether to include duplicate descendant trees """ Report.__init__(self, database, options, user) menu = options.menu self.max_generations = menu.get_option_by_name('gen').get_value() pid = menu.get_option_by_name('pid').get_value() self.center_person = database.get_person_from_gramps_id(pid) if (self.center_person == None): raise ReportError(_("Person %s is not in the Database") % pid) sort = Sort.Sort(self.database) self.by_birthdate = sort.by_birthdate #Initialize the Printinfo class self._showdups = menu.get_option_by_name('dups').get_value() numbering = menu.get_option_by_name('numbering').get_value() if numbering == "Simple": obj = PrintSimple(self._showdups) elif numbering == "de Villiers/Pama": obj = PrintVilliers() elif numbering == "Meurgey de Tupigny": obj = PrintMeurgey() else: raise AttributeError("no such numbering: '%s'" % self.numbering) marrs = menu.get_option_by_name('marrs').get_value() divs = menu.get_option_by_name('divs').get_value() # Copy the global NameDisplay so that we don't change application defaults. self._name_display = copy.deepcopy(global_name_display) name_format = menu.get_option_by_name("name_format").get_value() if name_format != 0: self._name_display.set_default_format(name_format) self.objPrint = Printinfo(self.doc, database, obj, marrs, divs, self._name_display)
def test_InsertionSort(self): """! Testing of insertion sort method """ tst11 = [1, 2, 3, 7, 5, 6, 4] true_tst11 = [1, 2, 3, 4, 5, 6, 7] self.assertEqual(true_tst11, Sort.InsertionSort(tst11)) tst12 = [-1, -2, -3, -7, -5, -6, -4] true_tst12 = [-7, -6, -5, -4, -3, -2, -1] self.assertEqual(true_tst12, Sort.InsertionSort(tst12)) tst13 = [10, -2, 3, -7, 5, 6, -4] true_tst13 = [-7, -4, -2, 3, 5, 6, 10] self.assertEqual(true_tst13, Sort.InsertionSort(tst13)) tst14 = [5.0, 4.0, 3.0, 2.0, 1.0] true_tst14 = [1.0, 2.0, 3.0, 4.0, 5.0] self.assertEqual(true_tst14, Sort.InsertionSort(tst14)) tst15 = [] true_tst15 = [] self.assertEqual(true_tst15, Sort.InsertionSort(tst15))
def getSorts(lvl): """@summary: charge les sorts de début de combat @return: List <Sort> """ # pylint: disable=unused-argument sorts = [] sorts.append(Sort.Sort("Cawotte", 0, 4, 1, 6, [EffetInvoque("Cawotte", False, cibles_possibles="", cible_non_requise=True)], [], 0, 1, 1, 6, 0, "cercle", True, description="Invoque une Cawotte")) return sorts
def testHeapSort(self): # Test a small list data = [1, 5, 9, 1, 3, 2] Sort.heapSort(data) self.assertEqual(data, [1, 1, 2, 3, 5, 9])
def testBubbleSort(self): # Test that the list is sorted data = [1, 5, 9, 1, 3, 2] Sort.bubbleSort(data) self.assertEqual(data, [1, 1, 2, 3, 5, 9])
def testQuickSort(self): # Test that the list is properly sorted data = [1, 5, 9, 1, 3, 2] Sort.quickSort(data) self.assertEqual(data, [1, 1, 2, 3, 5, 9])
for j in range(0, len(key) - 1): sortArray.append(key[j] + "," + firstName[j] + " " + lastName[j]); correctFlag = False flag = raw_input("How would you like to sort the data (ASC, DESC):"); if (flag == "ASC") or (flag == "DESC") or (flag == "asc") or (flag == "desc"): correctFlag = True if (correctFlag == False): print("Incorrect sort flag. Please type in only ASC or DESC"); print("Please restart application and try again."); os._exit(0); sortedArray = Sort.quickSort(sortArray, flag); #Split Content del key[:]; del firstName[:]; del lastName[:]; for line in sortedArray: splitVals = line.split(','); key.append(splitVals[0]); nameSplit = splitVals[1].split(' '); firstName.append(nameSplit[0]); lastName.append(nameSplit[1]); #OutputFile
def testBucketSort(self): data = [1, 5, 9, 1, 3, 2] Sort.bucketSort(data) self.assertEqual(data, [1, 1, 2, 3, 5, 9])
def testPartition(self): # Test that the list is properly partitioned data = [1, 5, 9, 1, 3, 2] pivotPos = Sort._partition(data, 0, 5) self.assertEqual(data, [1, 1, 2, 5, 9, 3]) self.assertEqual(pivotPos, 2)
import Sort from Sort import verify import random ls = [random.randint(0,100) for i in xrange(100)] Sort.selectionSort(ls) print verify(ls) ls = [random.randint(0,100) for i in xrange(100)] Sort.insertionSort(ls) print verify(ls) ls = [random.randint(0,100) for i in xrange(100)] ls = Sort.mergeSort(ls) print verify(ls) ls = [random.randint(0,100) for i in xrange(100)] Sort.quickSort(ls) print verify(ls)
# Program to find the total score of all names in a file (see https://projecteuler.net/problem=22 for file), where # the score of a name is the sum of the numeric value for a character multiplied by its position when sorted, # where 'a' = 1, 'b' = 2, etc import Sort names = [] with open("p022_names.txt") as filestream: for line in filestream: currentline = line.split(",") for i in currentline: names.append(i) sorted_names = Sort.sort(names) all_names_total = 0 for name in sorted_names: total = 0 number = [ord(char)-96 for char in name[1:-1].lower()] total = sum(number) all_names_total += total*(sorted_names.index(name)+1) filestream.close() print(all_names_total) #answer = 871198282
def testInsertionSort(self): # Sort the random numbers Sort.insertionSort(self.testData) # Verify that the numbers were properly sorted self.assertEqual(self.testData, range(-10, 10))
def testBuildHeap(self): # Test that the list is built into a heap data = [1, 5, 9, 1, 3, 2] Sort._buildHeap(data) self.assertEqual(data, [9, 5, 2, 1, 3, 1])