def problem_4(): print("\nVous avez sélectionné le problème suivant :") print("-----------------------------------") print("Quel est le plus grand palindrome que l'on peut obtenir en multipliant un nombre de x chiffres avec un nombre de y chiffres ?") print("===================================\n") digit1 = utilities.check_input("Veuillez entrer le premier nombre de chiffres : ") digit2 = utilities.check_input("Veuillez entrer le deuxième nombre de chiffres : ") # Get the greatest number in the range of the digit (example : if digit = 3, max = 999) greatest1 = utilities.greatest_number(digit1) greatest2 = utilities.greatest_number(digit2) palindrome = 0 # Multiplication till a palindrome is found for number1 in range(greatest1, -1, -1): for number2 in range(greatest2, -1, -1): resultat = number1*number2 # Check if it's a palindrome if(utilities.is_palindrome(resultat)): if(resultat > palindrome): palindrome = resultat print("Le nombre suivant est un palindrome : {}".format(palindrome))
def set_render(self, render, number): render = utilities.check_input(render, image.Image) new_number = utilities.check_input(number, int) if new_number is not False: self.renders[new_number] = render return self
def set_gravity(self, strength): new_strength = utilities.check_input(strength, float) if -100 > new_strength > 100: raise Exception(f'Gravity cannot be set to {new_strength}. Please set it to a float number between -100 and 100.') else: self.gravity = new_strength / 10
def set_target_fps(fps): new_fps = utilities.check_input(fps, int) if 0 < new_fps < 10000: renderer.run_FPS = new_fps else: raise Exception(f'FPS cannot be set to {new_fps}. Make sure it is between 0 and 10000.')
def problem_3(): print("\nVous avez sélectionné le problème suivant :") print("-----------------------------------") print("Quel est le plus grand facteur premier du nombre x ?") print("===================================\n") # Return a correct input number = utilities.check_input("Veuillez entrer le nombre dont vous voulez trouver les facteurs premiers : ") # List of all the prime numbers found in the range max divided by 2 prime_numbers = utilities.list_prime_numbers(number//2) # List for the prime factors that will be found prime_factors = [] # Loop to check all the prime factors for prime in prime_numbers: while number%prime == 0: number //= prime prime_factors.append(prime) # If no prime factor, the number entered is its own if len(prime_factors) == 0: prime_factors.append(number) print("\nVoici la liste des facteurs premiers pour le nombre renseigné : ", prime_factors) print("\nVoici le plus grand facteur premier pour le nombre renseigné : {}".format(max(prime_factors))) print("===================================\n")
def set_starting_state(self, state): # for state based off its contents if type(state) == str: found = False for i in range(len(self.states)): if self.states[i] == state: found = True self.current_state = i if found is False: raise Exception(f'State {str(state)} does not seem to exist.') new_state = utilities.check_input(state, int) # for state based of place in list if new_state is not False: if new_state < 0 or new_state > len(self.states): raise Exception( f'State number {new_state} does not seem to exist. Try making it between 0 and {len(self.states)}' ) else: self.current_state = new_state raise Exception( f'State {state} could not be found. Make sure it is either of type int or str.' )
def set_animation_from_files(self, file_names): new_file_names = utilities.check_input(file_names, list) for i in range(len(new_file_names)): new_image = image.Image() new_image.set_image_from_file(str(file_names[i])) self.renders.append(new_image)
def get_render(self, number): new_number = utilities.check_input(number, int) if new_number < 0 or new_number > len(self.renders): raise Exception( f'Render {new_number} does not seem to exist. Make sure it is between 0 and ' f'{len(self.renders)}.') else: return self.renders[number]
def go_to_animation(self, number): new_number = utilities.check_input(number, int) if new_number < 0 or new_number > len(self.renders): raise Exception( f'Animation {number} does not exist. Needs to be in range 0 to {len(self.renders) - 1}' ) else: self.current_render = new_number self.update_collider()
def set_speed(self, speed): new_speed = utilities.check_input(speed, float) if self.velocity[1] == 0: self.velocity = (self.velocity[0], 0.0001) direction = math.atan(self.velocity[0] / self.velocity[1]) % 360 magnitude = new_speed self.velocity = utilities.angle_magnitude_to_vector(magnitude, direction)
def problem_5(): print("\nVous avez sélectionné le problème suivant :") print("-----------------------------------") print("Que vaut la somme des chiffres composant le nombre x^y ?") print("===================================\n") number = utilities.check_input("Veuillez entrer le nombre que vous voulez : ") exponent = utilities.check_input("Veuillez entrer l'exposant que vous voulez : ") # Get pow result from the two inputs pow_result = str(pow(number, exponent)) # Create the variable for the sum pow_sum = 0.0 for x in pow_result: if x != '.': pow_sum += int(x) print("\nLa somme des chiffres composant le nombre {}^{} est égale à {}".format(number, exponent, pow_sum)) print("===================================\n")
def get_darker(self, amount): new_amount = utilities.check_input(amount, int) if self.red >= new_amount: red = self.red - new_amount if self.green >= new_amount: blue = self.red - new_amount if self.blue >= new_amount: green = self.red - new_amount return red, green, blue raise Exception( f'Make sure that the amount is smaller than the current shade for all parts. Amount: ' f'{new_amount}, current shade: {self.colour}.')
def problem_1(): print("\nVous avez sélectionné le problème suivant :") print("-----------------------------------") print("Trouver la somme de tous les multiples de 5 ou 7 inférieurs à x") print("===================================\n") # Return a correct input max = utilities.check_input("Veuillez entrer le nombre maximum pour effectuer la somme : ") # Sum of all the multiples of 5 and 7 result = sum([x for x in range(max) if x % 5 == 0 or x % 7 == 0]) print("\nLa somme des multiples de 5 et 7 du nombre que vous avez entré est égale à :", result) print("===================================\n")
def get_component(self, type_): new_type = utilities.check_input(type_, str) if new_type is not False: if new_type == 'script': scripts = [] for component in self.components: if component.type == new_type: scripts.append(component) return scripts else: for component in self.components: if component.type == new_type: return component return False
def main(): print("\t-----------------") print("\t-- Défi Turing --") print("\t-----------------\n") # Program must_be_stopped = False # Loop to keep going on the problem resolving while must_be_stopped == False: print("Liste des problèmes résolus :") print("-----------------------------") # Print the list of all resolved problems for problem in utilities.problems: print("\n\t{}".format(problem)) print("\n=============================\n") # Check if the value of the input is correct number = utilities.check_input( "Sélectionnez le problème que vous souhaitez résoudre : ") # Function that will look into the list of problems to solve utilities.problem_to_solve(number) # Value is_ok = False # Condition to end the program while is_ok == False: stop = input("Voulez-vous arrêter le programme ? (y/n) ") # Check if the value of the input is correct if stop.isdigit() or (stop != 'y' and stop != 'n'): print("Veuillez rentrer une valeur correcte.") continue elif stop == 'n': is_ok = True else: is_ok = True must_be_stopped = True print("===============================\n")
def check_hit_box_collision(self, hit_box): hit_box = utilities.check_input(hit_box, HitBox) if hit_box.x + hit_box.size_x < self.x: return False elif hit_box.x > self.x + self.size_x: return False elif hit_box.y + hit_box.size_y < self.y: return False elif hit_box.y > self.y + self.size_y: return False else: return True
def main(): ''' Summary of behavior: starts, restarts, and manages the child processes Arguments: None Return values: Side effects: child processes launched and monitored for success Exceptions raised: Restrictions on when it can be called: None ''' config = utilities.parse_config('dad') round_length = int(config['round_length']) total_rounds = int(config['total_rounds']) time_between_check = int(config['time_between_check']) log_file = config['log_file'] utilities.log_data(log_file, 'Began operations at '+str(time.time())+'\n') child = CHILD('ChildNO') for i in range(0, total_rounds): time_start = time.time() while time.time() - time_start < round_length: print(str(time.time()-time_start)) if utilities.check_input(child.process.poll(), 1): if child.process.poll() == 0: response = str(child.process.communicate()) utilities.log_data(log_file, '%s success: %s at %s\n' % (child.get_name(), response, str(time.time()))) else: response = str(child.process.communicate()) utilities.log_data(log_file, '%s failure: %s at %s\n' % (child.get_name(), response, str(time.time()))) print(child.get_name()+response) elif child.process.poll() is None: utilities.log_data(log_file, '%s Ongoing at %s\n' % (child.get_name(), str(time.time()))) else: print('please look up what happens if subprocess.poll() does not return 1 or None') time.sleep(time_between_check) if child.process.poll() is None: print(child.get_name()+' on going: possibly too many files being launched') child.recreate_subprocess() print('round '+str(i)+' complete') utilities.log_data(log_file, 'Ended operations at %s\n' % (str(time.time()))) print('fully complete')
def run_processes(attacks, log_file): launch_storage = [] launch_order = [] time_between_launches = int((ROUND_LENGTH-SAFETY_BUFFER)/(len(attacks))) for attack, filename in attacks: launch = utilities.create_child_gen(attack) launch_storage.append(launch) launch_order.append(filename) time.sleep(time_between_launches) utilities.log_data(log_file, 'All attacks launched\n') complete = False while not complete: remove = [] curr_num = 0 time.sleep(3) complete = True for launch in launch_storage: if utilities.check_input(launch.poll(), 1): if launch.poll() == 0: response = str(launch.communicate()) if SUBMIT_AUTOMATICALLY: reply = utilities.submit_flag(SUBMIT_FLAG_IP, SUBMIT_FLAG_PORT, response[1]) utilities.log_data(log_file, 'Reply from server: ' + str(reply)+'\n') utilities.log_data(log_file, '%s success: %s\n' % (str(launch_order[curr_num]), response)) remove.append(launch) else: response = str(launch.communicate()) utilities.log_data(log_file, '%s failure: %s\n' % (str(launch_order[curr_num]), response)) print(str(launch_order[curr_num])+response) remove.append(launch) elif isinstance(launch.poll(), type(None)): response = str(launch.communicate()) utilities.log_data(log_file, '%s ongoing: %s\n' % (str(launch_order[curr_num]), response)) print(launch_order[curr_num]+' on going') complete = False curr_num = curr_num + 1 for i in remove: temp = launch_storage.index(i) launch_storage.remove(i) launch_order.pop(temp)
def problem_2(): print("\nVous avez sélectionné le problème suivant :") print("-----------------------------------") print("En prenant en compte les termes de la suite de Fibonacci dont les valeurs ne dépassent pas x, trouver la somme des termes impairs") print("===================================\n") # Return a correct input max = utilities.check_input("Veuillez entrer le nombre maximum pour les valeurs contenues dans la suite de Fibonacci : ") # Declaration of the table containing the Fibonacci suite fibonacci = [1, 1] # Fibonacci calculation while fibonacci[-1]+fibonacci[-2] < max: fibonacci.append(fibonacci[-1]+fibonacci[-2]) print("\nVoici la suite de Fibonacci pour le nombre maximum renseigné : ", fibonacci) # Sum of all the odd numbers result = sum([x for x in fibonacci if x % 2 == 1]) print("La somme des termes impairs de la suite de Fibonacci suivante est égale à :", result) print("===================================\n")
def problem_6(): print("\nVous avez sélectionné le problème suivant :") print("-----------------------------------") print("Trouver la somme des chiffres du nombre x! ?") print("===================================\n") number = utilities.check_input("Veuillez entrer le nombre à factorieliser : ") # Get pow result from the two inputs factorial_result = str(utilities.factorial(number)) # Create the variable for the sum factorial_sum = 0.0 for x in factorial_result: if x != '.': factorial_sum += int(x) print("\nLa somme des chiffres composant le nombre {}! est égale à {}".format(number, factorial_sum)) print("===================================\n") # ----------------------------------------------------------------------------------------------- # ===============================================================================================
def push(self, amount): self.set_speed(self.get_speed() + utilities.check_input(amount, float))
def set_animation(self, animation): new_animation = utilities.check_input(animation, list) for i in range(len(new_animation)): self.set_render(animation[i], i)
def __init__(self, x, y): self.x = utilities.check_input(x, int) self.y = utilities.check_input(y, int)
def add_to_vector(self, v2): v2 = utilities.check_input(v2, type(self)) self.x = self.x + v2.x self.y = self.y + v2.y
def jump(self, force): self.move((0, -1)) self.apply_force((0, -utilities.check_input(force, float)))
def rotate(self, angle): self.set_direction(self.get_direction() + utilities.check_input(angle, float))
def set_friction(self, amount): new_amount = utilities.check_input(amount, float) if new_amount > 0: self.friction = new_amount else: raise Exception(f'Friction must be greater than 0')
def set_mass(self, mass): self.mass = utilities.check_input(mass, float)
def set_colour(self, colour_): self.colour = utilities.check_input(colour_, Colour)
def set_direction(self, theta): magnitude = math.sqrt(self.velocity[0] ** 2 + self.velocity[1] ** 2) self.velocity = utilities.angle_magnitude_to_vector(magnitude, (utilities.check_input(theta, float) % 360) - 90)