text
stringlengths
37
1.41M
""" Controller ********** Description =========== Controller is used to read and process the game pad input, as well as drive the ROV autonomously. Functionality ============= Controller ---------- The :class:`Controller` class provides complex input reading and processing, connected with the :class:`DataManager`. It also handles the self-balancing and autonomous driving modes. Execution --------- To start the controller, you should create an instance of :class:`Controller` and call :func:`init`, for example:: controller = Controller() controller.init(stream) where `stream` is the video stream to be used by the autonomous driving mode. .. note:: You will be notified if the controller isn't detected. To switch in between different control modes you should call:: controller.driving_mode = mode where `mode` is a :class:`DrivingMode`. Functions & classes ------------------- .. note:: Remember that the code is further described by in-line comments and docstrings. The following list shortly summarises the functionality of each code component within the :class:`Server` class: 1. :class:`DrivingMode` enumerates acceptable driving modes 2. :func:`__init__` builds the controller, returns at the beginning if no controller is detected 3. :func:`_set_default_values` sets the controller values to the default ones 4. :func:`_dispatch_event` dispatches controller readings into class fields 5. :func:`_tick_update_data` updates the :class:`DataManager` with the current values 6. :func:`_update_data` runs an infinite loop to keep updating the :class:`DataManager` 7. :func:`_read` runs an infinite loop to keep reading the controller input and switch in between the driving modes 8. :func:`_register_thrusters` initialises thruster-related controls 9. :func:`_register_motors` initialises motor-related controls 10. :func:`_auto_drive` handles the autonomous driving 11. :func:`_auto_balance` handle the self-balancing 12. :func:`init` starts all threads Additionally, the :func:`normalise` provides the scaling of values to meet the expected range. Fields ------ The :class:`Controller` provides a number of controller fields that are accessible via the corresponding getters, as well as additional `driving_mode` and auto-driving functions to allow different driving modes. Axis (ints) +++++++++++ - left_axis_x - left_axis_y - right_axis_x - right_axis_y Triggers (ints) +++++++++++++++ - left_trigger - right_trigger * Hat (ints) * - hat_y - hat_x Buttons (booleans) ++++++++++++++++++ - button_A - button_B - button_X - button_Y - button_LB - button_RB - button_left_stick - button_right_stick - button_select - button_start On top of acquiring the information about the controller, PWM outputs are provided. Precisely: Thrusters (ints) ++++++++++++++++ - thruster_fp - thruster_fs - thruster_ap - thruster_as - thruster_tfp - thruster_tfs - thruster_tap - thruster_tas - thruster_m Motors (ints) +++++++++++++ - motor_arm - motor_gripper - motor_box Modifications ============= This module may require an extensive number of modifications to introduce any changes to it. To modify the behaviour of the controller itself, you should look into :func:`__init__` and adjust the constants inside. To change the control system, you should adjust the code within functions starting with `_register`, or add more. .. warning:: You must follow the style present in the current registering functions if you were to add a new one. You should adjust the :func:`_read` function to change how driving modes are switched, and change any functions starting with `_auto` to adjust the autonomous driving or self-balancing functionality. Default constants should be changed to adjust the default pitch and roll values of the ROV (in water) and self-balancing tolerance (the value responsible for when should the ROV attempt to auto-balance itself). Authorship ========== Kacper Florianski Modified by ----------- Pawel Czaplewski """ import communication.data_manager as dm import vision.tools as vt from threading import Thread from inputs import devices from time import time from enum import Enum # Declare the default constants for the ROV's pitch and roll DEFAULT_PITCH = -1.13 DEFAULT_ROLL = 11.25 # Declare the default self-balancing tolerance (degrees) BALANCE_TOLERANCE = 3 def normalise(value, current_min, current_max, intended_min, intended_max): """ Function used to normalise a value to fit within a given range, knowing its actual range. MinMax normalisation. :param value: Value to be normalised :param current_min: The actual minimum of the value :param current_max: The actual maximum of the value :param intended_min: The expected minimum of the value :param intended_max: The expected maximum of the value :return: Normalised value """ return int(intended_min + (value - current_min) * (intended_max - intended_min) / (current_max - current_min)) class Controller: class DrivingMode(Enum): """ Enumeration for possible driving modes. """ MANUAL = "Manual" BALANCING = "Balancing" AUTONOMOUS = "Autonomous" def __init__(self): """ Constructor function used to initialise the controller. Returns early if no controller is detected. You should modify: 1. `self._axis_max' and '_axis_min' constants to specify the expected axis values. 2. `self._trigger_max' and '_trigger_min' constants to specify the expected trigger values. 3. `self._SENSITIVITY' constant to specify how sensitive should the values setting be. 4. Hardcoded value in '_button_sensitivity' to specify the quickly should the buttons change the values. 5. `self._data_manager_map' dictionary to synchronise the controller with the data manager. 6. `self._UPDATE_DELAY' constant to specify the read delay from the controller. """ # Fetch the hardware reference via inputs try: self._controller = devices.gamepads[0] except IndexError: print("No game controllers detected.") return # Initialise the threads self._data_thread = Thread(target=self._update_data) self._controller_thread = Thread(target=self._read) # Initialise the axis hardware values self._AXIS_MAX = 32767 self._AXIS_MIN = -32768 # Initialise the axis goal values self._axis_max = 1900 self._axis_min = 1100 # Initialise the axis hardware values self._TRIGGER_MAX = 255 self._TRIGGER_MIN = 0 # Initialise the axis goal values self._trigger_max = 1900 self._trigger_min = 1500 # Initialise the axis self._left_axis_x = 0 self._left_axis_y = 0 self._right_axis_x = 0 self._right_axis_y = 0 # Initialise the triggers self._left_trigger = 0 self._right_trigger = 0 # Initialise the hat self._hat_y = 0 self._hat_x = 0 # Initialise the buttons self.button_A = False self.button_B = False self.button_X = False self.button_Y = False self.button_LB = False self.button_RB = False self.button_left_stick = False self.button_right_stick = False self.button_select = False self.button_start = False # Initialise the idle value (default PWM output) self._idle = normalise(0, self._AXIS_MIN, self._AXIS_MAX, self._axis_min, self._axis_max) # Initialise the cache delay (to slow down with writing the data) self._UPDATE_DELAY = 0.025 # Declare the sensitivity level (when to update the axis value), smaller value for higher sensitivity self._SENSITIVITY = 100 # Initialise the button sensitivity (higher value for bigger PWM values' changes) self._button_sensitivity = min(400, self._axis_max - self._idle) # Initialise the roll sensitivity self._roll_sensitivity = self._button_sensitivity # Initialise the event to attribute mapping self._dispatch_map = { "ABS_X": "left_axis_x", "ABS_Y": "left_axis_y", "ABS_RX": "right_axis_x", "ABS_RY": "right_axis_y", "ABS_Z": "left_trigger", "ABS_RZ": "right_trigger", "ABS_HAT0X": "hat_x", "ABS_HAT0Y": "hat_y", "BTN_SOUTH": "button_A", "BTN_EAST": "button_B", "BTN_WEST": "button_X", "BTN_NORTH": "button_Y", "BTN_TL": "button_LB", "BTN_TR": "button_RB", "BTN_THUMBL": "button_left_stick", "BTN_THUMBR": "button_right_stick", "BTN_START": "button_select", "BTN_SELECT": "button_start" } # Initialise the data manager key to attribute mapping self._data_manager_map = dict() # Register thrusters, motors and the light self._register_thrusters() self._register_motors() # Create a separate set of the data manager keys, for performance reasons self._data_manager_keys = set(self._data_manager_map.keys()).copy() # Create a separate dict to remember the last state of the values and avoid updating the cache unnecessarily self._data_manager_last_saved = dict() # Initialise the driving mode self._driving_mode = self.DrivingMode.MANUAL # Update the initial values self._tick_update_data() @property def driving_mode(self): """ Getter for the :class:`DrivingMode`. :return: Current driving mode """ return self._driving_mode @driving_mode.setter def driving_mode(self, value): """ Setter for the driving mode. Throws :class:`AttributeError` if the value passed is not a :class:`DrivingMode`. :param value: Driving mode to be set """ # Assign the value if it is a driving mode if isinstance(value, self.DrivingMode): # Set the default values (to turn the ROV motion off) self._set_default_values() # Set the driving mode self._driving_mode = value # If the automatic mode is being turned on if value == self.DrivingMode.AUTONOMOUS: # Fetch the yaw data and set the default yaw, pitch and roll self._default_yaw = float(dm.get_data("Sen_IMU_X")["Sen_IMU_X"]) self._default_pitch = DEFAULT_PITCH self._default_roll = DEFAULT_ROLL # If the balancing mode is being turned on elif value == self.DrivingMode.BALANCING: # Fetch the sensor values sensors = dm.get_data("Sen_IMU_X", "Sen_IMU_Y", "Sen_IMU_Z") # Set the default yaw, pitch and roll self._default_yaw = float(sensors["Sen_IMU_X"]) self._default_pitch = float(sensors["Sen_IMU_Y"]) self._default_roll = float(sensors["Sen_IMU_Z"]) # Otherwise raise an error else: raise AttributeError @property def left_axis_x(self): """ Getter for the left stick x-axis. :return: Normalised controller reading """ return normalise(self._left_axis_x, self._AXIS_MIN, self._AXIS_MAX, self._axis_min, self._axis_max) @left_axis_x.setter def left_axis_x(self, value): """ Setter for the left stick x-axis. Updates the value if the sensitivity threshold was passed. """ if value == self._AXIS_MAX or value == self._AXIS_MIN or abs(self._left_axis_x - value) >= self._SENSITIVITY: self._left_axis_x = value @property def left_axis_y(self): """ Getter for the left stick y-axis. :return: Normalised controller reading """ return normalise(self._left_axis_y, self._AXIS_MIN, self._AXIS_MAX, self._axis_min, self._axis_max) @left_axis_y.setter def left_axis_y(self, value): """ Setter for the left stick y-axis. Updates the value if the sensitivity threshold was passed. """ if value == self._AXIS_MAX or value == self._AXIS_MIN or abs(self._left_axis_y - value) >= self._SENSITIVITY: self._left_axis_y = value @property def right_axis_x(self): """ Getter for the right stick x-axis. :return: Normalised controller reading """ return normalise(self._right_axis_x, self._AXIS_MIN, self._AXIS_MAX, self._axis_min, self._axis_max) @right_axis_x.setter def right_axis_x(self, value): """ Setter for the right stick x-axis. Updates the value if the sensitivity threshold was passed. """ if value == self._AXIS_MAX or value == self._AXIS_MIN or abs(self._right_axis_x - value) >= self._SENSITIVITY: self._right_axis_x = value @property def right_axis_y(self): """ Getter for the right stick y-axis. :return: Normalised controller reading """ return normalise(self._right_axis_y, self._AXIS_MIN, self._AXIS_MAX, self._axis_min, self._axis_max) @right_axis_y.setter def right_axis_y(self, value): """ Setter for the right stick y-axis. Updates the value if the sensitivity threshold was passed. """ if value == self._AXIS_MAX or value == self._AXIS_MIN or abs(self._right_axis_y - value) >= self._SENSITIVITY: self._right_axis_y = value @property def left_trigger(self): """ Getter for the left trigger. :return: Normalised controller reading """ return normalise(self._left_trigger, self._TRIGGER_MIN, self._TRIGGER_MAX, self._trigger_min, 2 * self._trigger_min - self._trigger_max) @left_trigger.setter def left_trigger(self, value): """ Setter for the left trigger. """ self._left_trigger = value @property def right_trigger(self): """ Getter for the right trigger. :return: Normalised controller reading """ return normalise(self._right_trigger, self._TRIGGER_MIN, self._TRIGGER_MAX, self._trigger_min, self._trigger_max) @right_trigger.setter def right_trigger(self, value): """ Setter for the right trigger. """ self._right_trigger = value @property def hat_x(self): """ Getter for the hat x-axis. :return: Normalised controller reading """ return self._hat_x @hat_x.setter def hat_x(self, value): """ Setter for the hat x-axis. """ self._hat_x = value @property def hat_y(self): """ Getter for the hat y-axis. :return: Normalised controller reading """ return self._hat_y @hat_y.setter def hat_y(self, value): """ Setter for the hat y-axis. """ self._hat_y = value * (-1) def _set_default_values(self): """ Function used to set the controller to the default state. You should modify this function as required to modify the autonomous driving behaviour. """ # Turn off the buttons self.button_A = False self.button_B = False self.button_X = False self.button_Y = False self.button_LB = False self.button_RB = False self.button_left_stick = False self.button_right_stick = False self.button_select = False self.button_start = False # Set the axis to idle self.left_axis_x = 0 self.left_axis_y = 0 self.right_axis_x = 0 self.right_axis_y = 0 # Set the triggers to idle self.left_trigger = 0 self.right_trigger = 0 # Set the hat to idle self.hat_y = 0 self.hat_x = 0 # Set the roll sensitivity self._roll_sensitivity = self._button_sensitivity # Set the IMU values self._default_roll = DEFAULT_ROLL self._default_pitch = DEFAULT_PITCH self._default_yaw = 0 def _dispatch_event(self, event): """ Function used to dispatch each controller event into its corresponding value. :param event: Controller (:mod:`inputs`) event """ # Check if a registered event was passed if event.code in self._dispatch_map: # Update the corresponding value self.__setattr__(self._dispatch_map[event.code], event.state) def _tick_update_data(self): """ Function used to update the data manager with the current controller values depending on the driving mode. """ # Check if the non-manual mode is one if self.driving_mode != self.DrivingMode.MANUAL: # If autonomous mode is on if self.driving_mode == self.DrivingMode.AUTONOMOUS: # Auto-drive the ROV self._auto_drive() # If self-balancing mode is on else: # Auto-balance the ROV self._auto_balance() # Iterate over all keys that should be updated (use copy of the set to avoid runtime concurrency errors) for key in self._data_manager_keys: # Fetch the current attribute's value value = self.__getattribute__(self._data_manager_map[key]) # Check if the last saved value and the current reading mismatch if key not in self._data_manager_last_saved or self._data_manager_last_saved[key] != value: # Update the corresponding values dm.set_data(**{key: value}) self._data_manager_last_saved[key] = value def _update_data(self): """ Function used to keep updating the manager with controller values. """ # Initialise the time counter timer = time() # Keep updating the data while True: # Update the data if enough time passed if time() - timer > self._UPDATE_DELAY: self._tick_update_data() timer = time() def _read(self): """ Function used to read an event from the controller and dispatch it accordingly. Changes the driving modes on select and start buttons pressed. """ # Keep reading the input while True: # Get the current event event = self._controller.read()[0] # TODO: Unfinished # # If select button was pressed (Yes, it is labeled "Start" in the controller hardware) # if event.code == "BTN_START" and event.state: # # # If the mode wasn't autonomous # if self.driving_mode != self.DrivingMode.AUTONOMOUS: # # # Change the driving mode to autonomous # self.driving_mode = self.DrivingMode.AUTONOMOUS # # # Otherwise change the driving mode to manual # else: # self.driving_mode = self.DrivingMode.MANUAL # # # If start button was pressed (Yes, it is labeled "Select" in the controller hardware) # elif event.code == "BTN_SELECT" and event.state: # # # If the mode wasn't balancing # if self.driving_mode != self.DrivingMode.BALANCING: # # # Change the driving mode to balancing # self.driving_mode = self.DrivingMode.BALANCING # # # Otherwise change the driving mode to manual # else: # self.driving_mode = self.DrivingMode.MANUAL # Check if the manual mode is on if self.driving_mode == self.DrivingMode.MANUAL: # Distribute the event to a corresponding field self._dispatch_event(event) def _register_thrusters(self): """ Function used to associate thruster values with the controller. You should modify each sub-function to change the thrusters' controls. """ # Create custom functions to update the thrusters def _update_thruster_fp(self): # If surge and yaw if self.left_axis_y != self._idle and self.right_axis_x != self._idle: # If backwards if self.left_axis_y < self._idle: return 2 * self._idle - self.left_axis_y # Else forwards else: return 2 * self._idle - self.right_axis_x # If surge only elif self.left_axis_y != self._idle: return 2 * self._idle - self.left_axis_y # If sway only elif self.right_axis_x != self._idle: return 2 * self._idle - self.right_axis_x # If yaw starboard elif self.right_trigger != self._idle: return 2 * self._idle - self.right_trigger # If yaw pot elif self.left_trigger != self._idle: return 2 * self._idle - self.left_trigger # Else idle else: return self._idle def _update_thruster_fs(self): # If surge and yaw if self.left_axis_y != self._idle and self.right_axis_x != self._idle: # If backwards if self.left_axis_y < self._idle: return 2 * self._idle - self.left_axis_y # Else forwards else: return self.right_axis_x # If surge only elif self.left_axis_y != self._idle: return 2 * self._idle - self.left_axis_y # If sway only elif self.right_axis_x != self._idle: return self.right_axis_x # If yaw starboard elif self.right_trigger != self._idle: return self.right_trigger # If yaw pot elif self.left_trigger != self._idle: return self.left_trigger # Else idle else: return self._idle def _update_thruster_ap(self): # If surge and yaw if self.left_axis_y != self._idle and self.right_axis_x != self._idle: # If forwards if self.left_axis_y > self._idle: return self.left_axis_y # Else backwards else: return 2 * self._idle - self.right_axis_x # If surge only elif self.left_axis_y != self._idle: return self.left_axis_y # If sway only elif self.right_axis_x != self._idle: return 2 * self._idle - self.right_axis_x # If yaw starboard elif self.right_trigger != self._idle: return self.right_trigger # If yaw pot elif self.left_trigger != self._idle: return self.left_trigger # Else idle else: return self._idle def _update_thruster_as(self): # If surge and yaw if self.left_axis_y != self._idle and self.right_axis_x != self._idle: # If forwards if self.left_axis_y > self._idle: return self.left_axis_y # Else backwards else: return self.right_axis_x # If surge only elif self.left_axis_y != self._idle: return self.left_axis_y # If sway only elif self.right_axis_x != self._idle: return self.right_axis_x # If yaw starboard elif self.right_trigger != self._idle: return 2 * self._idle - self.right_trigger # If yaw pot elif self.left_trigger != self._idle: return 2 * self._idle - self.left_trigger # Else idle else: return self._idle def _update_thruster_tfp(self): # If full upwards if self.button_RB: return self._idle + self._button_sensitivity # If full downwards elif self.button_LB: return self._idle - self._button_sensitivity # If pitch elif self.right_axis_y != self._idle: return 2 * self._idle - self.right_axis_y # If roll pot elif self.button_X: return self._idle - self._roll_sensitivity # If roll starboard elif self.button_B: return self._idle + self._roll_sensitivity # Else idle else: return self._idle def _update_thruster_tfs(self): # If full upwards if self.button_RB: return self._idle + self._button_sensitivity # If full downwards elif self.button_LB: return self._idle - self._button_sensitivity # If pitch elif self.right_axis_y != self._idle: return 2 * self._idle - self.right_axis_y # If roll pot elif self.button_X: return self._idle + self._roll_sensitivity # If roll starboard elif self.button_B: return self._idle - self._roll_sensitivity # Else idle else: return self._idle def _update_thruster_tap(self): # If full upwards if self.button_RB: return self._idle + self._button_sensitivity # If full downwards elif self.button_LB: return self._idle - self._button_sensitivity # If pitch elif self.right_axis_y != self._idle: return self.right_axis_y # If roll pot elif self.button_X: return self._idle - self._roll_sensitivity # If roll starboard elif self.button_B: return self._idle + self._roll_sensitivity # Else idle else: return self._idle def _update_thruster_tas(self): # If full upwards if self.button_RB: return self._idle + self._button_sensitivity # If full downwards elif self.button_LB: return self._idle - self._button_sensitivity # If pitch elif self.right_axis_y != self._idle: return self.right_axis_y # If roll pot elif self.button_X: return self._idle + self._roll_sensitivity # If roll starboard elif self.button_B: return self._idle - self._roll_sensitivity # Else idle else: return self._idle def _update_thruster_m(self): # If surge forwards if self.button_A: return self._idle + self._button_sensitivity # If surge backwards elif self.button_Y: return self._idle - self._button_sensitivity # Else idle else: return self._idle # Register the thrusters as the properties self.__class__.thruster_fp = property(_update_thruster_fp) self.__class__.thruster_fs = property(_update_thruster_fs) self.__class__.thruster_ap = property(_update_thruster_ap) self.__class__.thruster_as = property(_update_thruster_as) self.__class__.thruster_tfp = property(_update_thruster_tfp) self.__class__.thruster_tfs = property(_update_thruster_tfs) self.__class__.thruster_tap = property(_update_thruster_tap) self.__class__.thruster_tas = property(_update_thruster_tas) self.__class__.thruster_m = property(_update_thruster_m) # Update the data manager with the new properties self._data_manager_map["Thr_FP"] = "thruster_fp" self._data_manager_map["Thr_FS"] = "thruster_fs" self._data_manager_map["Thr_AP"] = "thruster_ap" self._data_manager_map["Thr_AS"] = "thruster_as" self._data_manager_map["Thr_TFP"] = "thruster_tfp" self._data_manager_map["Thr_TFS"] = "thruster_tfs" self._data_manager_map["Thr_TAP"] = "thruster_tap" self._data_manager_map["Thr_TAS"] = "thruster_tas" self._data_manager_map["Thr_M"] = "thruster_m" def _register_motors(self): """ Function used to associate motor values with the controller. You should modify each sub-function to change the motors' controls. """ # Initialise the arm rotation sensitivity arm_rotation_speed = min(100, self._axis_max - self._idle) # Initialise the box opening sensitivity box_movement_speed = min(100, self._axis_max - self._idle) # Create custom functions to update the motors def _update_arm(self): # If starboard / pot if self.hat_x: return self._idle - self.hat_x * arm_rotation_speed # Else idle else: return self._idle def _update_gripper(self): # If upwards / downwards if self.hat_y: return self._idle - self.hat_y * self._button_sensitivity # Else idle else: return self._idle def _update_box(self): # If left box if self.button_left_stick: return self._idle - box_movement_speed # If right box elif self.button_right_stick: return self._idle + box_movement_speed # Else idle else: return self._idle # Register the thrusters as the properties self.__class__.motor_arm = property(_update_arm) self.__class__.motor_gripper = property(_update_gripper) self.__class__.motor_box = property(_update_box) # Update the data manager with the new properties self._data_manager_map["Mot_R"] = "motor_arm" self._data_manager_map["Mot_G"] = "motor_gripper" self._data_manager_map["Mot_F"] = "motor_box" # TODO: Unfinished def _auto_drive(self): """ Function used to drive the ROV autonomously and complete the dam-related task. """ # Auto-balance the ROV self._auto_balance() # Get the next frame frame = self._stream.frame # Extract the centroid information horizontal, vertical, frame = vt.find_centroids(frame, vt.Colour.RED) # If horizontal (using vertical point) adjustment is possible if vertical[0]: # Adjust the sway according to the vertical centroid self.right_axis_x = normalise(vertical[0], -frame.shape[1], frame.shape[1], self._AXIS_MIN, self._AXIS_MAX) # If vertical (using horizontal point) adjustment is possible if horizontal[1]: # Adjust the heave according to the horizontal centroid if horizontal[1] - frame.shape[0] > 0: self.button_RB = True self.button_LB = False else: self.button_LB = True self.button_RB = False print(self.button_RB, self.button_LB, self.right_axis_x) # TODO: Unfinished def _auto_balance(self): """ Function used to balance the ROV automatically. Roll, pitch and yaw are affected. """ print("Auto balance ON") # Fetch the sensor values sensors = dm.get_data("Sen_IMU_X", "Sen_IMU_Y", "Sen_IMU_Z") # Extract the roll, yaw and pitch values yaw = float(sensors["Sen_IMU_X"]) pitch = float(sensors["Sen_IMU_Y"]) roll = float(sensors["Sen_IMU_Z"]) # Check if the ROV is rolled too much if abs(self._default_roll - roll) > BALANCE_TOLERANCE: # If the ROV is rolled starboard if roll < self._default_roll: # Adjust the roll sensitivity self._roll_sensitivity = normalise(abs(roll - self._default_roll), 0, abs(-90 - self._default_roll), 0, self._button_sensitivity) # Roll pot self.button_X = True self.button_B = False # If the ROV is rolled pot else: # Adjust the roll sensitivity self._roll_sensitivity = normalise(abs(self._default_roll - roll), 0, abs(self._default_roll - 90), 0, self._button_sensitivity) # Roll starboard self.button_B = True self.button_X = False # Check if the ROV is pitched too much if abs(self._default_pitch - pitch) > BALANCE_TOLERANCE: # Adjust the pitch self.right_axis_y = normalise(pitch, self._default_pitch - 90, self._default_pitch + 90, self._AXIS_MIN, self._AXIS_MAX) # Calculate the yaw difference yaw_difference = self._default_yaw - yaw # Check if the ROV is yawed too much if abs(yaw_difference) > BALANCE_TOLERANCE: # If it's easier to yaw the ROV starboard if 0 >= yaw_difference <= 180: # Yaw right self.left_trigger = normalise(yaw_difference, 0, 180, self._TRIGGER_MIN, self._TRIGGER_MAX) self.right_trigger = self._TRIGGER_MIN # If it's easier to yaw the ROV pot else: # Yaw left self.right_trigger = normalise(abs(yaw_difference), 0, 180, self._TRIGGER_MIN, self._TRIGGER_MAX) self.left_trigger = self._TRIGGER_MIN def init(self): """ Function used to start the controller reading threads. Only executes if the controller is correctly detected. """ # Check if the controller was correctly created if not hasattr(self, "_controller"): print("Controller initialisation error detected.") # If controller initialised correctly else: # Start the threads (to not block the main execution) with event dispatching and data updating self._data_thread.start() self._controller_thread.start() print("Controller initialised.") if __name__ == "__main__": controller = Controller() controller.init()
"""Дано целое число, не меньшее 2. Выведите его наименьший натуральный делитель, отличный от 1. Формат ввода Вводится целое положительное число. Формат вывода Выведите ответ на задачу.""" n = int(input()) i = 2 while (n % i) != 0: i += 1 print(str(i))
x = int(input()) y = int(input()) if ((y % (y - x + 1)) == 0) and (((x - 1) % (y - x + 1)) == 0): print('YES') else: print('NO')
x1 = int(input()) y1 = int(input()) x2 = int(input()) y2 = int(input()) if (x1 == x2) and ((y1 - y2 == 1) or (y1 - y2 == -1)): print('YES') elif (y1 == y2) and ((x1 - x2 == 1) or (x1 - x2 == -1)): print('YES') elif (x1 == x2 - 1) and ((y1 - y2 == 1) or (y1 - y2 == -1)): print('YES') elif (x1 == x2 + 1) and ((y1 - y2 == 1) or (y1 - y2 == -1)): print('YES') elif (y1 == y2 - 1) and ((x1 - x2 == 1) or (x1 - x2 == -1)): print('YES') elif (y1 == y2 + 1) and ((x1 - x2 == 1) or (x1 - x2 == -1)): print('YES') else: print('NO')
"""Дана последовательность натуральных чисел, завершающаяся числом 0. Определите, какое наибольшее число подряд идущих элементов этой последовательности равны друг другу. Формат ввода Вводится последовательность целых чисел, оканчивающаяся числом 0 (само число 0 в последовательность не входит, а служит как признак ее окончания). Формат вывода Выведите ответ на задачу.""" now = int(input()) max = 1 count = 1 i = now while now != 0: i = now now = int(input()) if now == i: count += 1 elif count > max: max = count count = 1 else: count = 1 print(max)
ch="a" def vowel_find(ch): ch=ch.lower() if(ch=="a" or ch=="e" or ch=="i" or ch=="o" or ch=="u"): return "True" else: return "False" print(vowel_find(ch))
def find_longest_word(a): longest=0 for i,val in enumerate(a): if(len(val)>longest): longest=len(val) return longest a=["finding","the","length","of","longest","word","in","this","sentence"] print(find_longest_word(a))
########################## ##Exercicio 1: Contar o número de palavras no arquivo. ################################### import fileinput contador = 0 for s in fileinput.input("aux/Palavras.txt"): contador = contador + 1 print "Existem", contador, "palavras no arquivo Palavras.txt\n" ########################## ##Exercicio 2: Maior(es) Palavra(s) ################################### import fileinput maiorp = '' # 'Maior palavra' maioresp = '' # 'Maiores palavras' for i in fileinput.input('aux/Palavras.txt'): # Loop para encontrar a maior palavra if len(str(i)[0:-1]) > len(maiorp): maiorp = str(i)[0:-1] # NOTA: pequeno corte na string i pois esta possui o charactere # especial para quebra de linha "\n" em str(i)[-1] for j in fileinput.input('Palavras.txt'): # Loop para verificar se a maior palavra é unica if len(str(j)[0:-1]) == len(maiorp): # Caso não seja unica, criar uma string concatenando maioresp = maiorp + ', ' + str(j)[0:-1] # todas as palavras com o mesmo tamanho dela print "As maiores palavras são: " + maioresp + "\n" ## dois for loops no arquivo é desnecessário ## depois concerto o programa. ########################## ##Exercicio 3: Todos os Palindromos do arquivo ################################### import fileinput palavras = [] palindromes = [] for i in fileinput.input("Palavras.txt"): palavras.append(str(i)[:-1]) for x in range(len(palavras)): if str(palavras[x]) == str(palavras[x])[::-1]: # Checa se a string é igual ao seu inverso palindromes.append(palavras[x]) print 'As "palavras" palíndromes são:', palindromes, "\n" # No programa acima, considero possiveis palindromos todas as palavras(linhas) # contidas no arquivo, inclusive "palavras" de uma só letra, por exemplo. # Para uma resposta contendo apenas palavras de 3 digitos ou mais, # a condicional if deveria ser modificada para #if (str(palavras[x]) == str(palavras[x])[::-1]) and (len(str(palavras[x])) > 2): ########################## ##Exercicio 4: Mostrar palavras com padrão S**V***R** ################################### import fileinput palavras = [] resposta = [] for i in fileinput.input("Palavras.txt"): palavras.append(str(i)[:-1]) for j in range(len(palavras)): if len(palavras[j]) == 10 and str(palavras[j])[0] == 'S' and str(palavras[j])[3] == 'V' and str(palavras[j])[7] == 'R': resposta.append(palavras[j]) print "A(s) palavra(s) que corresponde(m) ao padrão S**V***R** é/são:", resposta, "\n" ########################## ##Desafio: Mostrar palavras com padrões escolhidos pelo usuário ################################### import fileinput import string import re palavras = [] temp = [] resposta = [] for i in fileinput.input("Palavras.txt"): palavras.append(str(i)[0:-1]) print "Bem vindo ao buscador de palavras.\nEle funciona com padrões analogos a S**V***R**, onde * é uma letra qualquer.\nUma busca por A*** retornaria palavras começando com A seguido de 3 letras quaisqer" padrao = raw_input('Digite o padrão que deseja buscar:') padrao2 = padrao.replace("*", ".") # Pequeno ajuste já que o charactere coringa para expressões # regulares no Python é "." e não "*". for j in range(len(palavras)): if len(padrao) == len(palavras[j]): temp.append(palavras[j]) padrao2 = re.compile(padrao2, re.IGNORECASE) # transformando o padrão de expressão regular em um # objeto que não faz distinção entre caixa baixa e alta. resposta = filter(padrao2.match, temp) # filtra temp (iteravel) com a função (método) .match, da lib re # .match retorna true se o padrão 'casar' com o objeto sendo iterado # e filter remove todos os resultados em que a condição (padrao2.match) # é falsa (i.e qnd .match returna False), para objetos na lista 'temp' if resposta == []: print "Nenhum resultado encontrado." else: print "As palavras que satisfazem o padrão", padrao, "são:", resposta, "\n"
amount=int(input("enter the salary ")) totalsal=amount*12 tax=0 if totalsal<250000: print("no Tax") elif totalsal<500000: tax=0.05*totalsal print("tax to be paid:Rs.",tax) elif totalsal<1000000: tax=0.2*totalsal print("tax to be paid:Rs.",tax) else: tax=0.3*totalsal print("tax to be paid:Rs.",tax)
""" 1. Сгенерировать список случайной длины заполнив его случайными числами (используйте random, диапазон чисел произвольный) 2. Вывести на экран числа из списка в обратном порядке через пробел 3. Извлечь первое число, возвести его в квадрат и вставить в средину списка 4. Удалить из списка простые числа. 5. Записать в файл list_info.txt строчки: - 1. элементы списка через запятую - 2. количество элементов списка - 3. самое маленькое число списка - 4. сумму чисел списка кратных 3 """ import random from pathlib import Path BASE_DIR = Path(__file__).resolve().parent def main(): list_ = generate_list() print("surce_list:", list_) print("reverse list: ", end="") reverse_list_print(list_) print("\nFirst in center list:", end="") print(first_in_center(list_)) print("removed simple list", remove_simple(list_)) file_path = BASE_DIR / "list_info.txt" with open(file_path, "a") as f: print("coma separated list:", coma_separated_list(list_), file=f) print("length:", len(list_), file=f) print("minimal:", min(list_), file=f) print("sum 3:", get_sum_3(list_), file=f) def generate_list() -> list: new_list = list() for i in range(random.randint(1, 20)): new_list.append(random.randint(1, 100)) return new_list def reverse_list_print(list_: list) -> list: new_list = list_[::-1] for i in new_list: print(i, end=" ") def first_in_center(list_: list) -> list: list_.insert(len(list_) // 2, int(list_[0]) ** 2) return list_ def is_simple(i: int) -> bool: for _ in range(2, i): if i % _ == 0: return False return True def remove_simple(list_: list) -> list: new_list = list() for i in list_: if not is_simple(i): new_list.append(i) return new_list def coma_separated_list(list_: list) -> str: string_ = '' for i in list_: string_ = string_ + str(i) + ',' return string_[:-1] def get_sum_3(list_: list) -> int: sum = 0 for i in list_: if i % 3 == 0: sum += i return sum if __name__ == "__main__": main()
""" Программу принимает на ввод строку string и число n. Выводит на экран строку с смещенными символами на число n. Весь код можно написать в одной функции main, но рекомендуется разбить код на несколько функций, например: - main - функция для получения не пустой строки. - функция для получения сдвига (целое число). - функция, которая делает сдвиг строки. Пример: Введите строку: python hello world Введите сдвиг: 5 Результат: n hello worldpytho Введите строку: python hello world Введите сдвиг: -2 Результат: ldpython hello wor * используйте индексы, срезы и возможно циклы """ def main(): print(shift(input_string(), input_shift())) def shift(string_, shift): return string_[shift:] + string_[:shift] def input_shift(): shift = input("Enter shift ") try: return int(shift) except ValueError: return input_shift() def input_string(): string_ = input("Enter not empty string: ") if len(string_) > 0: return string_ else: return input_string() if __name__ == "__main__": main()
print "x", for a in range(1,13): print a, print "" for i in range(0,13): if i > 0: print i, i*1, i*2, i*3, i*4, i*5, i*6, i*7, i*8, i*9, i*10, i*11, i*12
class Bike(object): # init function to set attributes of Bike object # include Bike name to differentiate various instances # all Bikes will start at 0 miles def __init__(self, name, price, max_speed): self.name = name self.price = price self.max_speed = max_speed self.miles = 0 # create and print strings for each attribute def displayInfo(self): print "Bike: " + self.name print "Price: $" + str(self.price) print "Max Speed: "+ str(self.max_speed) + "mph" print "Miles Ridden: " + str(self.miles) # add 10 miles on each ride() call, print "Riding..." to show user this is working def ride(self): print "Riding..." self.miles += 10 return self # subtract 5 miles, but only if there are at least 5 miles already accrued # this prevents creating a negative value for miles def reverse(self): if self.miles >= 5: print "Reversing..." self.miles -= 5 return self else: print "Cannot reverse any farther!" return self # instantiate three objects, passing in data for each bike1 = Bike("Specialized Allez", 1200, 25) bike2 = Bike("Cannondale CAAD12", 2000, 30) bike3 = Bike("Pinarello Dogma F10", 10000, 45) # add a new line at the end of each method chain to reduce visual clutter print bike1.ride().ride().ride().reverse().displayInfo(), "\n" print bike2.ride().ride().reverse().reverse().displayInfo(), "\n" print bike3.reverse().reverse().reverse().displayInfo(), "\n"
""" The current code given is for the Assignment 1. You will be expected to use this to make trees for: > discrete input, discrete output > real input, real output > real input, discrete output > discrete input, real output """ import numpy as np import pandas as pd import matplotlib.pyplot as plt from .utils import entropy, information_gain, gini_index np.random.seed(42) # creating class for a tree node class TreeNode(): def __init__(self): self.isLeaf = False self.isAttrCategory = False self.attr_id = None self.children = dict() self.splitValue = None self.value = None class DecisionTree(): def __init__(self, criterion, max_depth=None): self.criterion = criterion self.max_depth = max_depth self.head = None def fit_data(self,X,y,currdepth): currnode = TreeNode() # Creating a new Tree Node attr_id = -1 split_value = None best_measure = None # Classification Problems if(y.dtype.name=="category"): classes = np.unique(y) if(classes.size==1): currnode.isLeaf = True currnode.isAttrCategory = True currnode.value = classes[0] return currnode if(self.max_depth!=None): if(self.max_depth==currdepth): currnode.isLeaf = True currnode.isAttrCategory = True currnode.value = y.value_counts().idxmax() return currnode if(X.shape[1]==0): currnode.isLeaf = True currnode.isAttrCategory = True currnode.value = y.value_counts().idxmax() return currnode for i in X: xcol = X[i] # Discreate Input and Discreate Output if(xcol.dtype.name=="category"): measure = None if(self.criterion=="information_gain"): # Criteria is Information Gain measure = information_gain(y,xcol) else: # Criteria is Gini Index classes1 = np.unique(xcol) s = 0 for j in classes1: y_sub = pd.Series([y[k] for k in range(y.size) if xcol[k]==j]) s += y_sub.size*gini_index(y_sub) measure = -1*(s/xcol.size) if(best_measure!=None): if(best_measure<measure): attr_id = i best_measure = measure split_value = None else: attr_id = i best_measure = measure split_value = None # Real Input and Discreate Output else: xcol_sorted = xcol.sort_values() for j in range(xcol_sorted.size-1): index = xcol_sorted.index[j] next_index = xcol_sorted.index[j+1] if(y[index]!=y[next_index]): measure = None splitValue = (xcol[index]+xcol[next_index])/2 if(self.criterion=="information_gain"): # Criteria is Information Gain helper_attr = pd.Series(xcol<=splitValue) measure = information_gain(y,helper_attr) else: # Criteria is Gini Index y_sub1 = pd.Series([y[k] for k in range(y.size) if xcol[k]<=splitValue]) y_sub2 = pd.Series([y[k] for k in range(y.size) if xcol[k]>splitValue]) measure = y_sub1.size*gini_index(y_sub1) + y_sub2.size*gini_index(y_sub2) measure = -1*(measure/y.size) if(best_measure!=None): if(best_measure<measure): attr_id = i best_measure = measure split_value = splitValue else: attr_id = i best_measure = measure split_value = splitValue # Regression Problems else: if(self.max_depth!=None): if(self.max_depth==currdepth): currnode.isLeaf = True currnode.value = y.mean() return currnode if(y.size==1): currnode.isLeaf = True currnode.value = y[0] return currnode if(X.shape[1]==0): currnode.isLeaf = True currnode.value = y.mean() return currnode for i in X: xcol = X[i] # Discreate Input Real Output if(xcol.dtype.name=="category"): classes1 = np.unique(xcol) measure = 0 for j in classes1: y_sub = pd.Series([y[k] for k in range(y.size) if xcol[k]==j]) measure += y_sub.size*np.var(y_sub) if(best_measure!=None): if(best_measure>measure): best_measure = measure attr_id = i split_value = None else: best_measure = measure attr_id = i split_value = None # Real Input Real Output else: xcol_sorted = xcol.sort_values() for j in range(y.size-1): index = xcol_sorted.index[j] next_index = xcol_sorted.index[j+1] splitValue = (xcol[index]+xcol[next_index])/2 y_sub1 = pd.Series([y[k] for k in range(y.size) if xcol[k]<=splitValue]) y_sub2 = pd.Series([y[k] for k in range(y.size) if xcol[k]>splitValue]) measure = y_sub1.size*np.var(y_sub1) + y_sub2.size*np.var(y_sub2) # c1 = y_sub1.mean() # c2 = y_sub2.mean() # measure = np.mean(np.square(y_sub1-c1) + np.square(y_sub2-c2)) if(best_measure!=None): if(best_measure>measure): attr_id = i best_measure = measure split_value = splitValue else: attr_id = i best_measure = measure split_value = splitValue # when current treenode is category based if(split_value==None): currnode.isAttrCategory = True currnode.attr_id = attr_id classes = np.unique(X[attr_id]) for j in classes: y_new = pd.Series([y[k] for k in range(y.size) if X[attr_id][k]==j], dtype=y.dtype) X_new = X[X[attr_id]==j].reset_index().drop(['index',attr_id],axis=1) currnode.children[j] = self.fit_data(X_new, y_new, currdepth+1) # when current treenode is split based else: currnode.attr_id = attr_id currnode.splitValue = split_value y_new1 = pd.Series([y[k] for k in range(y.size) if X[attr_id][k]<=split_value], dtype=y.dtype) X_new1 = X[X[attr_id]<=split_value].reset_index().drop(['index'],axis=1) y_new2 = pd.Series([y[k] for k in range(y.size) if X[attr_id][k]>split_value], dtype=y.dtype) X_new2 = X[X[attr_id]>split_value].reset_index().drop(['index'],axis=1) currnode.children["lessThan"] = self.fit_data(X_new1, y_new1, currdepth+1) currnode.children["greaterThan"] = self.fit_data(X_new2, y_new2, currdepth+1) return currnode def fit(self, X, y): assert(y.size>0) assert(X.shape[0]==y.size) self.head = self.fit_data(X,y,0) def predict(self, X): y_hat = list() # List to contain the predicted values for i in range(X.shape[0]): xrow = X.iloc[i,:] # Get an instance of the data for prediction purpose h = self.head while(not h.isLeaf): # when treenode is not a leaf if(h.isAttrCategory): # when treenode is category based h = h.children[xrow[h.attr_id]] else: # when treenode is split based if(xrow[h.attr_id]<=h.splitValue): h = h.children["lessThan"] else: h = h.children["greaterThan"] y_hat.append(h.value) #when treenode is a leaf y_hat = pd.Series(y_hat) return y_hat def plotTree(self, root, depth): if(root.isLeaf): if(root.isAttrCategory): return "Class "+str(root.value) else: return "Value "+str(root.value) s = "" if(root.isAttrCategory): for i in root.children.keys(): s += "?("+str(root.attr_id)+" == "+str(i)+")\n" s += "\t"*(depth+1) s += str(self.plotTree(root.children[i], depth+1)).rstrip("\n") + "\n" s += "\t"*(depth) s = s.rstrip("\t") else: s += "?("+str(root.attr_id)+" <= "+str(root.splitValue)+")\n" s += "\t"*(depth+1) s += "Y: " + str(self.plotTree(root.children["lessThan"], depth+1)).rstrip("\n") + "\n" s += "\t"*(depth+1) s += "N: " + str(self.plotTree(root.children["greaterThan"], depth+1)).rstrip("\n") + "\n" return s def plot(self): h = self.head s = self.plotTree(h,0) print(s)
from bs4 import BeautifulSoup as bs from splinter import Browser import pandas as pd from time import sleep import requests def init_browser(): # @NOTE: Replace the path with your actual path to the chromedriver executable_path = {"executable_path": "chromedriver"} return Browser("chrome", **executable_path, headless=False) def scrape(): browser = init_browser() mars_info = {} # Visit visitcostarica.herokuapp.com url = "https://mars.nasa.gov/news/" browser.visit(url) time.sleep(1) # Design an XPATH selector to grab the "Mars in natural color in 2007" image on the right xpath = '//td//a[@class="image"]/img' # Use splinter to Click the "Mars in natural color in 2007" image # to bring up the full resolution image results = browser.find_by_xpath(xpath) img = results[0] img.click() # Scrape page into Soup html = browser.html soup = bs(html, "html.parser") # Find the src for the mrs image img_url = soup.find("img")["src"] img_url = "https://www.jpl.nasa.gov/"+img_url featured_image_url = img_url # relative_image_path = soup.find_all('img')[2]["src"] # img_url = url + relative_image_path # featured_image_url = img_url # Collect the latest News Title and Paragraph Text news_title=soup.find('div',class_='content_title').get_text() # print (news_title) # news_title=soup.find_all('div',{"class":"content_title"}) # print (news_title) # Collect the latest News Paragraph Text news_p=soup.find('div',class_='article_teaser_body').get_text() # Get the max avg temp # max_temp = avg_temps.find_all('strong')[1].text # Variables to store data in a dictionary mars_data = { "news_title" : news_title, "news_p" : news_p, # "mars_weather" : mars_weather } # Close the browser after scraping browser.quit() # Return results return mars_info #######################################################
dia = int(input('Por quantos dias você ficou com o carro: ')) km = float (input('Qual a kilometragem percorrida com o carro ? ')) aluguel = dia 60 kilometragem = km 0.15 print('O total a pagar é de R$ {:.2f} ' .format(aluguel+kilometragem))
# # @lc app=leetcode.cn id=818 lang=python3 # # [818] 赛车 # # @lc code=start class Solution: # https://leetcode.com/problems/race-car/discuss/124326/Summary-of-the-BFS-and-DP-solutions-with-intuitive-explanation # 这个把题目读明白已经是很有挑战的事 # 注意位运算符运算优先级低于加减号 # 状态定义 dp(i) 为走到位置i,需要的最少指令数 # 分为三种情况 # 1.先走了a0个A,R(-1),又回头走了b0个A,R(1) --> dp[i] = min(dp[i], a0+1+b0+1+dp[i-(a1-b1)]) # 2.刚好a0个A与i相等 --> a0 # 3.a0个A走的距离大于i,R(-1),往回走b0个A --> dp[i] = min(dp[i], a0 + (0 if a1 == i else 1 + dp[a1-i])) # 最后再思考下base case的情况a0、a1、b0、b1 # 时间复杂度O(n * (log(n))^2) 900ms def racecar(self, target: int) -> int: dp = [float('inf')] * (target+1) dp[0] = 0 for i in range(1, target+1): a0, a1 = 1, 1 while a1 < i: b0, b1 = 0, 0 while b1 < a1: dp[i] = min(dp[i], a0+1+b0+1+dp[i-(a1-b1)]) b0 += 1 b1 = (1 << b0) - 1 a0 += 1 a1 = (1 << a0) - 1 dp[i] = min(dp[i], a0 + (0 if a1 == i else 1 + dp[a1-i])) # print(dp) return dp[-1] # 这个也太快了吧(52ms) # 应该需要什么数学方法来证明,为什么else那里的分支就是这样的状态 def racecar_dp(self, target: int) -> int: def race(t): if t not in dp: n = t.bit_length() if (1 << n) - 1 == t: # 如果刚好是全A指令就能到达的,如1/3/7 dp[t] = n else: # (形如AAARAA+dp[])先n次A到达2^n-1后再R,已操作n+1次,然后转换为从2^n-1到t的正向问题的指令次数 dp[t] = n+1+race((1 << n)-1-t) for m in range(n-1): # 2^m < 2^(n-1) # (形如AAARAAR+dp[])先n-1次A到达2^(n-1)-1后再R,然后m次A往回走,再R变为正向,已指令n-1+2+m次, # 接着转换为剩余差值即t-(2^(n-1)-1)+(2^m-1)的正向问题即可 dp[t] = min(dp[t], n + m + 1 + race(t - (1 << n - 1) + (1 << m))) return dp[t] dp = {0: 0} return race(target) # @lc code=end if __name__ == "__main__": res = Solution().racecar(1024) print(res)
#解法1 并查集 加了parent 数组和rank秩,路径压缩 class UnionFind: def __init__(self,n): self.count = n self.parent = [i for i in range(n)] self.rank = [1 for i in range(n)] def get_count(self): return self.count def find(self,p): while p != self.parent[p]: self.parent[p] = self.parent[self.parent[p]] p = self.parent[p] return p def is_connected(self,p,q): return self.find(p) == self.find(q) def union(self,p,q): p_root = self.find(p) q_root = self.find(q) print("p_root = j", p_root) print('q_root = i',q_root) if p_root == q_root: return if self.rank[p_root] > self.rank[q_root]: self.parent[q_root] = p_root elif self.rank[p_root] < self.rank[q_root]: self.parent[p_root] = q_root else: self.parent[q_root] = p_root self.rank[p_root] += 1 print("parent",self.parent) print("rank",self.rank) self.count -= 1 print("count",self.count) def findCircleNum(M): """ :type M: List[List[int]] :rtype: int """ m = len(M) print("m",m) union_find_set = UnionFind(m) for i in range(m): for j in range(i): if M[i][j] == 1: union_find_set.union(j,i) return union_find_set.get_count() #解法2 BFS class Solution(object): def findCircleNum(self, M): """ :type M: List[List[int]] :rtype: int """ circlenum = 0 checkedFlg = [0] * len(M) queue =[] while (0 in checkedFlg): circlenum += 1 newperson = checkedFlg.index(0) queue.append(newperson) checkedFlg[newperson] = 1 while queue: cur = queue.pop() for i,v in enumerate(M[cur]): if v == 1 and checkedFlg[i] == 0: queue.append(i) checkedFlg[i] = 1 return circlenum #解法3 DFS 染色法 class Solution(object): white = 1 grey = 2 black = 3 def findCircleNum(self, M): """ :type M: List[List[int]] :rtype: int """ self.M = M n = len(M) self.colorMap = [self.white] * n group = 0 for i in range(n): if self.colorMap[i] == self.white: group += 1 self.dfs(i) return group def dfs(self,i): self.colorMap[i] = self.grey for f,v in enumerate(self.M[i]): if v == 1 and self.colorMap[f] == self.white: self.dfs(f) self.colorMap[i] = self.black
def remove_duplicates(nums): """ :type nums: List[int] :rtype: int """ i = 0 for j in range(1, len(nums)): if nums[i] != nums[j]: nums[i+1] = nums[j] i += 1 return i+1 if __name__ == '__main__': print(remove_duplicates([1, 1, 2]))
class Solution(object): def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ # sort O(nlogn) # if len(s) != len(t): # return False # if sorted(s) != sorted(t): # return False # return True # map O(n) if len(s) != len(t): return False d = {} for i in s: d[i] = d.get(i, 0) + 1 for i in t: d[i] = d.get(i, 0) - 1 if d.get(i) < 0: return False return True if __name__ == "__main__": solu = Solution() print(solu.isAnagram('anagram', 'nagaram'))
# -*- coding: utf-8 -*- """https://leetcode-cn.com/problems/counting-bits/""" from typing import List class Solution: def countBits(self, num: int) -> List[int]: res = [0] for i in range(1, num + 1): if i%2 == 0: # i 为偶数, 二进制中1的个数为其1/2数二进制中的1个数 # 位运算<<,表示将当前数乘以2,即在二进制的最右侧加个0 res.append(res[i//2]) else: # i 为奇数,二进制中1的个数为前一个偶数中的1个数加1 res.append(res[i-1] + 1) return res
#假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。对每个孩子 i ,都有一个胃口值 gi ,这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j ,都有一个尺寸 sj 。如果 sj >= gi ,我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。 # # 注意: # # 你可以假设胃口值为正。 #一个小朋友最多只能拥有一块饼干。 # # 示例 1: # # #输入: [1,2,3], [1,1] # #输出: 1 # #解释: #你有三个孩子和两块小饼干,3个孩子的胃口值分别是:1,2,3。 #虽然你有两块小饼干,由于他们的尺寸都是1,你只能让胃口值是1的孩子满足。 #所以你应该输出1。 # # # 示例 2: # # #输入: [1,2], [1,2,3] # #输出: 2 # #解释: #你有两个孩子和三块小饼干,2个孩子的胃口值分别是1,2。 #你拥有的饼干数量和尺寸都足以让所有孩子满足。 #所以你应该输出2. # # Related Topics 贪心算法 from typing import List #leetcode submit region begin(Prohibit modification and deletion) class Solution: def findContentChildren(self, g: List[int], s: List[int]) -> int: # 先满足需求最小的孩子的 g,s = sorted(g),sorted(s) p = 0 i = j = 0 while i < len(g) and j < len(s): # 如果饼干不满足往下找 if g[i] <= s[j]: i += 1 j += 1 return i #leetcode submit region end(Prohibit modification and deletion)
import collections from typing import List class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: hashMap = collections.defaultdict(list) for str in strs: count = [0] * 26 for char in str: count[ord(char) - ord('a')] += 1 hashMap[tuple(count)].append(str) return hashMap.values()
class Solution: def reverseWords(self, s: str) -> str: if not s: return '' strList = s.split(' ') result = '' for word in strList: temp = '' for i in range(len(word)): temp += word[len(word) - i - 1] result += ' ' + temp return result.strip() if __name__ == "__main__": solution = Solution() print(solution.reverseWords("Let's take LeetCode contest"))
#假设按照升序排序的数组在预先未知的某个点上进行了旋转。 # # ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。 # # 搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。 # # 你可以假设数组中不存在重复的元素。 # # 你的算法时间复杂度必须是 O(log n) 级别。 # # 示例 1: # # 输入: nums = [4,5,6,7,0,1,2], target = 0 #输出: 4 # # # 示例 2: # # 输入: nums = [4,5,6,7,0,1,2], target = 3 #输出: -1 # Related Topics 数组 二分查找 from typing import List #leetcode submit region begin(Prohibit modification and deletion) class Solution: def search(self, nums: List[int], target: int) -> int: # 先找到旋转的点 if not nums: return -1 point, rotate = nums[0], -1 for i in range(1, len(nums)): if nums[i] < point: rotate = i break if rotate == -1: return self.binary_search(nums, target) # 分别在左或者右边进行二分查找 if target == nums[rotate]: return rotate if target <= nums[-1]: p = self.binary_search(nums[rotate + 1:], target) return p + 1 + rotate if p != -1 else -1 else: return self.binary_search(nums[:rotate], target) def binary_search(self, arr, target): left, right = 0, len(arr) - 1 while left <= right: mid = left + (right - left) // 2 if target == arr[mid]: return mid if target > arr[mid]: left = mid + 1 else: right = mid - 1 return -1 #leetcode submit region end(Prohibit modification and deletion) print(Solution().search([1, 3], 2)) print(Solution().search([1, 3], 1)) print(Solution().search([1, 3], 3)) print(Solution().search([7, 8, 9, 0, 1, 2, 3, 4, 5,6], 4))
#解法1数学法 class Solution(object): def trap(self, height): """ :type height: List[int] :rtype: int """ #数学:平铺面积算法: 以最高高度的墙高 为高度,高 h = max(height),宽 w = len(height),面积 s = h * w #从左到右遍历 找左边最高的墙,从右到做遍历,找右边最高的墙,算面积1, 面积1多算了最高高度的面积,所以减掉最高高度的面积, s1 = s1 - h * w #剩下的面积就是墙的面积和水的面积,减去抢的面积就是水的面积,遍历 s -= h[i] if not height or len(height) < 3: return 0 area, left_max, right_max = 0, 0, 0 for i in range(len(height)): left_max = max(left_max,height[i]) #更新左边最高的墙 right_max = max(right_max,height[-i-1]) #更新右边最高的墙 从右到左,顺序倒过来 area += left_max + right_max -height[i] #宽是1,需要乘1,乘1后,对原式不变,area = 平铺面积-墙的面积 return area - len(height) * left_max #遍历完后,left_max = right_max,选择其一就行,area 再减去多变的最高高度的面积 area = area - h * w 高 h = max(height),宽 w = len(height) #解法2 栈 class Solution(object): def trap(self, height): """ :type height: List[int] :rtype: int """ #栈 if not height or len(height) < 3: return 0 volume,current, n, stack = 0, 0, len(height), [] #初始化,分别是存水量,当前指针,数组长度,栈 while current < n: while stack and height[current] > height[stack[-1]]: #栈不为空,且当前值大于栈顶的值,计算存水量 h = height[stack[-1]] #h 为栈顶元素,当前值的第前一个或是第前几个值 stack.pop() #出栈,栈顶元素出栈 if not stack: #出栈后栈空了,无操作,直接让当前元素入栈 break else: left_index = stack[-1] distance = current - left_index -1 #两个索引号的距离,如 3-1-1 min1 = min(height[left_index],height[current]) #取较矮的墙 volume += distance * (min1-h) #存水量 = 两者距离 * (较矮的墙高-原栈顶的高) stack.append(current) current += 1 return volume #解法3 动态规划 class Solution(object): def trap(self, height): """ :type height: List[int] :rtype: int """ #动态规划 if not height or len(height) < 3: return 0 n = len(height) left = [0 for i in range(n)] #存左边最大值 right = [0 for i in range(n)] #存右边最大值 left[0],right[-1] = height[0], height[-1] #初始化,很重要,遍历是从左边的第一个,和右边的倒数第二个开始的,所以左边第0个和右边的倒数一个 都是初始的0值 for i in range(1,n): #默认 左边值从第一个开始计算 left[i] = max(left[i-1],height[i]) #存更新后 左边最大值 for i in range(n-2,-1,-1): #默认 左边值从倒数第二个开始计算,递减 right[i] = max(right[i+1],height[i]) #存更新后 右边最大值 volume = 0 for i in range(n): colleted_water= min(left[i],right[i]) - height[i] #取左右两边最矮的墙,减去当前墙高,就是能存的水量 volume += colleted_water return volume #解法4 双指针 class Solution(object): def trap(self, height): """ :type height: List[int] :rtype: int """ if not height or len(height) < 3: return 0 left,right = 0,len(height) -1, #设置左指针和右指针 l_max,r_max = height[left], height[right] #记录左右两边最高的 高度 volume = 0 #存水 while left < right: l_max, r_max = max(l_max, height[left]),max(r_max,height[right]) if l_max <= r_max: volume += l_max - height[left] left += 1 else: volume += r_max - height[right] right -= 1 return volume
# # @lc app=leetcode.cn id=94 lang=python3 # # [94] 二叉树的中序遍历 # # https://leetcode-cn.com/problems/binary-tree-inorder-traversal/description/ # # algorithms # Medium (69.12%) # Likes: 340 # Dislikes: 0 # Total Accepted: 84.3K # Total Submissions: 121.8K # Testcase Example: '[1,null,2,3]' # # 给定一个二叉树,返回它的中序 遍历。 # # 示例: # # 输入: [1,null,2,3] # ⁠ 1 # ⁠ \ # ⁠ 2 # ⁠ / # ⁠ 3 # # 输出: [1,3,2] # # 进阶: 递归算法很简单,你可以通过迭代算法完成吗? # # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: # 1.递归 # res = [] # if root: # res.extend(self.inorderTraversal(root.left)) # res.append(root.val) # res.extend(self.inorderTraversal(root.right)) # return res # 2.基于栈的遍历 # TODO: # 将最左节点加入栈中,然后依次弹出检查其右节点 res = [] stack = [] cur = root while cur or stack: while cur: stack.append(cur) # 每个节点,首先访问其最左边的叶子节点 cur = cur.left # 将叶子节点置于栈顶 cur = stack.pop() res.append(cur.val) # 访问根节点 cur = cur.right # 当前右子树 return res # 3.树节点带状态 # TODO: # PENDING, DONE = 0,1 # res = [] # stack = [(PENDING, root)] # while stack: # state, node = stack.pop() # if not node: # continue # if state == PENDING: # stack.append((PENDING, node.right)) # stack.append((DONE, node)) # stack.append((PENDING, node.left)) # else: # res.append(node.val) # return res # @lc code=end
# 322. Coin Change class Solution(object): def coinChange(self, coins, amount): """ :type coins: List[int] :type amount: int :rtype: int """ memo = {0: 0} def helper(n): if n in memo: return memo[n] res = float("inf") for coin in coins: if n >= coin: res = min(res, helper(n-coin) + 1) memo[n] = res return res return helper(amount) if (helper(amount) != float("inf")) else -1
#解法1:字典树 + dfs def findWords(board, words): """ :type board: List[List[str]] :type words: List[str] :rtype: List[str] """ #dfs def dfs(i,j,t,s): ch = board[i][j] if ch not in t: return #递归终止条件 t = t[ch] #当前层处理逻辑 if "end" in t and t['end'] == 1: #word 在board里 res.append(s+ch) t['end'] = 0 board[i][j] = '#' #drill down if i + 1 < m and board[i+1][j] != '#': dfs(i+1,j,t,s+ch) if i - 1 >= 0 and board[i-1][j] != '#': dfs(i-1,j,t,s+ch) if j + 1 < n and board[i][j+1] != '#': dfs(i,j+1,t,s+ch) if j - 1 >= 0 and board[i][j-1] != '#': dfs(i,j-1,t,s+ch) board[i][j] = ch # reverse state #把单词存入字典树中 trie = {} for word in words: t = trie print("0",t) for ch in word: if ch not in t: t[ch] = {} print("1",t) t = t[ch] print("2",t) t['end'] = 1 print("3",trie) #对board 进行深度优先遍历 m, n = len(board),len(board[0]) res = [] for i in range(m): for j in range(n): dfs(i,j,trie,'') return res # 解法2:字典树 + dfs, 比解法1 只是写法不一样,把字典树单独建了一个类 class TrieNode(): def __init__(self): self.children = collections.defaultdict(TrieNode) self.isWord = False class Trie(): def __init__(self): self.root = TrieNode() def insert(self, word): node = self.root for w in word: node = node.children[w] node.isWord = True def search(self, word): node = self.root for w in word: node = node.children.get(w) if not node: return False return node.isWord class Solution(object): def findWords(self, board, words): """ :type board: List[List[str]] :type words: List[str] :rtype: List[str] """ res = [] trie = Trie() node = trie.root for w in words: trie.insert(w) for i in range(len(board)): for j in range(len(board[0])): self.dfs(board,node,i,j,'',res) return res def dfs(self,board,node,i,j,path,res): if node.isWord: res.append(path) node.isWord = False if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]): return temp = board[i][j] node = node.children.get(temp) if not node: return board[i][j] = '#' self.dfs(board,node,i+1,j,path + temp, res) self.dfs(board,node,i-1,j,path + temp, res) self.dfs(board,node,i,j+1,path + temp, res) self.dfs(board,node,i,j-1,path + temp, res) board[i][j] = temp #解法3:复数的知识简化操作 class Solution(object): def findWords(self, board, words): """ :type board: List[List[str]] :type words: List[str] :rtype: List[str] """ root = {} for word in words: node = root for c in word: node = node.setdefault(c, {}) node[None] = True board = {i + 1j*j: c for i, row in enumerate(board) for j, c in enumerate(row)} found = [] def search(node, z, word): if node.pop(None, None): found.append(word) c = board.get(z) if c in node: board[z] = None for k in range(4): search(node[c], z + 1j**k, word + c) board[z] = c for z in board: search(root, z, '') return found
# -*- coding: utf-8 -*- # @Time : 2019-12-13 09:49 # @Author : songzhenxi # @Email : [email protected] # @File : LeetCode_84_1034.py # @Software: PyCharm # 给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。 # 求在该柱状图中,能够勾勒出来的矩形的最大面积。 # 以上是柱状图的示例,其中每个柱子的宽度为 1,给定的高度为 [2,1,5,6,2,3]。 # 图中阴影部分为所能勾勒出的最大矩形面积,其面积为 10 个单位。 # # 示例: # # 输入: [2,1,5,6,2,3] # 输出: 10 # Related Topics 栈 数组 # leetcode submit region begin(Prohibit modification and deletion) class Solution(object): def largestRectangleArea(self, heights): """ 题目:84.柱状图中的最大矩形面积(https://leetcode-cn.com/problems/largest-rectangle-in-histogram/) 标签:栈 数组 学号:1034(五期一班三组) :type heights: List[int] :rtype: int """ stack, max_area = [-1], 0 for i in xrange(0, len(heights)): while stack[-1] > -1 and heights[stack[-1]] >= heights[i]: max_area = max(max_area, heights[stack.pop()] * (i - stack[-1] - 1)) stack.append(i) while stack[-1] > -1: max_area = max(max_area, heights[stack.pop()] * (len(heights) - stack[-1] - 1)) return max_area # leetcode submit region end(Prohibit modification and deletion)
#给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。 # # 例如: #给定二叉树: [3,9,20,null,null,15,7], # # 3 # / \ # 9 20 # / \ # 15 7 # # # 返回其层次遍历结果: # # [ # [3], # [9,20], # [15,7] #] # # Related Topics 树 广度优先搜索 from typing import List class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def stringToTreeNode(input): input = input.strip() input = input[1:-1] if not input: return None inputValues = [s.strip() for s in input.split(',')] root = TreeNode(int(inputValues[0])) nodeQueue = [root] front = 0 index = 1 while index < len(inputValues): node = nodeQueue[front] front = front + 1 item = inputValues[index] index = index + 1 if item != "None": leftNumber = int(item) node.left = TreeNode(leftNumber) nodeQueue.append(node.left) if index >= len(inputValues): break item = inputValues[index] index = index + 1 if item != "None": rightNumber = int(item) node.right = TreeNode(rightNumber) nodeQueue.append(node.right) return root #leetcode submit region begin(Prohibit modification and deletion) # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def levelOrder1(self, root: TreeNode) -> List[List[int]]: if not root: return [] q, res = [root], [] while q: res.append([node.val for node in q]) q1 = [] for node in q: if node.left: q1.append(node.left) if node.right: q1.append(node.right) q = q1 return res def levelOrder(self, root: TreeNode) -> List[List[int]]: q, res = [root], [] while root and q: res.append([node.val for node in q]) # children = [(node.left, node.right) for node in q] # q = [kid for c in children for kid in c if kid] q = [child for node in q for child in (node.left, node.right) if child] return res def levelOrder2(self, root: TreeNode) -> List[List[int]]: res = [] def _dfs(root, height): # terminate if not root: return # process current level if len(res) == height: res.append([]) res[height].append(root.val) # dirll down _dfs(root.left, height + 1) _dfs(root.right, height + 1) _dfs(root, 0) return res #leetcode submit region end(Prohibit modification and deletion) x = Solution().levelOrder(stringToTreeNode(str([1,2,3,4, None, None, 5]))) print(x)
#给定两个字符串 text1 和 text2,返回这两个字符串的最长公共子序列。 # # 一个字符串的 子序列 是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串。 #例如,"ace" 是 "abcde" 的子序列,但 "aec" 不是 "abcde" 的子序列。两个字符串的「公共子序列」是这两个字符串所共同拥有的子序列。 # # 若这两个字符串没有公共子序列,则返回 0。 # # # # 示例 1: # # 输入:text1 = "abcde", text2 = "ace" #输出:3 #解释:最长公共子序列是 "ace",它的长度为 3。 # # # 示例 2: # # 输入:text1 = "abc", text2 = "abc" #输出:3 #解释:最长公共子序列是 "abc",它的长度为 3。 # # # 示例 3: # # 输入:text1 = "abc", text2 = "def" #输出:0 #解释:两个字符串没有公共子序列,返回 0。 # # # # # 提示: # # # 1 <= text1.length <= 1000 # 1 <= text2.length <= 1000 # 输入的字符串只含有小写英文字符。 # # Related Topics 动态规划 #leetcode submit region begin(Prohibit modification and deletion) class Solution(object): def longestCommonSubsequence0(self, text1, text2): # 暴力解法, 先求出子序列, 再比较 sub1 = self.subsequence(text1) sub2 = self.subsequence(text2) max_l = 0 for s in sub1: if len(s) > max_l and s in sub2: max_l = max(len(s), max_l) print(max_l, s) return max_l def subsequence(self, s): res = [] def backtrack(p, n): if p: res.append(''.join(p)) for i in range(n, len(s)): if p and (s[i] in p or i < s.index(p[-1])): continue p.append(s[i]) backtrack(p, n + 1) p.pop() backtrack([], 0) return res # res = [] # def bc(p, n): # if p: # res.append(p) # for i in range(n, len(text1)): # if text1[i] in p: # continue # bc(p + text1[i], n + 1) # # p.append(text1[i]) # # bc(p, n + 1) # # p.pop() # bc("", 0) # print(len(res), len(set(res))) # for x in sorted(res, key=len): # print(x) def longestCommonSubsequence(self, text1, text2): """ dp[i - 1][j - 1] + 1 text1[i-1]=text2[j-1] dp[i][j] = Max( dp[i - 1][j], dp[i][j - 1] text1[i-1] != text2[j-1] a c d [0, 0, 0, 0] a [0, 1, 1, 1] b [0, 1, 1, 1] c [0, 1, 2, 2] d [0, 1, 2, 2] e [0, 1, 2, 3] """ m, n = len(text1), len(text2) if m == 0 or n == 0: return 0 dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): if text1[i - 1] == text2[j - 1]: dp[i][j] = dp[i - 1][j - 1] + 1 else: dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) return dp[m][n] def longestCommonSubsequence2(self, text1, text2): """ 暴力递归 """ def dp(i, j): if i == - 1 or j == -1: return 0 if text1[i] == text2[j]: return dp(i - 1, j - 1) + 1 else: return max(dp(i - 1, j), dp(i, j - 1)) return dp(len(text1) - 1, len(text2) - 1) #leetcode submit region end(Prohibit modification and deletion) assert Solution().longestCommonSubsequence("abcde", "ace") == 3 assert Solution().longestCommonSubsequence("ubmrapg", "ezupkr") == 2 assert Solution().longestCommonSubsequence("ylqpejqbalahwr", "yrkzavgdmdgtqpg") == 3
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None #递归 # class Solution: # def preorderTraversal(self, root: TreeNode) -> List[int]: # result = [] # def helper(root, result): # if not root: return # result.append(root.val) # if root.left: # helper(root.left, result) # if root.right: # helper(root.right, result) # helper(root, result) # return result #迭代 class Solution: def preorderTraversal(self, root: TreeNode) -> List[int]: result = [] if not root: return result pointer = root stack = [pointer] while stack: cur = stack.pop() result.append(cur.val) #这里要注意,是右先入栈,左再入栈,使得pop时,左先出,右再出 if cur.right: stack.append(cur.right) if cur.left: stack.append(cur.left) return result
class Solution: def reverseWords(self, s: str) -> str: import re str1 = re.findall(r'\S+', s) if len(str1) == 0: return '' str1 = str1[::-1] str2 = '' for i in range(len(str1) -1): str2 += (str1[i] + ' ') return str2 + str1[-1]
# # @lc app=leetcode.cn id=541 lang=python3 # # [541] 反转字符串 II # # https://leetcode-cn.com/problems/reverse-string-ii/description/ # # algorithms # Easy (50.28%) # Likes: 58 # Dislikes: 0 # Total Accepted: 10.3K # Total Submissions: 20.1K # Testcase Example: '"abcdefg"\n2' # # 给定一个字符串和一个整数 k,你需要对从字符串开头算起的每个 2k 个字符的前k个字符进行反转。如果剩余少于 k # 个字符,则将剩余的所有全部反转。如果有小于 2k 但大于或等于 k 个字符,则反转前 k 个字符,并将剩余的字符保持原样。 # # 示例: # # # 输入: s = "abcdefg", k = 2 # 输出: "bacdfeg" # # # 要求: # # # 该字符串只包含小写的英文字母。 # 给定字符串的长度和 k 在[1, 10000]范围内。 # # # # @lc code=start class Solution: def reverseStr(self, s: str, k: int) -> str: # n = len(s) # ans = '' # for i in range(0, n, 2 * k): # if i + 2 * k <= n: # sub = s[i:i + k][::-1] + s[i + k:i + 2 * k] # elif i + 2 * k - n < k: # sub = s[i:i + k][::-1] + s[i + k:] # else: # sub = s[i:][::-1] # ans += sub # return ans a = list(s) for i in range(0, len(a), 2 * k): a[i:i + k] = reversed(a[i:i + k]) return ''.join(a) # @lc code=end
# -*- coding: utf-8 -*- """https://leetcode-cn.com/problems/merge-two-sorted-lists""" # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # 将输入列表转换为链表 def initList(self, data): if len(data) == 0: return # 头结点 head = ListNode(data[0]) # 逐个为 data 内的数据创建结点, 建立链表 p = head for i in data[1:]: node = ListNode(i) p.next = node p = p.next return head def mergeTwoListsSolutionOne(self, l1: ListNode, l2: ListNode) -> ListNode: if l1 and l2: # ensure l1 是较小的结点 if l1.val > l2.val: l1, l2 = l2, l1 l1.next = self.mergeTwoListsSolutionOne(l1.next, l2) return l1 or l2 def mergeTwoListSolutionTwo(self, l1: ListNode, l2: ListNode) -> ListNode: # 得到头结点 """ cur = ListNode(-1) head = cur ...... return head.next """ if l1.val < l2.val: cur = l1 l1 = l1.next else: cur = l2 l2 = l2.next head = cur while l1 and l2: if l1.val < l2.val: cur.next = l1 l1 = l1.next else: cur.next = l2 l2 = l2.next cur = cur.next cur.next = l1 if l1 is not None else l2 return head def display_arr(self, node: ListNode) -> []: if node is None: return [] res = [] while node is not None: res.append(node.val) node = node.next return res if __name__ == "__main__": test = Solution() data1 = [1, 4, 7, 8] data2 = [1, 3, 5] l1 = test.initList(data1) l2 = test.initList(data2) print(test.display_arr(l1)) print(test.display_arr(l2)) result = test.mergeTwoListsSolutionOne(l1, l2) # result = test.mergeTwoListSolutionTwo(l1, l2) print(test.display_arr(result))
#给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。 # # 示例: # # 输入: ["eat", "tea", "tan", "ate", "nat", "bat"], #输出: #[ # ["ate","eat","tea"], # ["nat","tan"], # ["bat"] #] # # 说明: # # # 所有输入均为小写字母。 # 不考虑答案输出的顺序。 # # Related Topics 哈希表 字符串 from typing import List #leetcode submit region begin(Prohibit modification and deletion) import collections class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: result = collections.defaultdict(list) for s in strs: result[tuple(sorted(s))].append(s) return result.values() # class Solution: # def groupAnagrams(self, strs: List[str]) -> List[List[str]]: # ans = collections.defaultdict(list) # for s in strs: # count = [0] * 26 # for c in s: # count[ord(c) - ord('a')] += 1 # ans[tuple(count)].append(s) # return ans.values() #leetcode submit region end(Prohibit modification and deletion) r = Solution().groupAnagrams(["eat","tea","tan","ate","nat","bat"]) print(r)
#给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 # # 例如,给出 n = 3,生成结果为: # # [ # "((()))", # "(()())", # "(())()", # "()(())", # "()()()" #] # # Related Topics 字符串 回溯算法 #leetcode submit region begin(Prohibit modification and deletion) class Solution(object): def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ result = [] def backtrack(s, left, right): # 满足条件添加结果 if len(s) == 2 * n: result.append(s) if left < n: backtrack(s + '(', left + 1, right) if right < left: backtrack(s + ')', left, right + 1) backtrack('', 0, 0) return result #leetcode submit region end(Prohibit modification and deletion) x = Solution().generateParenthesis(3) print(x)
""" 排序相关 https://mp.weixin.qq.com/s/Qf416rfT4pwURpW3aDHuCg """ class SortAlgorithm: @classmethod def bubble_sort(cls, arr): """冒泡排序""" i = 0 while i < len(arr) - 1: j = 0 is_sorted = True while j < len(arr) - 1 - i: # print(arr, 'i:', i, 'j:', j, " arr[j]:", arr[j], "arr[j + 1]:", arr[j + 1]) if arr[j] < arr[j + 1]: temp = arr[j] arr[j] = arr[j + 1] arr[j + 1] = temp is_sorted = False j += 1 # print(i, is_sorted) if is_sorted: break i += 1 return arr @classmethod def select_sort(cls, arr): """选择排序: 首先,找到数组中最小的元素,拎出来,将它和数组的第一个元素交换位置 第二步,在剩下的元素中继续寻找最小的元素,拎出来,和数组的第二个元素交换位置 如此循环,直到整个数组排序完成。 """ i = 0 while i < len(arr): _min = i # 最小元素下标 j = i + 1 while j < len(arr): if arr[j] < arr[_min]: _min = j j += 1 if i != _min: temp = arr[i] arr[i] = arr[_min] arr[_min] = temp i += 1 return arr @classmethod def insert_sort(cls, arr): """插入排序 想象一下摸牌的时候从左往右,从小到大插入 """ i = 1 # 从第二个元素开始 while i < len(arr): j = i - 1 # 从i-1开始往前数 current = i while j >= 0: # print(current, j, arr) if arr[current] < arr[j]: temp = arr[current] arr[current] = arr[j] arr[j] = temp current = j # 交换后下标要随着一起移动 else: break j -= 1 i += 1 return arr @classmethod def shell_sort(cls, arr): """ 希尔排序(发明人叫shell) https://www.geeksforgeeks.org/shellsort/ """ n = len(arr) gap = n // 2 while gap > 0: partb = range(gap, n) for i in partb: temp = arr[i] j = i print("gap:{} {} i:{} j:{} j-gap:{} arr[j-gap]>temp:{} > {} arr[j]: {}" .format(gap, partb, i, j, j-gap, arr[j-gap], temp, arr[j]), arr) while j >= gap and arr[j - gap] > temp: arr[j] = arr[j - gap] print("\t j:{} j-gap:{} arr[j]=arr[j-gap]:{}={}" .format(j, j - gap, arr[j], arr[j-gap]), arr) j -= gap arr[j] = temp gap //= 2 return arr @classmethod def merge_sort(cls, arr): """ 递推公式: merge_sort(p…r) = merge(merge_sort(p…q), merge_sort(q+1…r)) 终止条件: p >= r 不用再继续分解 """ # TODO 可改写为递归 def merge(left, right): result = [] print('合', left, ',', right) while left and right: min_value = left.pop(0) if left[0] <= right[0] else right.pop(0) result.append(min_value) # print("\t", "merged", result, "l:", left, 'right', right) print("\t", result + left + right) return result + left + right if len(arr) <= 1: return arr # print("\t分", arr) mid = len(arr) // 2 lft = arr[:mid] r = arr[mid:] # print("\t分", lft, ',', r) return merge(cls.merge_sort(lft), cls.merge_sort(r)) @classmethod def quick_sort(cls, arr): if len(arr) <= 1: return arr povit = arr.pop() left, right = [], [] for i in arr: if i < povit: left.append(i) else: right.append(i) return cls.quick_sort(left) + [povit] + cls.quick_sort(right) @classmethod def quick_sort1(cls, arr): pass if __name__ == '__main__': # print(SortAlgorithm.bubble_sort([8, 2, 5, 9, 7, 1])) # print(SortAlgorithm.select_sort([8, 2, 5, 9, 7, 1])) # print(SortAlgorithm.insert_sort([8, 2, 5, 9, 7, 1])) # print(SortAlgorithm.shell_sort([8, 2, 5, 9, 7, 10, 1, 15, 12, 3])) # print(SortAlgorithm.merge_sort([8, 2, 5, 9, 7, 10, 1, 15, 12, 3, -1])) print(SortAlgorithm.merge_sort([1, 5, 8, 0, 10, 7, 2, 6])) # print(SortAlgorithm.quick_sort([8, 2, 5, 9, 7, 10, 1, 15, 12, 3, -1]))
# # @lc app=leetcode.cn id=105 lang=python3 # # [105] 从前序与中序遍历序列构造二叉树 # # https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/ # # algorithms # Medium (62.93%) # Likes: 289 # Dislikes: 0 # Total Accepted: 34.2K # Total Submissions: 54.3K # Testcase Example: '[3,9,20,15,7]\n[9,3,15,20,7]' # # 根据一棵树的前序遍历与中序遍历构造二叉树。 # # 注意: # 你可以假设树中没有重复的元素。 # # 例如,给出 # # 前序遍历 preorder = [3,9,20,15,7] # 中序遍历 inorder = [9,3,15,20,7] # # 返回如下的二叉树: # # ⁠ 3 # ⁠ / \ # ⁠ 9 20 # ⁠ / \ # ⁠ 15 7 # # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: # preorder 中任一节点 root # inorder 中对应的 root 节点左边所有节点组成 root.left, 右边节点组成 root.right pre_idx = 0 idx_map = {val:idx for idx, val in enumerate(inorder)} def helper(in_left = 0, in_right = len(inorder)): nonlocal pre_idx if in_left == in_right: return None # preorder 中节点为 root root_val = preorder[pre_idx] root = TreeNode(root_val) # inorder 中对应 root 节点左边所有节点为 root.left, 右边所有节点为 root.right index = idx_map[root_val] pre_idx += 1 # 递归栈每一层都依次确定一个 root 元素 root.left = helper(in_left, index) root.right = helper(index + 1, in_right) return root return helper() # @lc code=end
""" 590. N-ary Tree Postorder Traversal Given an n-ary tree, return the postorder traversal of its nodes' values. Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).   Follow up: Recursive solution is trivial, could you do it iteratively?   Example 1: Input: root = [1,null,3,2,4,null,5,6] Output: [5,6,3,2,4,1] Example 2: Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] Output: [2,6,14,11,7,3,12,8,4,13,9,10,5,1]   Constraints: The height of the n-ary tree is less than or equal to 1000 The total number of nodes is between [0, 10^4] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/n-ary-tree-postorder-traversal 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ from typing import List """ # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ class Solution: def postorder(self, root: 'Node') -> List[int]: """ :type root: Node :rtype: List[int] """ if root is None: return [] stack, output = [root, ], [] while stack: root = stack.pop() if root is not None: output.append(root.val) for c in root.children: stack.append(c) return output[::-1]
# # @lc app=leetcode.cn id=429 lang=python3 # # [429] N叉树的层序遍历 # # @lc code=start """ # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ # class Solution: # # 每层记录节点的值,放到数组中,并记录下一层的children。重复之前的操作 # def levelOrder(self, root: 'Node') -> List[List[int]]: # if not root: # return [] # res = [] # cur = [root] # while cur: # next = [] # temp = [] # for node in cur: # temp.append(node.val) # next += node.children # res.append(temp) # cur = next # return res # # # class Solution(object): # def levelOrder(self, root): # L = [] # self.traverse(root,0,L) # return L # def traverse(self,root, depth, L): # if root == None: # return # if len(L) == depth:# 如果该层还没有层级数组,则初始化一个 # L.append([]) # L[depth].append(root.val)# 将同一层的元素加入level中 # for x in root.children:# 遍历孩子 # self.traverse(x, depth+1, L) # 这个turkey boy的代码tql,充满了伪代码的味道,记录一层一层的值。 class Solution(object): def levelOrder(self, root): q, ret = [root], [] while any(q): ret.append([node.val for node in q]) q = [child for node in q for child in node.children if child] return ret # @lc code=end
import sys import itertools class SumPairMatcher(object): """ #Program that accepts a list of integers separated by spaces and a target integer. #Prints out all of the pairs of numbers from the input list that sum to the target integer. #Sorts lists so smaller values are shown first. """ def getLine(self): # accept integer list as line line = sys.stdin.readline() digits = line.strip().split(" ") return digits def mapper(self, rawInput): # Map digits to ints as list castDigits = list(map(int, rawInput)) return castDigits def getTarget(self): # accept target integer target = sys.stdin.readline() return target def combinator(self, mappedDigits): # Create list of all pairs of values using itertools combinations combos = list(itertools.combinations(mappedDigits, 2)) return combos def createPairList(self, combinatorResults, targetSum): # Create empty list for valid pairs pairList = [] # Loop through each pair in combinations, create sum for pair in combinatorResults: summed = pair[0] + pair[1] # check if sum matches target if summed == int(targetSum): matchingPairs = pair[0], pair[1] # Check if matching pair is already in list if matchingPairs in pairList: pass else: pairList.append(matchingPairs) else: pass return pairList def orderPairs(self, pairResults): # Create newList to generate ordered lists newList = [] for each in pairResults: if each[0] > each[1]: item = each[1], each[0] newList.append(item) else: item = each[0], each[1] newList.append(item) return newList def finalSort(self, unsortedList): # Sort the sorted list sortedList = sorted(unsortedList) for each in sortedList: print(each[0], each[1]) return None if __name__ == "__main__": a = SumPairMatcher() inputLine = a.getLine() mappedDigits = a.mapper(inputLine) target = a.getTarget() combos = a.combinator(mappedDigits) unorderedPairs = a.createPairList(combos, target) orderedPairs = a.orderPairs(unorderedPairs) a.finalSort(orderedPairs)
#!/usr/bin/env python def numFactors(n): factors = 2 for i in xrange( 2, (n/2)+1 ): if( n % i == 0 ): factors += 1 return factors i = 1 biggest_n = 0 triangle = i while( True ): i += 1 triangle += i n = numFactors(triangle) if( n > biggest_n ): biggest_n = n print triangle, n if(n > 500): break
##### ### Matthew Nuckolls ### Project Euler #32 ### Production Code ##### def digits(*args): result = set() for arg in args: result = result.union(set([int(i) for i in str(arg)])) return result def pandigital(*args): length = sum([len(str(arg)) for arg in args]) if length != 9: return False d = digits(*args) if len(d) != length: return False else: return d == set(range(1,length+1)) def pandigital_product(a,b): return pandigital( a, b, a*b ) def small_pandigits(): result = set() for a in xrange(1,10000): for b in xrange(1,10000): if pandigital_product(a,b): print a, b, a*b result.add(a*b) print sum(result) small_pandigits()
#!/usr/bin/env python # # Project Euler 94 # a^2 + b^2 = c^2 # c^2 - b^2 = a^2 from math import sqrt def is_square(n): m = int(sqrt(n)) return n == m * m def is_valid(c,a): return is_square(c*c - a*a) def high(c): return is_valid(c, c/2 + 1) def low(c): return is_valid(c, c/2) def both(c): if is_valid(c, c/2): print c, "low!" if is_valid(c, c/2 + 1): print c, "high!" def solution(): return "buttes" #if __name__ == "__main__": # print solution() """ find a "base" of the form n = k^2 + 1 where k is even and n is valid high each "base" adds 3*n + 1 perimeter to the total between each n_i and n_i+1 there exists m = k_i*k_i+1 + 1 for each halfway number m, add 3*m - 1 perimeter to the total """ perimeter = 0 bases = [c for c in xrange(2,25000,2) if high(c*c+1)] for base in bases: n = base*base + 1 p = 3*n + 1 if p < 1000000000: # print n, "used", p perimeter += p for i in xrange(1,len(bases)): m = bases[i]*bases[i-1] + 1 p = m*3 - 1 if p < 1000000000: # print m, "used", p perimeter += p print perimeter
#!/usr/bin/env python # # Project Euler 58 from bitarray import bitarray from math import sqrt def generate_primes(): size = 10 ** 9 stop = int(sqrt(size)) a = bitarray(size) a.setall(True) a[:2] = False primes = list() next = 2 try: while True: primes.append(next) if next < stop: a[next::next] = False next = a.index(True, next+1) except ValueError: pass return primes def diagonals(n): return [n*n, n*n - (n-1), n*n - 2*(n-1), n*n - 3*(n-1)] def solution(): primes = set(generate_primes()) prime_count = 0 diag_count = 1 ratio = 999.0 n = 1 while ratio > 0.1: n += 2 prime_count += len([x for x in diagonals(n) if x in primes]) diag_count += 4 ratio = float(prime_count) / diag_count return n if __name__ == "__main__": print solution()
#!/usr/bin/env python sum = 0 for i in xrange(1000): if( (i % 3 == 0) or (i % 5 == 0) ): sum += i print sum print sum(x for x in xrange(1000) if (x % 3 == 0 or x % 5 == 0))
#!/usr/bin/python import os import subprocess import sys # Return codes # 1 : No command is given # -1 : Error in command excecution or in command syntax def run_command(command=None): """ This module runs the command input to it. On Success returns output On failure returns -1 On no input string passed returns 1 """ if command is None: print "command sent : ", command return 1 else: args = command.split() try: proc = subprocess.Popen(args, stdout=subprocess.PIPE, stdin=subprocess.PIPE) except OSError as e: print print str(e), ": ", command try: proc op = proc.communicate()[0] ret_code = proc.returncode if ret_code == 0: return op except NameError: print "Command execution failed. " return -1 def cmd_op_to_file(command, filename): """ This module can be used to run a python file from another .. python file and store the output into a file using subprocess. """ if command: args = command.split() else: return None try: with open(filename, "w") as fh: proc = subprocess.Popen(args, stdout=fh) except IOError as e: print print str(e) op = proc.communicate()[0] if proc.returncode == 0: return op else: return -1 def handle_ret_val(ret_val, command=None): """ Function to handle return value. Prints message according to value inside ret_val. Returns nothing. """ if ret_val == -1: print print "Command execution failed : %s" % command elif ret_val == 1: print print "No command is passed : %s" % command else: print print "Output of your input command \"%s\" : \n%s " % (command, ret_val) def main(): # For run_command cmd1 = "lsa" ret_val = run_command(cmd1) handle_ret_val(ret_val, cmd1) # For writing command output into a file filename = "/tmp/command_output" cmd2 = "/usr/bin/python factorial.py" ret_val_file = cmd_op_to_file(cmd2, filename) handle_ret_val(ret_val_file, cmd2) if os.path.exists(filename) : print print "Output is written to : %s" % filename if __name__ == '__main__': main()
#This program tracks grades from students and collects an average. runtotal = float(0) count = int(0) avg = float(0) sent = int(0) #ask the user for the grade num = int(input('Please enter the first grade. Enter -1 to stop. ')) sent = 1 while sent == 1: if num >= 0: if num > 100: num = int(input('Invalid grade. Please try again. ')) else: count = count + 1 runtotal = num + runtotal if num > 90: print(' You made an A. Nice.') elif num >= 80 and num < 90: print(' You made a B. You can do better.') elif num >= 70 and num < 80: print('You made a C. Perhaps you should see a tutor?') elif num >= 60 and num < 70: print('You made a D. Do you even have the book?') elif num < 60: print('You made an F!! You are fired. Get out!!') num = int(input('Please enter the next grade. Enter -1 to stop. ')) else: sent = 0 #add the count for the grade #add the grade to the current running total of grades #finish the loop with -1 #average the grades unless there are zero grades avg = runtotal / count print('The number of grades entered is', count,".") print('The average of the grades entered is', avg,".")
#Mary Jacobsen #Project 2 - file transer system #client side import sys from socket import * #This function sets up the data socket #It is mostly from Project 1 def getSocket(): if sys.argv[3] == "-l": #if command is -l, <SERVER_HOST>, <SERVER_PORT>, <COMMAND>, <DATA_PORT> numArguments = 4 elif sys.argv[3] == "-g": #if command is -g, <SERVER_HOST>, <SERVER_PORT>, <COMMAND>, <FILENAME>, <DATA_PORT> numArguments = 5 #get server port number from command line arg serverport = int(sys.argv[numArguments]) #create socket serversocket = socket(AF_INET, SOCK_STREAM) #referenced https://docs.python.org/2/howto/sockets.html #bind socket serversocket.bind(('', serverport)) #referenced https://docs.python.org/2/howto/sockets.html #listen for connections and queue up only 1 connect request serversocket.listen(1) #referenced https://docs.python.org/2/howto/sockets.html (dataSocket, address) = serversocket.accept() #referenced https://docs.python.org/2/howto/sockets.html return dataSocket #This function sets up the client socket #Used https://docs.python.org/2/howto/sockets.html def connectServer(): #flip1, flip2, or flip3 servername = sys.argv[1]+".engr.oregonstate.edu" #get server port from command line args serverport = int(sys.argv[2]) #get a client connection socket clientsocket = socket(AF_INET,SOCK_STREAM) #connect using server name and port clientsocket.connect((servername, serverport)) return clientsocket #This function gets the IP address #I found how to do this here: #https://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib def getIP(): s = socket(AF_INET, SOCK_DGRAM) s.connect(("8.8.8.8", 80)) return s.getsockname()[0] #This function receives a file specified gy the command line #I found how to do this here: #https://www.bogotobogo.com/python/python_network_programming_server_client_file_transfer.php def receiveFile(datasocket): f = open(sys.argv[4], "w") #<SERVER_HOST>, <SERVER_PORT>, <COMMAND>, <FILENAME>, <DATA_PORT> buffer = datasocket.recv(1024) #receive until server sends "finished" while "finished" not in buffer: f.write(buffer) print "{}".format(buffer) buffer = datasocket.recv(1024) print "File transfer complete." #This function receives and prints all the filenames in the directory from the server def receiveList(datasocket): filename = datasocket.recv(100) #receive files until server sends "finished" while filename != "finished": print filename filename = datasocket.recv(100) #This function sends the info from the command line to the server #then receives back the data using a seperate data socket that is closed after. #It also has some error handling #https://docs.python.org/2/howto/sockets.html def receiveData(clientsocket): if sys.argv[3] == "-g": #<SERVER_HOST>, <SERVER_PORT>, <COMMAND>, <FILENAME>, <DATA_PORT> print "Reqesting {}".format(sys.argv[4]) portnumber = sys.argv[5] command = "-g" elif sys.argv[3] == "-l": #<SERVER_HOST>, <SERVER_PORT>, <COMMAND>, <DATA_PORT> print "Requesting list of files in this directory" portnumber = sys.argv[4] command = "-l" #send port number clientsocket.send(portnumber) #receive response clientsocket.recv(1024) #send command clientsocket.send(command) #receive response clientsocket.recv(1024) #send IP address clientsocket.send(getIP()) #receive response response = clientsocket.recv(1024) if response == "notokay": print "The server could not process the command.\n Please use: -l or -g <FILENAME>" exit(1) if command == "-g": #send file name clientsocket.send(sys.argv[4]) #receive response response = clientsocket.recv(1024) if response != "File found": #if the server does not send back "File found", we are done here." print "{}:{} says FILE NOT FOUND".format(sys.argv[1],sys.argv[5]) return #socket for just data datasocket = getSocket() if command == "-g": #if command is g, call receiveFile print "Receiving {} from {}:{}".format(sys.argv[4],sys.argv[1],sys.argv[5]) receiveFile(datasocket) if command == "-l": #if command is l, call receiveList print "Receiving directory structure from {}:{}".format(sys.argv[1],sys.argv[4]) receiveList(datasocket) #close datasocket datasocket.close() #All that is left to do in main is to error handle for the command line arguments, #get the client socket by calling connectServer, #and call getData if __name__ == "__main__": #check the number of arguments if len(sys.argv) < 5 or len(sys.argv) > 6: print "Please use: python ftclient.py <SERVER_HOST> <SERVER_PORT> -g <FILENAME> <DATA_PORT>\n or python ftclient.py <SERVER_HOST> <SERVER_PORT> -l <DATA_PORT>" exit(1) #check if the server name (either flip1, flip2, or flip3) elif (sys.argv[1] != "flip1" and sys.argv[1] != "flip2" and sys.argv[1] != "flip3"): print "Server name must be flip1, flip2, or flip3." exit(1) #check the server port elif (int(sys.argv[2]) < 1024 or int(sys.argv[2]) > 65535): print "Please enter a valid server port number." exit(1) #check command (either -g or -l) elif (sys.argv[3] != "-g" and sys.argv[3] != "-l"): print "Please enter either -g or -l for the command." exit(1) #check data port for command equal to l elif (sys.argv[3] == "-l" and (int(sys.argv[4]) < 1024 or int(sys.argv[4]) > 65535)): print "Please enter a valid data port number." exit(1) #check data port for command equal to g elif (sys.argv[3] == "-g" and (int(sys.argv[5]) < 1024 or int(sys.argv[5]) > 65535)): print "Please enter a valid data port number." exit(1) #get the client socket for talking with the server clientsocket = connectServer() #And we're ready to receive the data the user wants from the server receiveData(clientsocket)
import math import Dif_Helman class Input: @staticmethod def count_digits(n): if n == 0: return 0 return 1 + n.count_digits(n // 10) @staticmethod def binary_input(): binary = int(input("Введите число в двоичном виде (до 10 символов): "),2) try: binary == 0 except Warning: print("Число слишком мало! Необходимо вводить числа строго больше нуля!") else: print("Необходимо вводить число только в двоичном виде!") try: digits = int(math.log10(binary)) + 1 > 10 # Проверяем если введенное число больше 10 значеиний except IndexError: print("Число слишком большое") return binary @staticmethod def decimal_input(): decimal = int(input("Введите число в десятичном виде : ")) try: decimal == 0 except Warning: print("Число слишком мало! Необходимо вводить числа строго больше нуля!") except ValueError: print("Нужно вводить только числа") return decimal @staticmethod def hex_input(): num = input("Введите 16 - ричное число : ") try: hex = int(num, 16) # interpret the input as a base-16 number, a hexadecimal. except ValueError: print("Вы не ввели 13-ричное число") return hex @staticmethod def convert_binary_to_decimal(value): return int(value,2) @staticmethod def convert_hex_to_binary(value): return int(value,16) class Prime: def __init__(self): pass @staticmethod def GCD(a,b): #НОД while a!=b: if a>b: a = a-b else: b = b - a return a # проверка на простоту тут и на первообразность @staticmethod # Возврат первообразного корня для введенного числа def prime_root(value): required_set = set(num for num in range(1,value) if Prime.GCD(num,value)==1) for g in range(1,value): real_set = set(pow(g,powers)%value for powers in range(1,value)) if required_set == real_set: return g #вызов метода шифрования для создания 2-х ключей def cypher_method(prime_root,dec_convert): # публичный ключ для первого secret_number_A = Dif_Helman.Dif_Helman_cypher.secret_number_generator() public_key_A = Dif_Helman.Dif_Helman_cypher.key_generator(dec_convert,secret_number_A,prime_root) # публичный ключ для второго secret_number_B = Dif_Helman.Dif_Helman_cypher.secret_number_generator() public_key_B = Dif_Helman.Dif_Helman_cypher.key_generator(dec_convert,secret_number_B,prime_root) # секретный ключ для первого private_key_A = Dif_Helman.Dif_Helman_cypher.secret_key_generator(public_key_B,secret_number_A,dec_convert) private_key_B = Dif_Helman.Dif_Helman_cypher.secret_key_generator(public_key_A,secret_number_B,dec_convert) print("первый ключ {0} второй ключ: {1}".format(public_key_A,public_key_B)) # вопрос для пользователя def question(prime_root,dec_convert): answer = input("Создать секретный ключ c полученным числом?") if answer == "да": cypher_method(prime_root,dec_convert) return True return False def main(): print('Start') while True: menu = int(input('Введите 2, 10, 16 для начала ввода')) if menu == 2: dec_convert = Input.convert_binary_to_decimal(Input.binary_input()) prime_root = Prime.prime_root(dec_convert) print("Простое корень: {0}".format(prime_root)) question(prime_root,dec_convert ) elif menu == 10: dec_convert = Input.decimal_input() prime_root = Prime.prime_root(dec_convert) print("Простое корень: {0}".format(prime_root)) question(prime_root, dec_convert) elif menu == 16: dec_convert = Input.convert_hex_to_binary(Input.hex_input()) prime_root = Prime.prime_root(dec_convert) print("Простое корень: {0}".format(prime_root)) question(prime_root,dec_convert) else: break if __name__ == '__main__': main()
# Важная информация! По ссылке объяснение как .py файлы компилировать в .exe # http://nikovit.ru/blog/samyy-prostoy-sposob-skompilirovat-python-fayl-v-exe/ import ProbabilityTest import DivisionTest # main def main(): print('\n') print("Начало выполнения программы") while True: test_method = int(input("Введите название теста: ")) if test_method == 1: print("\t\v Тест Ферма") test = ProbabilityTest.TestForNumbers() num = test.set_number() test.Ferma_test(num) elif test_method == 2: print("\t\v Тест Рабина-Миллера'") test = ProbabilityTest.TestForNumbers() num = test.set_number() test_num = int(input('Введите число проверок : ')) test.RabinMiller_test(num, test_num) elif test_method == 3: print("\t\v Тест на простоту числа") DivisionTest.DivisionTest.division() else: break # end main if __name__ == '__main__': main()
import random n = int(input ("Masukkan jumlah n =")) for i in range (n): while 1: n = random.random() if n < 0.5 : break print(n)
t = int(input()) for i in range(t): num = int(input()) num = str(num) if num[::-1] == num: print("wins") else: print("losses")
import basicfunctions as bf #loss function def loss(fwdprop,correct): return (correct-fwdprop)**2 def lossList(fwdpropList,correctList): lost = 0 min = bf.minLenTwo(fwdpropList,correctList) for i in range(0,min): lost += loss(fwdpropList[i],correctList[i]) return lost/min #print(lossList([1,5,5,4,6,8,4,21,3,5],[1,6,4,2,5,10,20 #print(lossList([1,5,5,4,6,8,4,21,3,5],[1,5,5,4,6,8,4,21,3,6]))
# Write a program which can compute the factorial of a given numbers. # The results should be printed in a comma-separated sequence on a single line. def fact(x): if x == 0: return 1 return (x * fact(x -1)) x = int(input()) print(fact(x))
for i in range(1,6): print(" "*(5-i)+"$"*i) print("\n\n") for i in range(0,5): print(" "*i+"$"*(5-i)) for i in range(1,6): print(" "*(5-i)+"$"*(2*i-1)) for i in range(0,5): print(" "*i+"$"*(9-2*i))
import pickle import random from helper import * def generate_random_initial_sequence(INPUT_SEQUENCE_LENGTH): WEIGHTS_COUNTER = int(input("Enter weight file number to generate the seed: ")) print("[!]INFO: Generating random seed notes.") try: note_to_int = get_note_to_int(WEIGHTS_COUNTER) int_to_note = get_int_to_note(WEIGHTS_COUNTER) inputSequence = list() for i in range(INPUT_SEQUENCE_LENGTH): inputSequence.append(note_to_int[int_to_note[random.randint(0, len(int_to_note)-1)]]) with open('seed/seed_'+str(WEIGHTS_COUNTER), 'wb') as filepath: pickle.dump(inputSequence, filepath) print("[+]SUCCESS: Seed notes generated successfully.") except: print("[-]ERROR: Error in generating seed notes.") # return inputSequence generate_random_initial_sequence(100)
''' Created on 26 avr. 2013 @author: Alexis Thongvan The purpose of this code is to move a sheet across the existing one ''' from Basics import openExcel, openWorkbook, saveCopy, closeExcel xl = openExcel() wb = openWorkbook("../files/testWorkbook.xlsx", xl) def MoveSheet(sheet, new_position, wb): """sheet can be an integer (the number of the sheet) or a String (the name of the sheet it will be move next to)""" wb.Sheets(sheet).Move(Before=wb.Sheets(new_position)) MoveSheet("toto", "lol", wb) saveCopy("../files/testWorkbookMoveSheetResult.xlsx", wb) closeExcel(xl) #MoveSheet("toto", 3, wb) produce the same result #Before : "toto", "titi", "lol" #After : "titi", "toto", "lol"
''' Created on 8 mai 2013 @author: thongvan Rename a sheet ''' from Basics import openExcel, openWorkbook, saveCopy, closeExcel xl = openExcel() wb = openWorkbook("../files/testWorkbook.xlsx", xl) def renameSheet(old_sheet, new_name, wb): """Rename a sheet to a new name, old sheet can be the number of the sheet, or it's actual name as a string""" ws = wb.Sheets(old_sheet) ws.Name = new_name renameSheet("lol", "NO", wb) renameSheet(1, "one", wb) saveCopy("../files/testWorkbookRenameSheetResult.xlsx", wb) closeExcel(xl) #Before : "toto", "titi", "lol" #After : "one", "titi", "NO"
# price conditions MIN_PRICE = 800 MAX_PRICE = 1500 # area conditions MIN_AREA = 8.0 MAX_AREA = 20.0 # direction condition DIRECTION = ['南', '北', '东', '西'] # location condition def handle(data): if not data: return False # filter status room_status = data['room_status'] print('room_status:') print(room_status) if not room_status: return False # filter price room_price = int(data['room_price']) print('room_price:') print(room_price) if room_price < MIN_PRICE: return False elif room_price > MAX_PRICE: return False # filter area room_area = float(data['room_area']) print('room_area:') print(room_area) if room_area < MIN_AREA: return False elif room_area > MAX_AREA: return False # filter direction room_direction = data['room_direction'] print('room_direction:') print(room_direction) if room_direction not in DIRECTION: return False # filter location return data
"""A Python implementation of LaserLang""" import argparse import operator import sys import math NORTH = [0, 1] SOUTH = [0, -1] EAST = [1, 0] WEST = [-1, 0] INSTRUCTION = 0 STRING = 1 RAW = 2 CONDITIONALS = "⌞⌜⌟⌝" MIRRORS = "\\/>v<^" + CONDITIONALS NULLARY = "crRpPoOnB " UNARY = "()!~b" BINARY = "+-×÷*gl=&|%" def stack_string(self): """ Casts a sequence of integers from the top of the stack to a string """ chars = [] while isinstance(self.memory.peek(), int) and len(self.memory) > 0: chars.append(chr(self.memory.pop())) self.memory.push(''.join(chars)) nullary_ops = {"c": lambda self: self.memory.push(len(self.memory)), "r": lambda self: self.memory.push(self.memory.peek()), "R": lambda self: self.memory.repl(), "p": lambda self: self.memory.pop(), "P": lambda self: self.memory.pop(), "o": lambda self: print(self.memory.pop()), "O": lambda self: self.memory.printself(), "n": lambda self: [self.memory.push(ord(c)) for c in self.memory.pop()[::-1]], "B": stack_string, " ": lambda _: None} unary_ops = {"(": lambda x: x - 1, ")": lambda x: x + 1, "~": operator.inv, "!": lambda x: (1 << int((math.log(x)/math.log(2))+1)) - 1 ^ x, "b": chr} binary_ops = {"+": operator.add, "-": operator.sub, "×": operator.mul, "÷": operator.truediv, "*": operator.pow, "g": lambda a, b: int(b > a), "l": lambda a, b: int(b < a), "=": lambda a, b: int(a == b), "&": operator.and_, "|": operator.or_, "%": lambda a, b: b % a} stack_ops = {"U": lambda self: self.memory.s_up(), "D": lambda self: self.memory.s_down(), "u": lambda self: self.memory.r_up(), "d": lambda self: self.memory.r_down(), "s": lambda self: self.memory.sw_up(), "w": lambda self: self.memory.sw_down()} mirror_ops = {"\\": [WEST, NORTH, EAST, SOUTH], "/": [EAST, SOUTH, WEST, NORTH], ">": [EAST, WEST, EAST, EAST], "v": [NORTH, SOUTH, SOUTH, SOUTH], "<": [WEST, WEST, WEST, EAST], "^": [NORTH, NORTH, SOUTH, NORTH], "⌞": [EAST, NORTH, EAST, NORTH], "⌜": [EAST, SOUTH, EAST, SOUTH], "⌟": [WEST, NORTH, WEST, NORTH], "⌝": [WEST, SOUTH, WEST, SOUTH]} class LaserStack: """ Performs the stack operations required by Laser """ contents = [[]] addr = 0 def pop(self): """Pops the top element off the current stack""" if len(self.contents[self.addr]) == 0: print("Error: pop from empty stack") sys.exit(-1) return self.contents[self.addr].pop() def push(self, item): """Pushes an element to the current stack, casting to an int if numeric""" if isinstance(item, str) and item.isnumeric(): item = int(item) self.contents[self.addr].append(item) def peek(self): """Returns the top element from the current stack""" if len(self.contents[self.addr]) == 0: return 0 return self.contents[self.addr][-1] def s_up(self): """Moves up 1 stack""" self.addr += 1 if self.addr == len(self.contents): # Top of the stack self.contents.append([]) def s_down(self): """Moves down 1 stack""" self.addr -= 1 def sw_up(self): """Moves the top element off the current stack to the next stack up""" temp = self.contents[self.addr].pop() if self.addr == len(self.contents) - 1: self.contents.append([]) self.contents[self.addr + 1].append(temp) def sw_down(self): """Moves the top element of the current stack to the next stack down""" temp = self.contents[self.addr].pop() self.contents[self.addr - 1].append(temp) def r_up(self): """Moves the bottom element of the current stack to the top""" temp = self.contents[self.addr].pop(0) self.contents[self.addr].append(temp) def r_down(self): """Moves the top element of the current stack to the bottom""" temp = self.contents[self.addr].pop() self.contents[self.addr].insert(0, temp) def repl(self): """Replicate the current stack""" temp = list(self.contents[self.addr]) self.contents.insert(self.addr, temp) def printself(self): """Prints the current stack""" while len(self) > 0: print(self.pop(), end=' ') print() def __repr__(self): return repr(self.contents[self.addr][::-1]) def __len__(self): return len(self.contents[self.addr]) class LaserMachine: """A Laser 'VM' for intepreting a program""" # pylint: disable=too-many-instance-attributes # There's a lot to keep track of def __init__(self, prog, verbose=False, init=None): self.direction = EAST self.memory = LaserStack() self.parse_mode = INSTRUCTION self.current_string = "" self.verbose = verbose lines = prog.split('\n') self.prog = [] self.width = max(map(len, lines)) self.height = len(lines) for line in lines: self.prog.append(list(line.ljust(self.width))) self.program_counter = [0, self.height - 1] if isinstance(init, list): for var in init[::-1]: self.memory.push(var) if verbose: for line in self.prog: print(''.join(line)) self.debug() def debug(self): """Print some debug info""" print(f"addr: {self.memory.addr} - " f"stack: {self.memory}" ) def do_step(self): """Performs a single step of the machine""" i = self.fetch_item() if self.verbose: print(i) if self.parse_mode == RAW: self.process_string(i) elif i in MIRRORS: self.switch_direction(i) elif self.parse_mode == INSTRUCTION: self.process_instruction(i) elif self.parse_mode == STRING: self.process_string(i) x_mov, y_mov = self.direction[0], self.direction[1] self.program_counter[0] += x_mov self.program_counter[1] += y_mov if self.program_counter[0] == self.width: self.program_counter[0] = 0 elif self.program_counter[0] == -1: self.program_counter[0] = self.width - 1 if self.program_counter[1] == self.height: self.program_counter[1] = 0 elif self.program_counter[1] == -1: self.program_counter[1] = self.height - 1 if self.verbose: self.debug() return True def fetch_item(self): """Fetches the character at the current PC""" x_pos = self.program_counter[0] y_pos = self.height - self.program_counter[1] - 1 return self.prog[y_pos][x_pos] def process_instruction(self, i): """ Handle an instruction character """ if i == '"': self.parse_mode = STRING elif i == '`': self.parse_mode = RAW # NULLARY OPERATIONS (NO ARGUMENTS) # elif i in nullary_ops: nullary_ops[i](self) # UNARY OPERATIONS # elif i in unary_ops: temp = self.memory.pop() self.memory.push(unary_ops[i](temp)) # BINARY OPERATIONS # elif i in binary_ops: temp_a = self.memory.pop() temp_b = self.memory.pop() self.memory.push(binary_ops[i](temp_a, temp_b)) # STACK OPERATIONS # elif i in stack_ops: stack_ops[i](self) # TERMINATE elif i == "#": self.memory.printself() sys.exit(0) else: print(f"Instruction {i} unknown!") sys.exit(-1) def process_string(self, i): """Process input while in string mode""" if i in ('"', '`'): self.memory.push(self.current_string) self.current_string = "" self.parse_mode = INSTRUCTION else: self.current_string += i def switch_direction(self, mirror): """Process a mirror and switch direction""" if mirror in CONDITIONALS: if self.memory.peek() != 0: return directions = [NORTH, WEST, SOUTH, EAST] self.direction = mirror_ops[mirror][directions.index(self.direction)] parser = argparse.ArgumentParser(description='Run a LaserLang program.') parser.add_argument("-v", "--verbose", action="store_true", default=False, help="verbose output") parser.add_argument("program", help="Laser program to run") parser.add_argument("input", help="Items to initialize stack with", nargs='*') args = parser.parse_args() with open(args.program, 'r') as f: program = f.read() LM = LaserMachine(program, verbose=args.verbose, init=args.input) while LM.do_step(): pass
#github username: ahal1779 #github email:[email protected] #Ahmed M Alismail import Queue class myQueue(): def __init__(this): this.q = Queue.Queue()#create new Q def putq(this,value): this.q.put(value)#add using the put function def popq(this): while not this.q.empty():# if the queue is not empty print the next value print this.q.get() #Stack class Stack1(): def __init__(this): this.stack1=[] def push(this,i): return this.stack1.append(i)#add a new value to the list stack1 def pop(this): return this.stack1.pop()#pop all values in the list def checkSize(this): return len(this.stack1)#return the length of the list stack1 class Node(): def __init__(this,key): #initiate a new node with the given key but no others this.key=key this.right=None this.left=None this.parent=None def getrightchild(this): return this.right# return the right child def getleftchild(this): return this.left# return the left child def getparent(this): return this.parent#return the parent of this specific node def getkey(this): return this.key# return the key value of this node class BinaryTree(): def __init__(this,key): this.root= Node(key)# intiate the new tree root this.current=this.root# make the current node we are in equal to the root node this.deleted=0# indication if the delete function was successful this.added=0# indication if the add function was successful def add(this,value,parentValue): if this.current.getkey()==parentValue:# is this the parent child if this.current.left==None:# if it has no lef child, add the new node in the left space this.current.left=Node(value) this.current.left.parent=this.current this.added=1# addition was successful return elif this.current.right==None: # if it has a left child but no right child, add the child in the right place this.current.right=Node(value) this.current.right.parent=this.current this.added=1#addition was succesfull return elif this.current.left!=None and this.current.right!=None: print "Parent has two children, node not added"# if the two spaces are taken, then it has two children return # if we didn't find it, go left always if this.current.left:# if it has a left child, go left this.current=this.current.left#change the node we are working on this.add(value,parentValue)# go left # if we are done with all left childs, then start going back and checking right childs if this.current.right:# if we have a right child, go right this.current=this.current.right# change the node we are working on to right nde this.add(value,parentValue)# go right if this.current==this.root:# if we are back to the root if this.added==0:# and we couldn't find the parent node print "Node not found" else: this.added=0# return to defualt state. if this.current.parent:# go back to the parent of the node to keep searching this.current=this.current.parent if this.current==this.root: this.added=0# return to defualt state return def printT(this): if this.current:# if the node we are in is valid print(this.current.getkey())#print the value of this node if this.current.left:# go left all the way to the end printing these values this.current=this.current.left this.printT() if this.current.right:# after finishing left side, check every right side of the node this.current=this.current.right this.printT() if this.current.parent: #if we reached the bottom, then start going back step by step this.current=this.current.parent return def delete(this,value): if this.current.getkey()==value:#did we find the matching key value if this.current.left!=None or this.current.right!=None:#check if it has children, if so, it cannot be deleted print "Node not deleted, has children" return else:#otherwize, delete it and remove it from the parent list if this.current.parent.left.getkey()==value: this.current.parent.left=None else: this.current.parent.right=None this.current=this.current.parent this.deleted=1# delete process was succesfull return if this.current:# if this node is still available if this.current.left:# go left all the way to find the required value this.current=this.current.left this.delete(value) if this.current: if this.current.right:# if we reached the end of the left search, then go right while steping back wards this.current=this.current.right this.delete(value) if this.current==this.root:#if we reached the end and the node is not found print not found if this.deleted==0: print "Not Found" else: this.deleted=0 return if this.current:# go back in order to seach the right nodes if this.current.parent: this.current=this.current.parent return return class Graph(): def __init__(this): this.dic={}# initilaize a new dictionary for the graph this.list1=[]# initilize a temproray list def addVertex(this,value): if this.dic.has_key(value):# is the key found in the dictionary print "Vertex already exists" else:# if not add it with an empty values section dic2={value:[]} this.dic.update(dic2)# add it to the dicitonary return def addEdge(this,value1,value2):# add new edge between two vertices if this.dic.has_key(value1) and this.dic.has_key(value2):# check if the two vertices are present this.dic.get(value1).append(value2)# add each in the others' list this.dic.get(value2).append(value1) else:# if one or two vertices not found, print the follwoing print "One or more vertices not found." return def findVertex(this,value):# search for the vertex if this.dic.has_key(value):# is the value present in the print "Vertices adjecsent to "+value+" are:" for w in this.dic.get(value):# walk through the values adjecsent to the value and print them print(w) else:# if the value not found, print the follwoing print "Vertex Not Found" print "input 1 to test Queue" print "input 2 to test Stack" print "input 3 to test Binary Tree" print "input 4 to test Graph" x=input("input -999 to Quit ") while x!=-999: #Queue Test if x==1: print "Testing the Queue" print "adding 1, 3, 6, 8, 4, 5, 12, 9, 15, 7, 23, 45" que=myQueue() que.putq(1) que.putq(3) que.putq(6) que.putq(8) que.putq(4) que.putq(5) que.putq(12) que.putq(9) que.putq(15) que.putq(7) que.putq(23) que.putq(45) print "poping all values out of the queue" que.popq() #Stack Test if x==2: print "Testing the Stack" print "Adding 1, 3, 6, 8, 4, 5, 12, 9, 15, 7, 23, 45" stack = Stack1() stack.push(1) stack.push(3) stack.push(6) stack.push(8) stack.push(4) stack.push(5) stack.push(12) stack.push(9) stack.push(15) stack.push(7) stack.push(23) stack.push(45) print "\n Checking the size of the values in graph: " print stack.checkSize() print "poping all values out of the stack:" while stack.checkSize()!=0: print stack.pop() elif x==3: #Binary Tree Test print "Testing the Binary Tree" print "Root has value 1" binary=BinaryTree(1) print "Addiing 2 to 1" binary.add(2,1) print "Addiing 3 to 1" binary.add(3,1) print "Addiing 4 to 2" binary.add(4,2) print "Addiing 5 to 2" binary.add(5,2) print "Addiing 6 to 3" binary.add(6,3) print "Addiing 7 to 4" binary.add(7,4) print "Addiing 8 to 6" binary.add(8,6) print "Addiing 9 to 6" binary.add(9,6) print "Addiing 10 to 8" binary.add(10,8) print "Addiing 11 to 7" binary.add(11,7) print "Addiing 12 to 2" binary.add(12,2) print "Addiing 13 to 23" binary.add(13,20) print "Printing Tree" binary.printT() print "Deleting 9 (can be deleted)" binary.delete(9) print "Deleting 11 (can be deleted)" binary.delete(11) print "Deleting 12 (12 was never added to the tree)" binary.delete(12) print "Deleting 3 (3 has two children )" binary.delete(3) print "Deleting 19 (19 was never added to the tree)" binary.delete(19) print "Printing Tree after deleted values" binary.printT() elif x==4: #Graph test print "Testing the Graph" print "adding the vertex: a, b, c, d , e ,f ,g, h, i, j, k, l, m" g=Graph() g.addVertex('a') g.addVertex('b') g.addVertex('c') g.addVertex('d') g.addVertex('e') g.addVertex('f') g.addVertex('g') g.addVertex('h') g.addVertex('i') g.addVertex('j') g.addVertex('k') g.addVertex('l') g.addVertex('m') print "adding edges between: (a,b),(b,c),(c,d),(d,e),(e,f),(f,g),(g,h),(h,i),(i,j),(j,k),(k,l),(l,m),(m,a)" g.addEdge('a','b') g.addEdge('b','c') g.addEdge('c','d') g.addEdge('d','e') g.addEdge('e','f') g.addEdge('f','g') g.addEdge('g','h') g.addEdge('h','i') g.addEdge('i','j') g.addEdge('j','k') g.addEdge('k','l') g.addEdge('l','m') g.addEdge('m','a') print "adding edges between: (a,e),(a,h),(b,j),(c,m),(c,i),(d,g),(e,m),(f,m),(h,k),(i,m)" g.addEdge('a','e') g.addEdge('a','h') g.addEdge('c','m') g.addEdge('c','i') g.addEdge('d','g') g.addEdge('e','m') g.addEdge('f','m') g.addEdge('h','k') g.addEdge('i','m') print "adding edge between: a and z (z is not in the graph)" g.addEdge('z','a') print "adding vertex: n" g.addVertex('n') print "adding edges: (a,n), (n,h)" g.addEdge('a','n') g.addEdge('h','n') print "finding vertex: a" g.findVertex('a') print "finding vertex m" g.findVertex('m') print "finding vertex: c" g.findVertex('c') print "finding vertex: l" g.findVertex('l') print "finding vertex d" g.findVertex('d') print "finding vertex: n" g.findVertex('n') print "\ninput 1 to test Queue" print "input 2 to test Stack" print "input 3 to test Binary Tree" print "input 4 to test Graph" x=input("input -999 to Quit ") print "Thank you have a good day"
import string import random for i in range(0, 3): file = open("file" + str(i) + ".txt", "w") fileText = "" for j in range(0, 10): fileText += random.choice(string.ascii_lowercase) file.write(fileText + "\n") print(fileText) numa = random.randint(1, 42) numb = random.randint(1, 42) print(numa) print(numb) print(numa * numb)
# Um professor quer sortear um dos seus quatro alunos para apagar o quadro. # Faça um programa que ajude ele, lendo o nome dos alunos e escrevendo na tela # o nome do escolhido# import random nome0 = input('Digite um nome: ') nome1 = input('Digite um nome: ') nome2 = input('Digite um nome: ') nome3 = input('Digite um nome: ') escolhido = random.choice([nome0, nome1, nome2, nome3]) print('O aluno escolhido para apagar o quadro foi {}'.format(escolhido))
#Crie um programa que leia um número Real qualquer pelo teclado e mostre na tela a sua porção inteira. import math num = float(input('Digite um número: ')) print("A parte real do número {} é {}".format(num,math.trunc(num)))
# Escreva um programa que leia a velocidade de um carro. # Se ele ultrapassar 80Km/h, mostre uma mensagem dizendo # que ele foi multado. A multa vai custar R$7,00 por # cada Km acima do limite. velocidade = int(input('Digite a velocidade do veículo: ')) if velocidade > 80: multa = (velocidade-80) * 7 print('Você foi multado em ${:.2f} reais!'.format(multa)) else: print('Velocidade OK!')
# Crie um programa que leia o nome completo de uma pessoa e mostre: # O nome com todas as letras maiúsculas e minúsculas. # Quantas letras ao todo (sem considerar espaços). # Quantas letras tem o primeiro nome. nome = input('Nome completo: ').strip() print(nome.upper()) print(nome.lower()) print(len(nome) - nome.count(' ')) print(len(nome.split()[0]))
# Слово по буквам # Демонстрирует применение цикла for к строке word = input("Введите слово: ") print("\nBoт все буквы вашего слова по порядку:") for letter in word : print (letter) input("\n\nHaжмитe Enter. чтобы выйти . ")
name = input("what i your name?\n") age = int(input("your old\n")) weight = int(input("your weight\n")) print("\nyour parametrs", name, weight, age)
# Метрдотель # Демонстрирует условную интерпретацию значений print("Добро пожаловать в Шато-де-Перекуси!") print("Кажется, нынешним вечером у нас все столики заняти. \n") money = int(input ("Сколько долларов вы готовы дать метрдотелю на чай?\n")) if money: print("Прошу прощения, мне сейчас сообщили, что есть один свободный столик. Сюда, пожалуйста.") else: print("Присаживайтесь, будьте добры. Придется подождать.") input("\n\n Нажмите Enter, чтобы выйти.")
#!/usr/bin/env python3 # file: quick_sort.py # auth: Jack Lee # Date: Jan 31, 2017 # Desc: implementation of quick sort algorithm # https://en.wikipedia.org/wiki/Quicksort # import random # # func: partition(array, low, high) # desc: find the pivot for the array to quick sort # on the left of pivot, less # para: a - the array to be sort # lo - start index of the array, inclusive # hi - end index of the array, inclusive # ret : pivot of the array, left of pivot, less than pivot, # def partition(a, lo, hi): pivot = a[hi] i = lo # place for swapping # for j := lo to hi - 1 do for j in range(lo, hi): if a[j] <= pivot: a[i], a[j] = a[j], a[i] # swap A[i] with A[j] i += 1 a[i], a[hi] = a[hi], a[i] # swap A[i] with A[hi] return i # # func: quick_sort(array, lo, hi) # desc: implementation of quick sort algorithm in Python # para: a - the array to be sort # lo - start index of the array, inclusive # hi - end index of the array, inclusive # ret : the sorted array # def quick_sort(a, lo, hi): if lo < hi: p = partition(a, lo, hi) quick_sort(a, lo, p - 1) quick_sort(a, p + 1, hi) return a # # func: gen_rand_list(numbers of random ) # desc: generate random number of list with bubble sort algorithm # para: number - how many numbers of random will be generated # def gen_rand_list(number): a = [] # null list for i in range(number): a.append(random.randrange(number * 2)) # range will be 0 to 2 * number return a # test program if __name__ == '__main__': n = eval(input("input numbers of rand you want to generate:")) l = gen_rand_list(n) print(l) print(quick_sort(l, 0, len(l) - 1))
# YouTube Video: https://youtu.be/6qo3ly3-_I8 # Gets the first name from the the full name string fullname = "John Jacob" # Start from position 0(first position of string) # Stop before position 4 firstname = fullname[0:4] # Print the first name print (firstname)
# example = 'test' # 'a' -> 'b' # # ord() # String -> 'test' # ASCII -> ord('a') = 97 # for Loop # chr(97) = a #userInput = input("String to encrypt: ") userInput = 'abc' encryptedOutput = '' incBy = input("Increment by? ") incBy = '1' # isDig = '22'.isdigit() # print(isDig) key = int(incBy) print("actualInput:", userInput) for ch in userInput: asc = ord(ch) asc = asc + key newCh = chr(asc) encryptedOutput = encryptedOutput + newCh print("Encrypted user input:", encryptedOutput) # Receiving End decryptedOutput = '' for ch in encryptedOutput: asc = ord(ch) asc = asc - key newCh = chr(asc) decryptedOutput = decryptedOutput + newCh print("Receiver Output: ", decryptedOutput) # def encrypt(text, key, mode): # place function content here! choice = input("e/d?") if True: # decrypt else: pass
# # # x = [3,2,1] # # # # x.__sizeof__() # # # # if 2 in x: # # # # print(x.index(2)) if 2 in x # # # x.append(4) # # # x.extend([1,2,3]) # # # x.insert(0, 9) # # # x.remove(3) # # # x.pop(1) # # # print(x.count(1)) # # # # x=[] # # # # x.extend(['a','x']) # # # # print(x.index(9,0, 9)) # # # # x.clear() # # # x.reverse() # # # y = x.copy() # # # print(len(x)) # # # # x.sort(reverse=True) # # # print(x) # # # print(list((1,2,3,4,5,6,7))) # # # print(max([2,3,1,9,18,2,4])) # # x = divmod(11, 5) # # print(x) # # a= '22.0' # # print(a.isdecimal()) # # print(a.isdigit()) # # print(a.isnumeric()) # # print(a.isalnum()) # # string = 'hey sofsf dfd how ate you' # # print(string[2:16]) # # # print(string) # # print(2*"Ok ") # # print(bin(2)) # a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] # b = [item for item in a if item<10] # print(b) # counter = 1 # while (counter < 10): # print (counter) # counter = counter +1 # print(ascii('a')) # print(sum([2,3,4,5,7])) # # print(set([1,2,3,4,5])) # x = [1,2,4,17,5,9] # a = sorted(x) # print(a)
from collections import namedtuple individual = namedtuple("ndividual", "name age height") user = individual(name="Homer", age=37, height=178) print(user) # print(user[name])
import sqlite3 import uuid #アカウント管理 class AccountDao: dbname = 'account.db' def __init__(self): conn = sqlite3.connect(self.dbname) cur = conn.cursor() # アカウント管理テーブル cur.execute("CREATE TABLE IF NOT EXISTS account(id, name, password);") conn.commit() conn.close() # アカウント作成 def create_account(self, user, password): import uuid conn = sqlite3.connect(self.dbname) cur = conn.cursor() uid = uuid.uuid4() print(uid) if self.is_account(user, password): return "Error" else: pass cur.execute("INSERT INTO account VALUES (?,?,?);", (str(uid), str(user), str(password),)) conn.commit() conn.close() # アカウント認証 def is_account(self, user, password): import uuid conn = sqlite3.connect(self.dbname) cur = conn.cursor() cur.execute("SELECT name FROM account WHERE name=? AND password=?;", (user, password,)) result = cur.fetchall() conn.close() if len(result) != 0: return True else: return False def is_exist_user(self, user): conn = sqlite3.connect(self.dbname) cur = conn.cursor() cur.execute("SELECT name FROM account WHERE name=?;", (user,)) result = cur.fetchall() conn.close() if len(result) != 0: return True else: return False # アカウント全件取得 def get_all_account(self): conn = sqlite3.connect(self.dbname) cur = conn.cursor() cur.execute("SELECT * FROM account;") result = cur.fetchall() conn.close() return result # メッセージIO管理 class MessageDao: dbname = 'messages.db' def __init__(self): conn = sqlite3.connect(self.dbname) cur = conn.cursor() cur.execute("CREATE TABLE IF NOT EXISTS messages(m_from, m_to, message, date);") conn.commit() conn.close() def get_message_by_name(self, username): conn = sqlite3.connect(self.dbname) cur = conn.cursor() cur.execute("SELECT * FROM messages WHERE m_to = ? OR m_from = ?;", (username, username, )) result = cur.fetchall() r = [{"from": x[0], "to": x[1], "message": x[2], "date": x[3]} for x in result] conn.close() return r def set_message(self, message): if not message.get('from', False) and message.get('to', False) and message.get('date', False) and message.get('message', False): return "Error" conn = sqlite3.connect(self.dbname) cur = conn.cursor() cur.execute( "INSERT INTO messages VALUES (?,?,?,?);", (message['from'], message['to'], message['message'], str(message['date'])) ) conn.commit() conn.close() def get_message(self): conn = sqlite3.connect(self.dbname) cur = conn.cursor() cur.execute("SELECT * FROM messages;") result = cur.fetchall() conn.close() return result # フレンドリスト管理 class FriendDao: dbname = 'account.db' def __init__(self): conn = sqlite3.connect(self.dbname) cur = conn.cursor() cur.execute("CREATE TABLE IF NOT EXISTS friends(my_user, your_user);") conn.commit() conn.close() # 友人リスト取得 def get_friend_list(self, username): conn = sqlite3.connect(self.dbname) cur = conn.cursor() cur.execute("SELECT * FROM friends WHERE my_user = ? ;", (username,)) result = cur.fetchall() conn.close() return result # 友人リスト登録 def set_friend_list(self, from_user, to_user): conn = sqlite3.connect(self.dbname) cur = conn.cursor() cur.execute("INSERT INTO friends VALUES (?,?);", (from_user, to_user,)) conn.commit() conn.close() if __name__ == "__main__": a = AccountDao() print(a.get_all_account()) b = MessageDao() for x in range(10): m = { "from": "thirao2", "to": "thirao", "message": "てすと", "date": str(1523348346672 + x) } b.set_message(m) # print(b.set_message(m)) print(b.get_message())
hours = int(input()) minutes = int(input()) if hours > 12: hours %= 12 if minutes > 60: minutes %= 60 if hours == 12: hours = 0 if minutes == 60: minutes = 0 degreesPerCircle = 360 degreesPerHour = degreesPerCircle / 12 degreesPerMinute = degreesPerCircle / 60 allDegreesInHours = hours * degreesPerHour allDegreesInMinutes = minutes * degreesPerMinute if allDegreesInHours >= allDegreesInMinutes: theAngleBetweenPoints = (allDegreesInHours + allDegreesInMinutes/12) - allDegreesInMinutes if allDegreesInMinutes > allDegreesInHours: theAngleBetweenPoints = allDegreesInMinutes - (allDegreesInHours + allDegreesInMinutes / 12) if theAngleBetweenPoints > 180: theAngleBetweenPoints = degreesPerCircle - theAngleBetweenPoints print(float(theAngleBetweenPoints), end=' ' + 'degrees between points')
str1 = "Yush" str2 = "contributes in" str3 = "Hacktoberfest2021" # Type-1 concat = str1 +" " +str2 +" "+str3 print(type(concat)) print(concat) # Type-2 concat1 = " ".join((str1,str2,str3)) print(type(concat1)) print(concat1)
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of Advent of Code 2020 # https://github.com/scorphus/advent-of-code-2020 # Licensed under the BSD-3-Clause license: # https://opensource.org/licenses/BSD-3-Clause # Copyright (c) 2020, Pablo S. Blum de Aguiar <[email protected]> from aoc import integers from importlib import import_module import subprocess import sys def aoc(): try: day, part, *_ = integers(sys.argv[-1].split(".")) except (IndexError, IOError, ValueError): print("Try: `aoc < input/day01 1.1` or `aoc input/day07 7.2`") exit(1) day_part = import_day_part(day, part) if sys.stdin.isatty(): with open(sys.argv[-2]) as input_file: answer = day_part(input_file) else: answer = day_part(sys.stdin) if not answer: print(f"⛔️ answer is {answer}") exit(1) copy_to_clipboard(f"{answer}".encode()) print(f"Your answer is: {answer} (already copied to clipboard)") def import_day_part(day, part): day = import_module(f"aoc.day{day:02d}") return getattr(day, f"part{part}", None) def copy_to_clipboard(text): subprocess.run("pbcopy", input=text)
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of Advent of Code 2020 # https://github.com/scorphus/advent-of-code-2020 # Licensed under the BSD-3-Clause license: # https://opensource.org/licenses/BSD-3-Clause # Copyright (c) 2020, Pablo S. Blum de Aguiar <[email protected]> import collections import graphlib def part1(lines): graph = {} for line in lines: bag, bags = parse_line(line) for _, each_bag in bags: graph.setdefault(each_bag, []).append(bag) visited = bfs(graph, "shiny gold") return len(visited) - 1 def part2(lines): graph = {} bags_in_bag = {} for line in lines: bag, bags = parse_line(line) graph[bag] = set(b for _, b in bags) bags_in_bag[bag] = bags qtt_acc = {} for bag in graphlib.TopologicalSorter(graph).static_order(): total = 1 for qtt, bag_in in bags_in_bag[bag]: total += qtt * qtt_acc[bag_in] qtt_acc[bag] = total if bag == "shiny gold": return qtt_acc[bag] - 1 def parse_bags(bags): bag_list = [] for bag in bags.split(", "): qtt, shade, color, _ = bag.split(maxsplit=3) bag_list.append((int(qtt), f"{shade} {color}")) return bag_list def parse_line(line): if " contain no " not in line: bag, bags = line.strip().split(" bags contain ") else: bag, _ = line.strip().split(" bags contain ") bags = None return bag, parse_bags(bags) if bags else [] def bfs(bags, start): visited = {start} next_bags = collections.deque([start]) while next_bags: bag = next_bags.popleft() if bag not in bags: continue for next_bag in bags[bag]: if next_bag not in visited: next_bags.append(next_bag) visited.add(next_bag) return visited
# #1 задача def print_my_name(my_name): print(my_name) print_my_name("kirill") #2 задача 3 задача def calculator(num1, num2, action): if action == "+": result = num1 + num2 print(result) elif action == "-": result = num1 - num2 print(result) elif action == "/": result = num1 / num2 print(result) elif action == "*": result = num1 * num2 print(result) action = input("Input action ") calculator(5, 2, action) #4 задача def even_number(num): if num % 2==0: print("акція діє") else: print("Акція не діє") even_number( int(input("input number: "))) # 5 задача def print_list(l): print(l) names = ["Ярослав", "Богдан", "Катя"] print_list(names) #6 задача names.append ("Євген") print(names) #7 задача def is_evgen(names): if "Євген" in names: print("у списку є ім'я Євген") else: print("у списку немає ім'я Євген") is_evgen(names)
# 1 задача presents = {"скейтборд", "футболку", "рюкзак", "цукерки (5 кг)", "мандарини"} for i in presents: if i == "скейтборд": print("так скейтборд є") # 2 задача money = {100, 200, 150, 300} sum_ = sum(money) mod_money = 200 all_money = sum_ + mod_money print (all_money) # 3 задача gomer = {"Піцу", "Премію на роботі", "Касети з всіма випусками Клоуна Красті", "Шоколад"} ned = {"Інструменти для лівшів", "Зелений чай", "Шоколад"} for i in gomer: if i in ned: print (i) # 4 задача svichky = "happy birsday" for i in svichky: print (i) # 5 задача names = ["Род", "Тод", "Мод", "Нед"] for i in names: if "М" in i: print (i) # 6 задача zgadav = "я згадав що нед мені не віддав газонокосилку" if "газон" in zgadav: print("гомер подумав про газон") # 7 задача. В завданні є помилка: субота це Saturday, а не Sunday. Перевіряємо на Saturday. import datetime x = datetime.datetime.now() print("tooday is", x.strftime("%A")) if x.strftime("%A") == "Saturday": print("привіт субота") else: print("НІІІІІ, хочу суботу") # 8 задача import datetime x = datetime.datetime.now() print(x.strftime("%m/%d/%y")) # 9 задача import datetime x1=datetime.datetime.now() x0=datetime.datetime(x1.year,x1.month,x1.day) diff = x1 - x0 print(diff.seconds) print(diff.seconds / 60)
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def postorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ result = [] stack = [] curNode = root while stack or curNode: while curNode: stack.append(curNode) curNode = curNode.left if curNode.left else curNode.right curNode = stack.pop() result.append(curNode.val) if stack and stack[-1].left == curNode: curNode = stack[-1].right else: curNode = None return result
#%% from abc import ABCMeta, abstractmethod # %% class Context(metaclass=ABCMeta): """the context of envirnment class in state pattern""" def __init__(self): self._states = [] self._curState = None # the attribute that state depends on as changing # set this variable as a single class when it is decided by multiple variables self._stateInfo = 0 def addState(self, state): if (state not in self._states): self._states.append(state) def changeState(self, state): if (state is None): return False if (self._curState is None): print("initial as ", state.getName()) else: print("from", self._curState.getName(), "to", state.getName()) self._curState = state self.addState(state) return True def getState(self): return self._curState def _setStateInfo(self, stateInfo): self._stateInfo = stateInfo for state in self._states: if (state.isMatch(stateInfo)): self.changeState(state) def _getStateInfo(self): return self._stateInfo #%% class State: """basic class of states""" def __init__(self, name): self._name = name def getName(self): return self._name def isMatch(self, stateInfo): "check if the stateInfo attribute is in the state._curState" return False @abstractmethod def behavior(self, context): pass
# -*- coding: utf-8 -*- """ CS231n http://cs231n.github.io/ """ import numpy as np from itertools import product """The implementation of KNN given below uses the following numpy functions: * np.bincount * np.argmax * np.argpartition https://stackoverflow.com/questions/34226400/find-the-k-smallest-values-of-a-numpy-array Additionally, KNN uses division of X_train into batches during "no loop" computations in order not to exceed memory limit provided to constructor in parameter "memory_threshold".""" class KNearestNeighbor(object): """ a kNN classifier with L2 distance """ def __init__(self, copy=False, memory_threshold=512): self.copy = copy self._distance_calculators = {0: self.compute_distances_no_loops, 1: self.compute_distances_one_loop, 2: self.compute_distances_two_loops} self.memory_threshold=memory_threshold # [Mb] def fit(self, X, y): self.train(X, y) def train(self, X, y): """ Train the classifier. For k-nearest neighbors this is just memorizing the training data. Inputs: - X: A numpy array of shape (num_train, D) containing the training data consisting of num_train samples each of dimension D. - y: A numpy array of shape (N,) containing the training labels, where y[i] is the label for X[i]. """ assert isinstance(X, np.ndarray) assert isinstance(y, np.ndarray) assert len(X.shape) == 2 assert len(y.shape) == 1 assert X.shape[0] == y.shape[0] if self.copy: self.X_train = np.array(X) self.y_train = np.array(y) else: self.X_train = X self.y_train = y self.train_size, self.n_dim = self.X_train.shape def predict(self, X, k=1, num_loops=0): """ Predict labels for test data using this classifier. Inputs: - X: A numpy array of shape (num_test, D) containing test data consisting of num_test samples each of dimension D. - k: The number of nearest neighbors that vote for the predicted labels. - num_loops: Determines which implementation to use to compute distances between training points and testing points. Returns: - y: A numpy array of shape (num_test,) containing predicted labels for the test data, where y[i] is the predicted label for the test point X[i]. """ assert k > 0 assert num_loops in self._distance_calculators dists = self.compute_distances(X, num_loops=num_loops) return self.predict_labels(dists, k=k) def compute_distances(self, X, num_loops=0): """ Compute the distance between each test point in X and each training point in self.X_train using a nested loop over both the training data and the test data. Inputs: - X: A numpy array of shape (num_test, D) containing test data. Returns: - dists: A numpy array of shape (num_test, num_train) where dists[i, j] is the Euclidean distance between the ith test point and the jth training point. """ assert isinstance(X, np.ndarray) assert len(X.shape) == 2 assert X.shape[1] == self.n_dim self.dists = self._distance_calculators[num_loops](X) assert self.dists.shape == (X.shape[0], self.train_size) return self.dists def compute_distances_two_loops(self, X): test_size = X.shape[0]; train_size = self.train_size dists = np.zeros((test_size, train_size)) for i, j in product(range(test_size), range(train_size)): dists[i, j] = np.sum((X[i] - self.X_train[j])**2) return dists def compute_distances_one_loop(self, X): test_size = X.shape[0]; train_size = self.train_size dists = np.zeros((test_size, train_size)) for i in range(test_size): dists[i, :] = np.sum((self.X_train - X[i][None, :])**2, axis=1) return dists def compute_distances_no_loops(self, X): batch_size = self._get_batch_size(X) assert X.shape[1] == self.n_dim test_size = X.shape[0] dists = [] X = X[:, None, :] # (test_size x 1 x D) X2 = (X**2).sum(axis=2, keepdims=True) # (test_size x 1 x 1) assert X2.shape == (X2.shape[0], 1, 1) for i in range(0, self.train_size, batch_size): j = min(i + batch_size, self.train_size) X_train_batch = self.X_train[i:j][None, :, :] # (1 x batch_size x D) assert X_train_batch.shape == (1, j - i, self.n_dim) X_train_batch2 = (X_train_batch**2).sum(axis=2, keepdims=True) # (1 x train_size x 1) assert X_train_batch2.shape == (1, j - i, 1) ds = X2 + X_train_batch2 - 2 * np.sum(X * X_train_batch, axis=2, keepdims=True) assert ds.shape == (test_size, j - i, 1) dists.append(ds[:,:,0]) dists = np.hstack(dists) return dists def _get_batch_size(self, X): test_size = X.shape[0] temp = 1.0 * self.n_dim * test_size * X.dtype.type(0).nbytes / 2 ** 20 batch_size = int(self.memory_threshold / temp) batch_size = max(1, min(self.train_size, batch_size)) self.batch_size = batch_size return batch_size def predict_labels(self, dists, k=1): """ Given a matrix of distances between test points and training points, predict a label for each test point. Inputs: - dists: A numpy array of shape (num_test, num_train) where dists[i, j] gives the distance betwen the ith test point and the jth training point. Returns: - y: A numpy array of shape (num_test,) containing predicted labels for the test data, where y[i] is the predicted label for the test point X[i]. """ test_size = dists.shape[0] y_pred = np.zeros(test_size) A = np.argpartition(dists, kth=k - 1, axis=1); assert A.shape == dists.shape labels = self.y_train[A[:, :k]] def find_most_common(arr): return np.argmax(np.bincount(arr)) y_pred = np.apply_along_axis(find_most_common, 1, labels) assert y_pred.shape == (test_size,) return y_pred
# -*- coding: utf-8 -*- import numpy as np from .layers import * class FullyConnectedNet: """ A fully-connected neural network with an arbitrary number of hidden layers, ReLU nonlinearities, and a softmax loss function. This will also implement dropout and batch normalization as options. For a network with L layers, the architecture will be {affine - [batch norm] - relu - [dropout]} x (L - 1) - affine - softmax where batch normalization and dropout are optional, and the {...} block is repeated L - 1 times. Similar to the TwoLayerNet above, learnable parameters are stored in the self.params dictionary and will be learned using the Solver class. """ def __init__(self, hidden_dims, input_dim=3*32*32, num_classes=10, use_relu=True, dropout=0, use_batchnorm=False, reg=0.0, weight_scale=1e-2, dtype=np.float64, seed=None, debug=False, keep_seed=False): """ Initialize a new FullyConnectedNet. Inputs: - hidden_dims: A list of integers giving the size of each hidden layer. - input_dim: An integer giving the size of the input. - num_classes: An integer giving the number of classes to classify. - dropout: Scalar between 0 and 1 giving dropout strength. If dropout=0 then the network should not use dropout at all. - use_batchnorm: Whether or not the network should use batch normalization. - reg: Scalar giving L2 regularization strength. - weight_scale: Scalar giving the standard deviation for random initialization of the weights. - dtype: A numpy datatype object; all computations will be performed using this datatype. float32 is faster but less accurate, so you should use float64 for numeric gradient checking. - seed: If not None, then pass this random seed to the dropout layers. This will make the dropout layers deteriminstic so we can gradient check the model. """ self.use_relu = use_relu self.use_batchnorm = use_batchnorm self.use_dropout = dropout > 0 self.reg = reg self.dtype = dtype self.params = {} self.random = np.random.RandomState(seed) prev_output_dim = input_dim # Размерность выхода предыдущего слоя hidden_dims += [num_classes] # Добавляем последний affine-слой self.num_layers = len(hidden_dims) # L for n_layer in range(self.num_layers): input_dim = prev_output_dim output_dim = hidden_dims[n_layer] W = self.random.rand(input_dim, output_dim) b = np.zeros(output_dim) if weight_scale is None: W *= 1 / np.sqrt(input_dim) else: W *= weight_scale W_name = 'W' + str(n_layer); b_name = 'b' + str(n_layer) self.params[W_name] = W self.params[b_name] = b prev_output_dim = output_dim if debug: print('{}: {}'.format(W_name, W.shape)) print('{}: {}'.format(b_name, b.shape)) if use_batchnorm & (n_layer < self.num_layers - 1): self.params['gamma' + str(n_layer)] = np.ones(output_dim) self.params['beta' + str(n_layer)] = np.zeros(output_dim) self.dropout_param = {} if self.use_dropout: self.dropout_param = {'mode': 'train', 'p': dropout, 'gen': self.random} if keep_seed: self.dropout_param['seed'] = seed self.bn_params = [] if self.use_batchnorm: self.bn_params = [{'mode': 'train'} for i in range(self.num_layers - 1)] # Cast all parameters to the correct datatype for k, v in self.params.items(): self.params[k] = v.astype(dtype) def loss(self, X, y=None): """ Compute loss and gradient for the fully-connected net. Input / output: Same as TwoLayerNet above. """ X = X.astype(self.dtype) mode = 'test' if y is None else 'train' # Set train/test mode for batchnorm params and dropout param since they # behave differently during training and testing. if self.use_dropout: self.dropout_param['mode'] = mode if self.use_batchnorm: for bn_param in self.bn_params: bn_param['mode'] = mode scores = None self.caches = {} X_out = X for n_layer in range(self.num_layers - 1): caches = {} W = self.params['W' + str(n_layer)] b = self.params['b' + str(n_layer)] cache_name = 'aff' + str(n_layer) X_out, caches[cache_name] = affine_forward(X_out, W, b) if self.use_batchnorm: gamma = self.params['gamma' + str(n_layer)] beta = self.params['beta' + str(n_layer)] cache_name = 'bn' + str(n_layer) X_out, caches[cache_name] = batchnorm_forward(X_out, gamma, beta, self.bn_params[n_layer]) if self.use_relu: cache_name = 'relu' + str(n_layer) X_out, caches[cache_name] = relu_forward(X_out) if self.use_dropout: cache_name = 'dropout' + str(n_layer) X_out, caches[cache_name] = dropout_forward(X_out, self.dropout_param) if mode == 'train': for k, v in caches.items(): self.caches[k] = v W, b = self.params['W' + str(self.num_layers - 1)], self.params['b' + str(self.num_layers - 1)] X_out, aff_cache = affine_forward(X_out, W, b) if mode == 'train': self.caches['aff' + str(self.num_layers - 1)] = aff_cache scores = X_out # If test mode return early if mode == 'test': return scores ############################################################################ # When using dropout, you'll need to pass self.dropout_param to each # # dropout forward pass. # # # # When using batch normalization, you'll need to pass self.bn_params[0] to # # the forward pass for the first batch normalization layer, pass # # self.bn_params[1] to the forward pass for the second batch normalization # # layer, etc. # ############################################################################ grads = {} loss, output_grad = softmax_loss(scores, y) output_grad, dW, db = affine_backward(output_grad, self.caches['aff' + str(self.num_layers - 1)]) W = self.params['W' + str(self.num_layers - 1)] grads['W' + str(self.num_layers - 1)] = dW + self.reg * W grads['b' + str(self.num_layers - 1)] = db loss += 0.5 * self.reg * np.sum(W ** 2) for n_layer in reversed(range(self.num_layers - 1)): if self.use_dropout: output_grad = dropout_backward(output_grad, self.caches['dropout' + str(n_layer)]) if self.use_relu: output_grad = relu_backward(output_grad, self.caches['relu' + str(n_layer)]) if self.use_batchnorm: output_grad, dgamma, dbeta = batchnorm_backward(output_grad, self.caches['bn' + str(n_layer)]) grads['gamma' + str(n_layer)] = dgamma grads['beta' + str(n_layer)] = dbeta output_grad, dW, db = affine_backward(output_grad, self.caches['aff' + str(n_layer)]) W = self.params['W' + str(n_layer)] grads['W' + str(n_layer)] = dW + self.reg * W grads['b' + str(n_layer)] = db loss += 0.5 * self.reg * np.sum(W ** 2) return loss, grads
def my_prime(n): for i in range(2,n): if n%i==0: return False else: return True number1=int(input('Enter number1: ')) number2=int(input('Enter number2: ')) for i in range(number1,number2+1): if my_prime(i)==True: print(i,end=',')
array=[] size = int(input('Enter array size : ')) for i in range(size): inp = int(input("Enter arr[%d] : " %(i))) array.append(inp) searchnum = int(input("Enter num to be searched : ")) flag=0 for i in range(len(array)): if(array[i] == searchnum): index=i flag=1 if(flag == 0): print("not found") else: print("Element found at %d" %index)
from operator import itemgetter class Book: """Книга""" def __init__(self, id, title, autor, price, store_id): self.id = id self.title = title self.autor = autor self.price = price self.store_id = store_id class Store: """Книжный магазин""" def __init__(self, id, name): self.id = id self.name = name class BookStore: """'Книги книжного магазина' для реализации связи многие-ко-многим""" def __init__(self, store_id, book_id): self.store_id = store_id self.book_id = book_id # Книжные магазины stores = [ Store(1, 'Читай-город'), Store(2, 'Книжный лабиринт'), Store(3, 'Московский Дом Книг'), ] # Книги books = [ Book(1, 'Война и мир Том 1-2', 'Толстой', 110, 1), Book(2, 'Фицджеральд', 'Скотт', 138, 2), Book(3, '451 по Фаренгейту', 'Брэдбери', 217, 3), Book(4, '1984', 'Оруэлл', 196, 1), Book(5, 'Мы', 'Замятин', 138, 2), Book(6, 'Война и мир Том 3-4', 'Толстой', 119, 3), ] store_book = [ BookStore(1, 1), BookStore(2, 2), BookStore(3, 3), BookStore(1, 4), BookStore(2, 5), BookStore(3, 6) ] def main(): """Основная функция""" one_to_many = [(b.title, b.price, s.name) for s in stores for b in books if b.store_id == s.id] many_to_many_temp = [(s.name, bs.store_id, bs.book_id) for s in stores for bs in store_book if s.id == bs.store_id] many_to_many = [(b.title, store_name) for store_name, store_id, book_id in many_to_many_temp for b in books if b.id == book_id] print('Задание А1') res_11 = list(filter(lambda x: x[0].startswith('В'), one_to_many)) print(res_11) print('\nЗадание А2') res_12_unsorted = [] for s in stores: s_books = list(filter(lambda i: i[2] == s.name, one_to_many)) if len(s_books) > 0: s_price = [price for _, price, _ in s_books] s_price_min = min(s_price) res_12_unsorted.append((s.name, s_price_min)) res_12 = sorted(res_12_unsorted, key=itemgetter(1), reverse=False) print(res_12) print('\nЗадание А3') res_13 = sorted(many_to_many, key=itemgetter(0)) print(res_13) if __name__ == '__main__': main()
#!/usr/bin/env python def quicksort(lista, inicio, fim): if(inicio < fim): pivor = particionamento(lista, inicio, fim) # print("{}".format(pivor)) quicksort(lista, inicio, pivor) quicksort(lista, pivor+1, fim) def particionamento(lista, inicio, fim): x, y, pivor, temp = inicio, fim, lista[inicio], -1 while True: while lista[x] < pivor and pivor != lista[x]: x += 1 while lista[y] > pivor and pivor != lista[y]: y -= 1 if x < y: temp = lista[x] lista[x] = lista[y] lista[y] = temp else: return y elementos = [5, 1, 6, 2, 4, 3] print ("List Before: %s" % elementos) quicksort(elementos,0,5) print ("List After: %s" % elementos) print u"Worst: {}, Best: {}, Average: {}, Space: {}".format("O(n elevado a 2)", "O (n log n)", "O( n log n)", "O( n log n)")
from vector import Vector from operation import cross def vertical(v1,v2): # get the vector is vertical to the plane determined by v1 and v2 # if v1 and v2 can not determine a plane, return unit vector c = cross(v1,v2).normalize() if c.length() > 0: return c return Vector(1,0,0)
"""" This analysis is mostly interesting when we start to handle inheritance. It is a more trivial case than __dict__ in datalog we can recognize when there is an assignment to the bases field and the baseHeap is a class. However we need a way to deal with tuples in our analysis. """ class Pair(object): def __init__(self, fst, snd) -> None: super().__init__() self.fst = fst self.snd = snd class StupidPair(object): def __init__(self, fst, snd) -> None: super().__init__() self.fst = snd self.snd = fst class Tripple(Pair): def __init__(self, fst, snd, trd) -> None: super().__init__(fst, snd) self.trd = trd y = Tripple(1,2,3) Tripple.__bases__ = (StupidPair,) x = Tripple(1,2,3) print(Tripple.__bases__) print(x.fst) print(x.snd) print(x.trd) print(y.fst) print(y.snd) print(y.trd)
# Use a stack to check whether a string has balanced usage of parentheses and brackets # Balanced: {([()])} # Not Balanced: {([())}] # Could alternatively import the stack created in stack_example.py # from stack_example import Stack class Stack(): def __init__(self): self.items = [] def push(self, value): self.items.append(value) def pop(self): return self.items.pop() def get_stack(self): return self.items # peek at top of stack def peek(self): return self.items[-1] def isMatch(p1, p2): if p1 == '(' and p2 == ')': return True elif p1 == '[' and p2 == ']': return True elif p1 == '{' and p2 == '}': return True else: return False def is_paren_balanced(paren_string): # initialize a stack # loop through the string # if the current element is an opening paren — ([{ — push to the stack # if the current element is a closing paren — )]} — and the last stack element is a matching open parens, pop the open parens off the stack and keep moving # else, return false # return true at the end stack = Stack() for el in paren_string: if el in '([{': stack.push(el) elif isMatch(stack.peek(), el): stack.pop() else: return False return True print(is_paren_balanced('{([())}]')) # False print(is_paren_balanced('{([()])}')) # True
from urllib.request import urlopen from bs4 import BeautifulSoup import tkinter as tk from datetime import date def get_price(): ''' Gets The Current Bitcoin Price From The Website ''' url = "https://www.coindesk.com/price/bitcoin" page = urlopen(url) html_bytes = page.read() html = html_bytes.decode("utf-8") soup = BeautifulSoup(html, "html.parser") Html_tag = soup.find_all("div", {"class": "price-large"}) Tag_String = str(Html_tag) BitCoin_Price = Tag_String[55:64] print(f"${BitCoin_Price}") return BitCoin_Price window = tk.Tk() window.geometry("200x100") window.title("BitCoin Price Checker") Today_date = date.today() label = tk.Label(window, text=f"The Bitcoin Price as of {Today_date}").pack() pricelabel = tk.Label(window, text=f"$ {get_price()}").pack() window.mainloop()
class A: pass a = A() print(a.__class__) # <class '__main__.A'> 实例化对象是由类创建出来的 print(A.__class__) # <class 'type'>类是由type即元类创建出来的 num = 10 print(num.__class__) # <class 'int'> 10是由int 类创建出来的 print(int.__class__) # <class 'type'>int类也是由元类创建出来 的 l = "oooo" print(l.__class__) # <class 'str'> print(str.__class__) #<class 'type'>
def f(x): while x > 3: f(x + 1) print x def Square(x): return SquareHelper(abs(x), abs(x)) def SquareHelper(n, x): if n == 0: return 0 return SquareHelper(n-1, x) + x def evalQuadratic(a, b, c, x): return a * x * x + b * x + c def twoQuadratics(a1, b1, c1, x1, a2, b2, c2, x2): return evalQuadratic(a1, b1, c1, x1) + evalQuadratic(a2, b2, c2, x2) def primesList(N): def isPrime(n): for divisor in range(2, n): if n % divisor == 0: return False return True primes = [] for number in range (2, N + 1): if isPrime(number): primes.append(number) return primes def count7(N): if len(str(N)) <= 1: if str(N) == "7": return 1 else: return 0 else: return count7(str(N)[0]) + count7(str(N)[1:]) def uniqueValues(aDict): uniquesList = [] for key in aDict: if aDict.values().count(aDict[key]) == 1: uniquesList.append(key) return uniquesList def satisfiesF(L): toRemove = [] for elt in L: if not f(elt): toRemove.append(elt) for elt in toRemove: L.remove(elt) return len(L) #run_satisfiesF(L, satisfiesF) def f(s): return 'a' in s L = ['a', 'b', 'a'] print satisfiesF(L) print L
import wikipedia as wiki from random import randint # Option 1: Downloaded https://github.com/daxeel/TinyURL-Python # change urllib2 to urllib3 in the tinyurl.py file and install using # python3 setup.py install # Didn't work #import tinyurl # Option 2: Download https://github.com/IzunaDevs/TinyURL # Edit the file setup.py and remove the line packages=['TinyURL'] # install fails: Install using sudo python3 setup.py install # Didn't work # Option 3: worked; Copy the file TinyURL.py file from IzunaDevs's git to working directory # so copy the directory to the working directory import TinyURL as tinyurl # pickle can dump a list to a file, and load import pickle # sys lets you use argv import sys allowedTypes = ['theorems','lemmas','inequalities' ] if len(sys.argv) == 1: randomType = randint(0,2) # debug here #randomType = 0 print ('No type specified. Assuming random type:', allowedTypes[randomType]) fileName = allowedTypes[randomType]+'List.dat' elif sys.argv[1] not in allowedTypes: print ('Usage: python filename.py [theorems | lemmas | inequalities ]') exit(1) else: fileName=sys.argv[1]+'List.dat' # e.g. theoremsList.dat links = pickle.load(open(fileName,'rb')) # Need to open in binary to read unicode randomNumber =randint(0,len(links)-1) # debug here #randomNumber = 51 print (randomNumber) randomTitle = links[randomNumber] # Random title print (randomTitle) # Get summary of the randomTitle for first 150 chars articleSummary = wiki.summary(title = randomTitle, sentences=2) #articleSummary = wiki.summary(title = randomTitle) articleLink = wiki.page(randomTitle).url # produce the tinyurl #tinyLink = tinyurl.shorten(articleLink,"") tinyLink = tinyurl.create_one(articleLink) tinierLink = tinyLink.split('//')[1] #break the string at // and use the second part, which is indexed as [1] #print (tinyLink) #print (tinierLink) #num = 140 - len(tinierLink) - 7 # This number seems optimum based on the behaviour of twitter num = 280 - len(tinierLink) - 5 # This number seems optimum based on the behaviour of twitter #num = 280 - len(tinierLink) - 7 # This number seems optimum based on the behaviour of twitter #num = 280 - 7 # This number seems optimum based on the behaviour of twitter body = articleSummary[:num] #print('Summary: ' + body) if body.partition(' ')[0] == "In": firstChunk = body.partition(',')[0] # the part before comma #pprint ( 'FirstChunk: ' +firstChunk) removeIn = firstChunk.split(' ',1)[1] # remove "In" hashTag = '#' + removeIn.title().replace(' ','') # title() makes the first letter of every work upper case, and replace(' ','') removes whitespaces gain = len(firstChunk) - len(hashTag) + 1 # gained some letters in this process newNum = num + gain secondPart = articleSummary[:newNum].partition(',')[2] body = hashTag + secondPart # [1]th array element is the ',' itself! That's why [2]. finalString = body + "\n" + tinierLink #finalString = body + "..\n" + tinierLink #finalString = body + "\n" #+ tinierLink print ('Final: ' + finalString) print (len(finalString)) import sys from twython import Twython CONSUMER_KEY = '' CONSUMER_SECRET = '' ACCESS_KEY = '' ACCESS_SECRET = '' api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET) # getting the first image of the file #import urllib #if (len(wiki.page(randomTitle).images) != 0): # firstimg = wiki.page(randomTitle).images[0] # print ('linkimg:' + firstimg) # urllib.request.urlretrieve(firstimg, 'img.jpg') # # not sure if image without extension works # photo = open('img.jpg', 'rb') # response = api.upload_media(media=photo) # api.update_status(status=finalString, media_ids=[response['media_id']]) #else: # api.update_status(status=finalString) api.update_status(status=finalString)
# Part 1 with open('day-1-input.txt') as f: module_masses = [int(line.strip()) for line in f] fuel_requirements = [m//3 - 2 for m in module_masses] total_fuel_required = sum(fuel_requirements) print(total_fuel_required) # Part 2 def fuel(m): """ Determine the total fuel required for a given module mass, taking into account the mass of the fuel itself. """ while True: m = m//3 - 2 if m > 0: yield m else: break fuel_requirements = [sum(fuel(m)) for m in module_masses] total_fuel_required = sum(fuel_requirements) print(total_fuel_required)