text
stringlengths
37
1.41M
# Helper functions import re from MathematicalOperations import * def EvaluateParentheses(string): # Evaluates all the expressions inside parentheses parenthetical_ops = [] # stores all the sums inside parentheses parenthetical_results = [] # stores the results of the sums inside the parentheses parentheses_start = False # flag for the start of parentheses parentheses_string = "" # stores the sum found inside parentheses for char in string: if char == "(": parentheses_start = True if parentheses_start: parentheses_string = parentheses_string + char # add each character that comes after a "(" if char == ")": parentheses_start = False # stop adding characters parenthetical_ops.append(parentheses_string) # add the sum to the array of sums that are inside parentheses parentheses_string = "" # resets the character accumulator for ops in parenthetical_ops: # for each sum in the array ops = ops.strip("()") # removes the parentheses operator = re.findall("[0-9]+([\*\-\+/]*)[0-9]+", ops)[0] # finds out the operator inside the parentheses numbers = re.findall("([0-9]+)", ops) # finds out the numbers that need to be operated on if operator == "+": # line 59 to 68 actually performs the operations result = add(numbers[0], numbers[1]) elif operator == "-": result = subtract(numbers[0], numbers[1]) elif operator == "*": result = multiply(numbers[0], numbers[1]) elif operator == "**": result = exponent(numbers[0], numbers[1]) else: result = divide(numbers[0], numbers[1]) parenthetical_results.append(result) # adds the result to another array for i in range(0, len(parenthetical_ops)): # basically replaces the sums with the results in the input array string = string.replace(str(parenthetical_ops[i]), str(parenthetical_results[i])) return(string) def EvaluateOperation(string): if "**" in string: sum = re.findall("[0-9]*\*\*[0-9]*", string)[0] # stores the sum itself and finds it using re numbers = re.findall("[0-9]+", sum) # stores the numbers to be operated on in array form result = str(exponent(numbers[0], numbers[1])) # calculates result string = string.replace(sum, result) # replaces the operation with the result in the input string return string # the following code is exactly the same expect for a few changes in the regular expressions elif "/" in string: sum = re.findall("[0-9]*/[0-9]*", string)[0] numbers = re.findall("[0-9]+", sum) result = str(divide(numbers[0], numbers[1])) string = string.replace(sum, result) return string elif "*" in string: sum = re.findall("[0-9]*\*[0-9]*", string)[0] numbers = re.findall("[0-9]+", sum) result = str(multiply(numbers[0], numbers[1])) string = string.replace(sum, result) return string elif "+" in string: sum = re.findall("[0-9]*\+[0-9]*", string)[0] numbers = re.findall("[0-9]+", sum) result = str(add(numbers[0], numbers[1])) string = string.replace(sum, result) return string else: sum = re.findall("[0-9]*\-[0-9]*", string)[0] numbers = re.findall("[0-9]+", sum) result = str(subtract(numbers[0], numbers[1])) string = string.replace(sum, result) return string
number1 = int(input("First number: ")) number2 = int(input("Second number: ")) operation = input("Operation [+, -, *, /]: ") if operation == "+": combination = number1 + number2 elif operation == "-": combination = number1 - number2 elif operation == "*": combination = number1 * number2 elif operation == "/": if number2 == 0: combination= "you can’t divide by zero." else: combination = number1 / number2 else: combination = "ERROR ... '" + operation + "' unrecognised" print("Answer: " + str(combination)) print() input("Press return to continue ...")
def self_powers(number): return sum(n ** n for n in range(1, number + 1)) def test_self_powers(): assert self_powers(10) == 10405071317 print(str(self_powers(1000))[-10:])
import itertools def is_magic(ring): groups = ring_groups(ring) return all(sum(group) == sum(groups[0]) for group in groups) def ring_groups(ring): length = len(ring) // 2 outer = ring[:length] inner = ring[length:] return [[outer[i], inner[i], inner[(i + 1) % length]] for i in range(length)] def all_magic_ngon_rings(n): yield from (combination for combination in itertools.permutations(range(1, n + 1)) if combination[0] == min(combination[:len(combination) // 2]) and is_magic(combination)) def ring_group_concat(ring): return "".join(str(n) for group in ring_groups(ring) for n in group) def test_p068(): assert is_magic([4, 6, 5, 3, 2, 1]) def p066(): return max(ring_group_concat(magic_ring) for magic_ring in all_magic_ngon_rings(10)) if __name__ == '__main__': print(p066())
visited = {} def step(x, y, size): if (x, y) in visited: return visited[(x, y)] right = down = final = 0 if x < size: right = step(x+1, y, size) if y < size: down = step(x, y+1, size) if x == size and y == size: final = 1 visited[(x, y)] = right + down + final return right + down + final def routes(size): return step(0, 0, size) print(routes(20))
import turtle turtle.shape("turtle") turtle.color("pink") turtle.width("10") turtle.penup() turtle.home() def thing(that): turtle.right(90) turtle.forward(that*2) turtle.right(90) turtle.forward(that*1.5) turtle.left(180) turtle.pendown() turtle.circle(that) turtle.penup() turtle.forward(that/2) turtle.left(90) turtle.pendown() turtle.forward(that*4) turtle.circle(-that,180) turtle.forward(4*that) turtle.penup() turtle.left(90) turtle.forward(that/2) turtle.pendown() turtle.circle(that) thing(100) print("LOLZ PIMMEL!") input("enter to exit")
import numpy as np import nnfs from nnfs.datasets import spiral_data #axis 0 means row wise and 1 means columns wise nnfs.init() # Dense layer class Layer_Dense: # Layer initialization def __init__(self, n_inputs, n_neurons): # Initialize weights and biases self.weights = 0.01 * np.random.randn(n_inputs, n_neurons) self.biases = np.zeros((1, n_neurons)) # Forward pass def forward(self, inputs): # Calculate output values from inputs, weights and biases self.output = np.dot(inputs, self.weights) + self.biases # ReLU activation class Activation_ReLU: # Forward pass def forward(self, inputs): # Calculate output values from inputs self.output = np.maximum(0, inputs) # Softmax activation class Activation_Softmax: # Forward pass def forward(self, inputs): # Get unnormalized probabilities exp_values = np.exp(inputs - np.max(inputs, axis=1, keepdims=True)) # Normalize them for each sample probabilities = exp_values / np.sum(exp_values, axis=1, keepdims=True) self.output = probabilities # Create dataset X, y = spiral_data(samples=100, classes=3) # Create Dense layer with 2 input features and 3 output values dense1 = Layer_Dense(2, 3) # Create ReLU activation (to be used with Dense layer): activation1 = Activation_ReLU() # Create second Dense layer with 3 input features (as we take output # of previous layer here) and 3 output values dense2 = Layer_Dense(3, 3) # Create Softmax activation (to be used with Dense layer): activation2 = Activation_Softmax() # Make a forward pass of our training data through this layer dense1.forward(X) # Make a forward pass through activation function # it takes the output of first dense layer here activation1.forward(dense1.output) # Make a forward pass through second Dense layer # it takes outputs of activation function of first layer as inputs dense2.forward(activation1.output) # Make a forward pass through activation function # it takes the output of second dense layer here activation2.forward(dense2.output) # Let's see output of the first few samples: print(activation2.output[:5]) ''' >>> [[0.33333334 0.33333334 0.33333334] [0.33333316 0.3333332 0.33333364] [0.33333287 0.3333329 0.33333418] [0.3333326 0.33333263 0.33333477] [0.33333233 0.3333324 0.33333528]] '''
# Functions with Inputs def personal_greeting(name): print(f"Hello {name} 👋") personal_greeting("Hannah") # Positional vs. Keyword Arguments def greet_with(name, location): print(f"Hello {name} 👋") print(f"What is it like in {location}? 🌍") greet_with("Hannah", "Gold Goast") # Positional Arguments greet_with("Gold Coast", "Hannah") # will mess up our desired argument because of something caleld positional argument # Keyword Arguments def my_function(a, b, c): # do something with a # do something with b # doe something with c print(a + b * c) my_function(c=3, a=1, b=2) greet_with(location="Gold Coast", name="Hannah") # Paint Area Calculator import math def paint_calc(height, width, cover): number_of_cans = math.ceil((height * width) / cover) print(f"You'll need {number_of_cans} cans of paint.") # 🚨 Testing Code 👇 test_h = int(input("Height of wall: ")) test_w = int(input("Width of wall: ")) coverage = 5 paint_calc(height=test_h, width=test_w, cover=coverage) # Prime Number Checker # prime number is a number only divisible by 1 or itself # 2, 3, 5, 7, 11, 13 ... def prime_checker(number): prime_num = True for i in range(2, number): if number % i == 0: prime_num = False if prime_num: print(f"{number} is not a prime number") else: print(f"{number} is a prime number") n = int(input("Check this number: ")) prime_checker(number=n)
# (nested) if-else statements, comparison operators (>, <, <=, >=, ==, !=) # elif # Multiple conditions (multiple if statements in succession) print("Welcome to the rollercoaster 🎢") height = int(input("What is your height in cm? ")) bill = 0 if height >= 120: print("You can ride the rollercoaster!") age = int(input("How old are you? ")) if age < 12: bill = 5 print("Child tickets are $5") elif age < 18 : bill = 7 print("Youth tickets are $7") elif age >= 45 and age <= 55: print("People your age ride for free!") else: bill = 12 print("$12 for an adult ticket") photo = input("Do you want a photo taken? Y/N. ") if photo == "Y": bill += 3 print(f"Your final bill is ${bill}") else: print("Sorry, you have to grow taller before you can ride.") # Odd or Even Exercise (Modulo Operation) number = int(input("Which number do you want to check? ")) if number % 2 == 0: print("This is an even number") else: print("This is an odd number") # BMI Calculator advanced ⚖ height = float(input("Enter your height in cm: ")) / 100 weight = float(input("Enter your weight in kg: ")) bmi = round((weight / (height * height)), 1) print(f"Your BMI is {bmi}."); if bmi < 18.5: print("You are underweight") elif bmi < 25: print("You have a normal weight") elif bmi < 30: print("You are overweight") elif bmi < 35: print("You are obwese") else: print("You are clinically obese") # Leap Year year = int(input("Which year do you want to check? ")) if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: print("Leap Year!") else: print("Not a leap year!") else: print("Leap year!") else: print("Not a leap year!") # Pizza Order Program 🍕 # Logical operators (written out in python) # and (equivalent to writing &&) # or (equivalent of ||) # not print("Welcome to Python Pizza Deliveries!") size = input("What size do you want your pizza? S, M or L? ") add_pepperoni = input("Do you want pepperoni? ") cheesy_crust = input("Do you want a cheesy crust? ") price = 0 if size == "S": price += 15 elif size == "M": price += 20 elif size == "L": price += 25 if add_pepperoni == "Y" and size == "S": price += 2 else: price += 3 if cheesy_crust == "Y": price += 1 print(f"Your final bill is ${price}💵") # Love Calculator # lower() function changes all the letters in a string to lowercase # count() function will give you the number of times a letter occurs in a string print("Welcome to the Love Calculator 💕") name1 = input("Whats your name? \n").lower() name2 = input("Whats your lovers name? \n").lower() lovescore = 0 firstNumber = 0 firstNumber += name1.count("t") firstNumber += name1.count("r") firstNumber += name1.count("u") firstNumber += name1.count("e") firstNumber += name2.count("t") firstNumber += name2.count("r") firstNumber += name2.count("u") firstNumber += name2.count("e") # print(name1, name2, firstNumber) secondNumber = 0 secondNumber += name1.count("l") secondNumber += name1.count("o") secondNumber += name1.count("v") secondNumber += name1.count("e") secondNumber += name2.count("l") secondNumber += name2.count("o") secondNumber += name2.count("v") secondNumber += name2.count("e") lovescore = int(str(firstNumber) + str(secondNumber)) if lovescore < 10 or lovescore > 90: print(f"Your score is {lovescore}, you to together like coke and mentos") elif lovescore >= 40 and lovescore <= 50: print(f"Your score is {lovescore}, you are alright together") else: print(f"Your score is {lovescore}") # Day 3 Project - Treasue Island print(''' ______________________________________________________________ _ _ _ _ . /\\/%\ . /%\/%\ . __.<\\%#//\,_ <%%#/%%\,__ . . <%#/|\\%%%#///\ /^%#%%\///%#\\ ""/%/""\ \""//| |/""'/ /\//"//' . L/'` \ \ ` " / / ``` ` \ \ . / / . . . \ \ / / . . \ \ / / . . . ..:\ \:::/ /:. . . ______________/ \__;\___/\;_/\________________________________ ''') print("Welcome to Treasue Island 🏴‍☠️") print("Your missure is to find the treasure...") direction = input("--- You are at a crossroad, where do you want to go? Type 'left' or 'right': \n").lower() if direction == "right": print("Game over, you fell into a well hidden trap.") elif direction == "left": action = input("--- You've reached the shore of the ocean but you see an island in the middle. Type 'wait' to wait for a boat or 'swim' to make the journey across yourself.\n").lower() if action == "swim": print("Game over, you were eaten by a crocodile while swimming towards the island 🐊") elif action == "wait": door = input("--- You arrived at the island unharmed, there are three hidden doors in the sand, a red, a yellow and a blue one. Which color do you choose? \n").lower() if door == "red": print("Game over - huge flames shot out of the door 🔥") elif door == "yellow": print("You found the treasure - you won!!! 🏆") elif door == "blue": print("The blue door let the water flood the island, you've drowned 🌊") else: print("Game over. You starved looking for a door with this color.")
class Node: def __init__(self, item, next=None): self.item = item self.next = next class Queue: def __init__(self): self.queueFront = None self.queueBack = None self.size = 0 def destroyQueue(self): self.queueFront = None self.queueBack = None self.size = 0 def is_empty(self): return self.size == 0 def enqueue(self, newItem): n = Node(newItem) if not self.is_empty(): self.queueBack.next = n self.queueBack = n if self.is_empty(): self.queueFront = n # als het 2e element wordt toegevorgd if self.size == 1: self.queueFront.next = self.queueBack self.size += 1 return True def dequeue(self): if self.is_empty(): return False, None n = self.queueFront self.queueFront = n.next self.size -= 1 return True, n.item def getFront(self): if self.is_empty(): return False, None return True, self.queueFront.item def visualize(self): code = '\tnode [shape=record];\n' \ '\tstruct [label="' ptr = self.queueFront while ptr is not None: if ptr is self.queueFront: code += "<front> " else: code += "|" code += str(ptr.item) ptr = ptr.next code += '"];\n' \ '\tFront [shape=plaintext];\n' \ '\tFront -> struct:front\n' \ return code if __name__ == "__main__": s = Queue() s.enqueue(5) s.enqueue(10) s.enqueue(6) s.enqueue(7) s.enqueue(20) s.dequeue() s.enqueue(1) print(s.visualize())
import time from colorama import init, Fore init(autoreset=True) '''Stretch goal explanation: Write a program to determine if a number, given on the command line, is prime. 1. How can you optimize this program? 2. Implement [The Sieve of Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes), one of the oldest algorithms known (ca. 200 BC).''' red = Fore.RED green = Fore.GREEN yes = green + "Yes, this number is prime :D" no = red + "No, this number is not prime :(" def prime_checker(x): if x > 1: for i in range(2, x//2): if (x % i) == 0: print("1", x, no) break else: print("2", x, yes) else: print("3", x, no) loop = True while(loop): num_input = input( 'Enter a number to discover whether it is PRIME ("ooo ahhh"):') try: num_input = int(num_input) prime_checker(num_input) except: print("You must enter a number!") time.sleep(0.5)
"""My calculator object""" class Calculator: """My constant #1""" CONSTANT_VAR = 4 """My constant #2""" CONSTANT_VAR_2 = 5 def __init__(self): """Initialization funciton""" self.public_var = 1 self._protected_var = 2 self.__private_var = 3 def _protected_function(self): """Some protected function""" def __private_function(self): """Some private function""" @staticmethod def addition(var_a, var_b): """Adds the list of arguments Args: var_a (float): First value var_b (float): Second value Returns: float: Sum Raises: TypeError: If something other than float or int is used. """ if (isinstance(var_a, (int, float)) and isinstance(var_b, (int, float))): var_r = var_a + var_b else: raise ValueError return var_r @staticmethod def subtraction(var_a, var_b): """Subtracts second value from first value. Args: var_a (float): First value var_b (float): Second value Returns: float: Subtraction """ return var_a - var_b @staticmethod def multiplication(var_a, var_b): """Multiply two numbers. Args: var_a (float): First value var_b (float): Second value Returns: float: Multiplication """ return var_a * var_b @staticmethod def division(var_a, var_b): """Divide first value by second value Args: var_a (float): First value var_b (float): Second value Returns: float: Division """ return var_a / var_b
''' References: https://stackoverflow.com/questions/6545023/how-to-sort-ip-addresses-stored-in-dictionary-in-python/6545090#6545090 https://stackoverflow.com/questions/20944483/python-3-sort-a-dict-by-its-values https://docs.python.org/3.3/tutorial/datastructures.html https://www.quora.com/How-do-I-write-a-dictionary-to-a-file-in-Python https://www.programiz.com/python-programming/break-continue https://www.ascii-art-generator.org/ #https://docs.python.org/3/howto/argparse.html #https://pymotw.com/2/argparse/ read mac-addr.txt containing the output of sh mac-address 11 sh mac-address 12 sh mac-address 13 sh mac-address 14 and create a list of Vlan, Mac Address, interface and manufacturer. Number of Entries: 4 Vlan MAC Address Interface Vendor -------------------------------------------------- 24 3417eb-ba532f 11 Dell -------------------------------------------------- 202 b4a95a-ab7608 11 Avaya -------------------------------------------------- 202 38bb3c-bc311f 13 Avaya -------------------------------------------------- 24 a4251b-30e9a8 14 Avaya -------------------------------------------------- Uses the Parser library for Wireshark's OUI database from https://github.com/coolbho3k/manuf to convert the MAC to a manufacture. The database needs to be updated occaisionally using: python3 manuf.py -u Changelog March 7, 2018 Added code to read Mac2IP.json and use it as a dictionary of IP to MAC. Mac2IP.json is created by running arp-hp.py against the output "show arp" on a core switch if Mac2IP.json is found in the same directory as macaddr.py it adds the IP address to the output. if Mac2IP.json is not found the IP address is not added March 24, 2018 Added an MD5 hash function to the list of MAC addresses. This gives a quick comparison of the before and after is some cables got swapped but are on the correct vlan. Added a sorted output of the MAC addresses. If there are differences before and after you can save the list of MACs and use MELD or Notepad++ (with the compare plugin) to see what is different. Hash of all the MAC addresses 6449620420f0d67bffd26b65e9a824a4 Sorted list of MAC Addresses 0018.c840.1295 0018.c840.12a8 0027.0dbd.9f6e April 7, 2018 Added output for PingInfoView (nirsoft.net) PingInfo Data 10.56.238.150 b499.ba01.bc82 10.56.239.240 0026.5535.7b7a April 30, 2018 Added better error trapping for the json and mac-addr.txt. May 15, 2018 Fixed a bug in the IP address selection loop. I wasn't clearing IP_Data at the end of the loop so is an interface didn't have an IP address in the json file it would use the last IP address. Clear the IP address in case the next interface has a MAC but no IP address IP_Data = '' ''' import manuf import sys import json import hashlib import re import argparse parser = argparse.ArgumentParser() parser.add_argument("-f", "--file", type=str, required=False, help="File to read from") # parser.add_argument('-o', '--output', type=str, help="Output file.") args = parser.parse_args() vernum = '1.0' AsciiArt = ''' __ __ _ ____ ____ __ __ __ _ | \/ | / \ / ___| |___ \ | \/ | __ _ _ __ _ _ / _| __ _ ___| |_ | |\/| | / _ \| | __) | | |\/| |/ _` | '_ \| | | | |_ / _` |/ __| __| | | | |/ ___ \ |___ / __/ | | | | (_| | | | | |_| | _| (_| | (__| |_ |_| |_/_/ \_\____| |_____| |_| |_|\__,_|_| |_|\__,_|_| \__,_|\___|\__| ''' def version(): """ This function prints the version of this program. It doesn't allow any argument. """ print(AsciiArt) print("+----------------------------------------------------------------------+") print("| "+ sys.argv[0] + " Version "+ vernum +" |") print("| This program is free software; you can redistribute it and/or modify |") print("| it in any way you want. If you improve it please send me a copy at |") print("| the email address below. |") print("| |") print("| Author: Michael Hubbard, michael.hubbard999@gmail.com |") print("| mwhubbard.blogspot.com |") print("| @rikosintie |") print("+----------------------------------------------------------------------+") version() # MAC addresses are expressed differently depending on the manufacture and even model device # the formats that this script can parse are: # 0a:0a:0a:0a:0a:0a, 0a-0a-0a-0a-0a-0a, 0a0a0a.0a0a0a0 and 0a0a0a-0a0a0a # this should cover most Cisco and HP devices. # print() # create an empty dictionary to hold the mac-IP data Mac_IP = {} IP_Data = '' device_name = 'Not Found' # create an empty list to hold MAC addresses for hashing hash_list = [] # open the json created by arp.py if it exists my_json_file = 'Mac2IP.json' try: with open(my_json_file) as f: Mac_IP = json.load(f) except FileNotFoundError as fnf_error: print(fnf_error) print('IP Addresses will not be included') my_json_file = None p = manuf.MacParser() # create a blank list to accept each line in the file data = [] # args.file contains the string entered after -f. That's becuase of the --file in the parser.add_argument function. if args.file: mydatafile = args.file else: mydatafile = 'mac-addr.txt' try: f = open(mydatafile, 'r') except FileNotFoundError as fnf_error: print(fnf_error) sys.exit(0) else: for line in f: match_PC = re.search(r'([0-9A-F]{2}[-:]){5}([0-9A-F]{2})', line, re.I) match_Cisco = re.search(r'([0-9A-F]{4}[.]){2}([0-9A-F]{4})', line, re.I) match_HP = re.search(r'([0-9A-F]{6}[-])([0-9A-F]{6})', line, re.I) match_Interface = line.find('Port Address Table') if match_PC or match_Cisco or match_HP or match_Interface != -1: data.append(line) device_name_loc = line.find('#') if device_name_loc != -1: device_name = line[0:device_name_loc] device_name = device_name.strip() f.close ct = len(data)-1 counter = 0 IPs = [] print() print('Device Name: %s ' % device_name) print('PingInfo Data') while counter <= ct: IP = data[counter] # Remove newline at end IP = IP.strip('\n') #If the line contains Port Address Table # if line.find('Port Address Table'): if IP.find('Port Address Table') != -1: # Remove the Status and Counters text. IP = IP.replace('Status and Counters - ','') L = str.split(IP) Interface_Num = L[4] Vlan = '' IP_Data = '' Mac = '' manufacture = '' else: L = str.split(IP) Mac = L[0] Vlan = L[1] Vlan = Vlan.replace(',...','') temp = hash_list.append(Mac) if Mac in Mac_IP: IP_Data = Mac_IP[Mac] else: IP_Data = 'No-Match' # print the pinginfo data print(IP_Data, Mac) # pull the manufacturer with manuf manufacture = p.get_manuf(Mac) # Pad with spaces for output alignment Front_Pad = 4 - len(Vlan) Pad = 7 - len(Vlan) - Front_Pad Vlan = (' ' * Front_Pad) + Vlan + (' ' * Pad) # Pad MAC Address Field Pad = 22 - len(Mac) Mac = Mac + (' ' * Pad) # Pad Interface Pad = 8 - len(Interface_Num) Interface_Num = Interface_Num + (' ' * Pad) # Pad IP address field if the json file exists if my_json_file: Pad = 17 - len(IP_Data) IP_Data = IP_Data + (' ' * Pad) # create the separator at 80 characters Pad = '--' * 35 else: # if not create the separator at 60 characters since there won't be IPs Pad = '--' * 25 IP_Data = '' # Build the string if IP.find('Port Address Table') != -1: counter = counter + 1 continue else: IP = Vlan + IP_Data + Mac + Interface_Num + str(manufacture) IPs.append(str(IP)) IPs.append(Pad) # Clear the IP address in case the next interface has a MAC but no IP address IP_Data = '' counter = counter + 1 d = int(len(IPs)/2) print() print('Number of Entries: %s ' % d) print() print('Device Name: %s ' % device_name) if my_json_file: print('Vlan IP Address MAC Address Interface Vendor') print('--' * 35) else: print('Vlan MAC Address Interface Vendor') print('--' * 25) for IP in IPs: print(IP) ''' hash the string of all macs. This gives a quick way to compare the before and after MACS ''' hash_list_str = str(hash_list) # convert the string to bytes b = hash_list_str.encode() hash_object = hashlib.md5(b) print() print('Hash of all the MAC addresses') print(hash_object.hexdigest()) print() ''' print out the MAC Addresses sorted for review. This is useful if the patch cables got mixed up during replacement ''' print('Sorted list of MAC Addresses') # print(hash_list) for x in sorted(hash_list): print(x) print('End of output')
# process CSV files # find rank 1~3 for all subjects def get_top_threes(file_in,file_out): # sort by last name def sort_lastname(ls): if len(ls) == 1: return ls else: r = [] for name in ls: sep = name.split(' ') sep.reverse() r.append(' '.join(sep)) r.sort() rr = [] for name in r: r = name.split(' ') r.reverse() rr.append(' '.join(r)) return rr # process file subjects = file_in.readline().strip('\n,').split(',') students_scores = {} for line in file_in: line = line.strip() if '"' in line: new_list = line.split('"') name = ' '.join(new_list[1].split(', ')[::-1]) scores = new_list[2].split(',')[1:] elif "'" in line: new_list = line.split("'") name = ' '.join(new_list[1].split(', ')[::-1]) scores = new_list[2].split(',')[1:] else: new_list = line.split(',') name = new_list[0] scores = new_list[1:] scores_int = [] for n in scores: scores_int.append(int(n)) students_scores[name] = scores_int # find top 3 for every subject rank_1, rank_2, rank_3 = [], [], [] for i in range(len(subjects)): first, second, third = ['name',0], ['name',0], ['name',0] for key,value in students_scores.items(): score = value[i] if score > first[-1]: third = second second = first first = [key,score] elif score == first[-1]: first.insert(0,key) elif score > second[-1]: third = second second = [key,score] elif score == second[-1]: second.insert(0,key) elif score > third[-1]: third = [key,score] elif score == third[-1]: third.insert(0,key) else: pass rank_1.append(', '.join(sort_lastname(first[:-1]))) rank_2.append(', '.join(sort_lastname(second[:-1]))) rank_3.append(', '.join(sort_lastname(third[:-1]))) # find overall top 3 oa_1, oa_2, oa_3 = ['name',0], ['name',0], ['name',0] for key,value in students_scores.items(): total = sum(value) if total > oa_1[-1]: oa_3 = oa_2 oa_2 = oa_1 oa_1 = [key,total] elif total == oa_1[-1]: oa_1.insert(0,key) elif total > oa_2[-1]: oa_3 = oa_2 oa_2 = [key,total] elif total == oa_2[-1]: oa_2.insert(0,key) elif total > oa_3[-1]: oa_3 = [key,total] elif score == oa_3[-1]: oa_3.insert(0,total) else: pass rank_1.append(', '.join(sort_lastname(oa_1[:-1]))) rank_2.append(', '.join(sort_lastname(oa_2[:-1]))) rank_3.append(', '.join(sort_lastname(oa_3[:-1]))) # write a new file file_out.write('rank,%s,overall\n' % ','.join(subjects)) count = {} for i in range(len(subjects)+1): count[i] = 0 file_out.write('1') for i in range(len(subjects)+1): if count[i] < 3: if rank_1[i].count(',') > 0: file_out.write(',"%s"' % rank_1[i]) else: file_out.write(',%s' % rank_1[i]) count[i] += rank_1[i].count(',')+1 else: file_out.write(',') file_out.write('\n2') for i in range(len(subjects)+1): if count[i] < 3: if rank_2[i].count(',') > 0: file_out.write(',"%s"' % rank_2[i]) else: file_out.write(',%s' % rank_2[i]) count[i] += rank_2[i].count(',')+1 else: file_out.write(',') file_out.write('\n3') for i in range(len(subjects)+1): if count[i] < 3: if rank_3[i].count(',') > 0: file_out.write(',"%s"' % rank_3[i]) else: file_out.write(',%s' % rank_3[i]) count[i] += rank_3[i].count(',')+1 else: file_out.write(',') if __name__ == '__main__': fin = open('sheet01.csv') fout = open('result01.csv', 'w') get_top_threes(fin,fout) fin.close() fout.close()
#basic numeric operations a = 10 b = 20 print(a+b) print(a-b) print(a*b) print(a/b) my_salary = 10000 tax_percentage = 0.2 taxes = my_salary * tax_percentage print(taxes)
from ..preprocessing import preprocess_text import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer # sample documents # change these to see what happens to the cell values document_1 = "This is a sample sentence!" document_2 = "I love to code." document_3 = "Jesus loves you!" # corpus of documents corpus = [document_1, document_2, document_3] # preprocess documents processed_corpus = [preprocess_text(doc) for doc in corpus] # initialize and fit TfidfVectorizer vectorizer = TfidfVectorizer(norm=None) tf_idf_scores = vectorizer.fit_transform(processed_corpus) # get vocabulary of terms feature_names = vectorizer.get_feature_names() corpus_index = [n for n in processed_corpus] # create pandas DataFrame with tf-idf scores df_tf_idf = pd.DataFrame(tf_idf_scores.T.todense(), index=feature_names, columns=corpus_index) print(df_tf_idf)
import functools def average(sample: list) -> float: sum = functools.reduce(lambda previous, actual: previous + actual, sample) return sum / len(sample) def median(sample: list) -> float: sample.sort() index = len(sample) // 2 if (len(sample) % 2) == 0: return average([sample[index - 1], sample[index]]) return sample[index] def mode(sample: list): max_element = max(sample) + 1 frequency_table = max_element * [0] for i in sample: frequency_table[i] += 1 modes = list() qtd_frequency = frequency_table[0] for i in range(0, len(frequency_table)): if (frequency_table[i] > qtd_frequency): qtd_frequency = frequency_table[i] modes.clear() modes.append(i) elif (frequency_table[i] == qtd_frequency): modes.append(i) return modes if __name__ == '__main__': print(mode([1, 1, 2, 2, 3, 4, 7, 9, 9, 0, 3]))
#1: #这是一个将函数里所有传进来的参数相加的函数 def test(a,b,*args):#末尾参数前加一个×号 print(a) print(b) print(*args) sum=a+b for i in args: sum+=i print(sum) # args是一个元组 #元组若是元素为一个,后面要跟一个逗号,否则不为元组 #2: def test(a,b,*args,**kwargs):#kwargs 用字典存带名字的多余参数 print(a) print(b) print(args) print(kwargs) test(1,2,3,5,5,66,4,9,8,2,5,58,5,5) #test(b=1,a=2,3,5,5,66,4,9,8,2,5,58,5,5) test(1,2,3,4,5,task=99,done=88) #test(a=1,b=2,3,4,5,task=99,done=88)用了不定长的参数,能再用指定参数的方式传参
# -*- coding: utf-8 -*- """ Created on 2019/10/2 @author: yhy 类定义: 1.cell类 2.strip类 3.rectangle类 4.grid类,也是就是图像类,用来创建一个多边形和其所在网格(grid) 存在问题2020.3.4: 如果一个grid类在定义的时候,给定的在多边形内部的hole如果是有一条边与多边形的边重叠的话 此时多边形的边应该更新为hole中不与其重叠的另外三个边。多边形的顶点也应该发生变化。 然而,该程序目前并不能完成这一功能,也就是说系统依然判定,多边形的被重叠边为多边形边界 总而言之就是存在hole与多边形有边的重叠,这是不规范的 """ import Point class Cell: # x,y是每个cell左下角的横纵坐标 def __init__(self,x,y,l,h): # 点属性坐标顺序0,1,2,3分别为左下,左上,右上,右下 self.point1 = Point.Point(x,y) self.point2 = Point.Point(x,y+h) self.point3 = Point.Point(x+l,y+h) self.point4 = Point.Point(x+l,y) # 表示是否为hole,1是,0否 self.holeNot= 1 self.length = l self.height = h # 列表存贮 self.point = [self.point1,self.point2,self.point3,self.point4] # 线属性,xline是纵坐标集合,yline是横坐标集合 self.XlineList = [self.point1.xline,self.point3.xline] self.YlineList = [self.point1.yline,self.point3.yline] class strip: def __init__(self,tCell,bCell): self.topCell=tCell self.bottomCell=bCell # 表示有几个cell,如只有一个cell的strip就是1,//属性目前有问题 # self.height = (self.topCell.point1.coordinate[1]-self.bottomCell.point1.coordinate[1])+1 # 特指由两个strip形成的矩形,在算法1中 class rectangle: def __init__(self,stripL,stripR): self.leftStrip = stripL self.rightStrip = stripR self.DiagonalPoints =self.findDiagonalPoints() def findDiagonalPoints(self): temp=[self.leftStrip.bottomCell.point1.coordinate[0], self.leftStrip.bottomCell.point1.coordinate[1], self.rightStrip.topCell.point3.coordinate[0], self.rightStrip.topCell.point3.coordinate[1], ] return temp # 网格类,主要储存正交多边形就是一个正交多边形对应一个网格 class Grid: def __init__(self,holeList,pointList): # 图像的每个拐点,list保存,注意该列表中存贮的是点实例 self.pointList = pointList #多边形内部的hole 所组成的list self.holeList = holeList # 多边形的边,该列表中存放的是线段的实例 self.segmentList = self.createSegmentlist() # 找出一个图形中所有顶点,从而确定grid有几条横线竖线,使用列表存储 self.xlineList=self.createXlineList(self.holeList,pointList) self.ylineList=self.createYlineList(self.holeList,pointList) # 列数 self.height = len(self.ylineList)-1 # 行数 self.length = len(self.xlineList)-1 #网格存放一个grid中的所有cell实列的列表 self.gridCellL = self.createGridC(self.xlineList,self.ylineList) #所有Hole列表 self.allHoleL = self.createAllHoleL() #新建属性2020.3.4,列表用来存储polygon中的所有convex角的list self.convexAngleL = [] # 新建属性2020.3.4,列表用来存储polygon中的所有concave角的list self.concaveAngleL = [] self.findPointWithOneCell() #新建属性2020.3.5, 用来存放convex边和concave边 self.concaveSegmentL = [] self.convexSegmentL = [] self.findConcaveEdge() # 如果两个及以上的点在横向或纵向的方向上共线,那么就只能产生一条横线或纵线 # 注意xlineList中的元素作为纵坐标,xline指平行于x轴的线的集合 def createXlineList(self,holeList,pointList): temp=[] for element in holeList: if element.XlineList[0] not in set(temp): temp.append(element.XlineList[0]) if element.XlineList[1] not in set(temp): temp.append(element.XlineList[1]) for element in pointList: if element.xline not in set(temp): temp.append(element.xline) else: continue temp.sort(reverse=True) return temp def createYlineList(self,holeList,pointList): temp = [] for element in holeList: if element.YlineList[0] not in set(temp): temp.append(element.YlineList[0]) if element.YlineList[1] not in set(temp): temp.append(element.YlineList[1]) for element in pointList: if element.yline not in set(temp): temp.append(element.yline) else: continue temp.sort() return temp ###################### # 创建一个cellList ##################### def createGridC(self,xline,yline): temp=[] for i in range(len(yline)-1): for j in range(1,len(xline)): # 少存一格交点坐标,及最上面的xline和最右边的yline不用计入 temp.append(Cell(yline[i],xline[j],yline[i+1]-yline[i],xline[j-1]-xline[j])) return temp #################################### # 用来建立一个包含多边形每个边的List,即多边形每一条边都是一个segment ##################################### def createSegmentlist(self): temp=[] for i in range(len(self.pointList)): if i != len(self.pointList)-1: temp.append(Point.Segment(self.pointList[i],self.pointList[i+1])) else: temp.append(Point.Segment(self.pointList[i],self.pointList[0])) return temp ############################## #一下为判断一个cell是否在多边形内部 ################################ # 计算一个cell的中心点,方便用来进行cell是否在多边形内部 def cellCertreP(self,cell): y = ((cell.point3.coordinate[1] - cell.point1.coordinate[1])/2)+ cell.point1.coordinate[1] x = ((cell.point3.coordinate[0] - cell.point1.coordinate[0])/2)+ cell.point1.coordinate[0] return Point.Point(x, y) # 生成一条横线线段 def createSegment(self,point1, xCoordinate): return Point.Segment(point1, Point.Point(xCoordinate, point1.coordinate[1])) # 生成一条竖线线段 def createSegmentVertical(self,point1, yCoordinate): return Point.Segment(point1, Point.Point(point1.coordinate[0],yCoordinate)) # 判断两条线段是否相交,这里主要是垂直和水平的线段相比较 def intersectOrNot(self,segment1, segment2): p1 = segment1.point1.coordinate p2 = segment1.point2.coordinate p3 = segment2.point1.coordinate p4 = segment2.point2.coordinate if min(p3[1], p4[1]) > max(p1[1], p2[1]) or max(p3[1], p4[1]) < min(p1[1], p2[1]): return False else: if min(p1[0], p2[0]) > max(p3[0], p4[0]) or max(p1[0], p2[0]) < min(p3[0], p4[0]): return False else: return True # 根据一个cell的线段是否与多边形的边的交点个数判断是否在多边形内部,在外部就是hole def holeOrNot(self,cell): count = 0 segment1 = self.createSegment(self.cellCertreP(cell), self.ylineList[-1]) for element in self.segmentList: if self.intersectOrNot(segment1, element): count = count + 1 if (count % 2) == 0: return True else: for element in self.holeList: # 为判断一个cell是否在holeList里出现过,进行一下比较 if element.point1.coordinate[0] == cell.point1.coordinate[0]: if cell.point1.coordinate[1] >= element.point1.coordinate[1] and cell.point1.coordinate[1] < element.point2.coordinate[1]: return True else: continue else: continue return False # 将所有的hole整合起来,闯将一个holeList,包括在多边形外部的区域 def createAllHoleL(self): temp=[] for element in self.gridCellL: if self.holeOrNot(element): temp.append(element) else: element.holeNot=0 continue return temp ##################### ##以下方法实现凹凸角的分离 #################### # 寻找多边形的顶点被几个在多边形内部的cell共享,并且由此得到角度的凹凸 def findPointWithOneCell(self): for element in self.pointList: count = 0 for cell in self.gridCellL: if cell.holeNot==0: if self.pointOnCellOrNot(cell,element): count = count + 1 continue else: continue else: continue if count > 1: self.concaveAngleL.append(element) else: self.convexAngleL.append(element) # 该方法判断一个点是否为一个cell的四个点中的其中一个 def pointOnCellOrNot(self,cell,point): if cell.point1.PointsEqualOrNot(point): return True elif cell.point2.PointsEqualOrNot(point): return True elif cell.point3.PointsEqualOrNot(point): return True elif cell.point4.PointsEqualOrNot(point): return True else: return False #实现凹凸边的分离 def findConcaveEdge(self): for element in self.segmentList: for i in range(len(self.concaveAngleL)): if element.point1.PointsEqualOrNot(self.concaveAngleL[i]): self.concaveSegmentL.append(element) break elif element.point2.PointsEqualOrNot(self.concaveAngleL[i]): self.concaveSegmentL.append(element) break elif i == len(self.concaveAngleL)-1: self.convexSegmentL.append(element) else: continue
# here is example to use Experiment Collector with tensorflow 2.0 # load tensorflow and Experimental Collector import tensorflow as tf from experimentcollector import ExperimentCollector # create Collector object # database will be store into memory by default collector = ExperimentCollector() # define tensorflow's computation graph # for example c = a^2 * b @tf.function def compute_graph(inputs): a = tf.constant(inputs['a']) b = tf.constant(inputs['b']) result = tf.multiply(a ** 2, b) return result # create compute function that call the tensorflow's computation graph # and convert it back to float to store in variable name c def compute(inputs): outputs = compute_graph(inputs).numpy() return {'c':float(outputs)} collector.compute(compute) # define parameter a and b to use in the computation graph collector.initial({ 'a':1, 'b':3 }) # add new experiment that increase a by 1 for 10 times collector.step(range(1,11)) collector.add( 'a', 'tensorflow computation graph', ) # run experiment # tensorflow's computation graph will called by this step collector.run() # plot the result collector.plot()
"""Code Challenge: Solve the Eulerian Cycle Problem. Input: The adjacency list of an Eulerian directed graph. Output: An Eulerian cycle in this graph. """ def eulerianCycle(graph): #First, we are going to store for each node the number of edges that are emerging from them #That's why we'll need a dictionnary to store this information edges = {} #We need therefore to store in edges the len of the value that correspond in the list graph for i in range (len(graph)): edges[i] = len(graph[i]) #Now that this is done, we'll need to store the circuit somewhere. I'll use a list #because keys will not be very useful. cycle = [] #As I saw in the chapter, we are going to do kind of "backtracking" by testing randomly #some cycles and see a bit what will happen en then act in consequence. #For this reason, we'll need to store a temporary cycle that will contain the cycle we are currently testing tempCycle = [] #Now, we'll start from a random node. I'll chose number1 (because 0 may not be on each graph) node = 0 tempCycle.append(0) #As said in the pseudocode given in the stepik intercative tool, the program needs to have #a while that will continue to boucle until there are no more inexplored edges in the graph while len(tempCycle): #We need now to see if there is an outdegree in the node chosen if edges[node]: tempCycle.append(node) #In that case, we'll go ahead and add the future node in our list, future nodes #that is given in the graph. The [-1] is again useful for not take the last list char #which is a special dedicated character. nextNode = graph[node][-1] #And then we need to remove it from the list of graph because otherwise we could #pass twice on the same spot. edges[node] -= 1 graph[node].pop() #And now of course lets move on in the graph. node = nextNode #Now we need to manage the case where there is no more edges available, #which means that our cycle is not eulerian and that we have to find a newstart. else: #As I have seen in the explanations, i need to start from the cycle I formed, #and then make Cycle' <- Cycle as said in the pseudo code. #Cycle' and Cycle are our Cycle and tempCycle #Let's add a newStart as requested. cycle.append(node) #Now we need to go back and make kindof backtracking. #The [-1] is for select the last element of tempCycle node = tempCycle[-1] #The new Start chosen, the tempCycle is no more useful, we'll just delete it #and try again to walk randomly from our newStart. tempCycle.pop() #Finally we have our final answer. Let's print it ! #I had to read the range function documentation #The three arguments means the start, the stop and the step. #The -1 allow us to decrement because the list is now reversed. eularian = [] for i in range(len(cycle) - 1, -1, -1): print(cycle[i], end = "") print(" -> ", end = "") eularian.append(cycle[i]) return eularian #Random test print(eulerianCycle([[3], [0], [1, 6], [2], [2], [4], [5, 8], [9], [7], [6]]))
import sys import math import time class Vertex: def __init__(self, id, x, y): self.id = id self.x = x self.y = y class Graph: def __init__(self): # list of cities self.vertices = [] # 2D matrix of distances between city pairs self.distances = [] self.cityCount = 0 # creates a new vertex and adds it to the graph's vertices list def add_vertex(self, id, x, y): self.vertices.append(Vertex(id, x, y)) self.cityCount = self.cityCount + 1 # calculates the distance between cities to nearest int def calculate_edge(self, vertex1, vertex2): x_dist = vertex1.x - vertex2.x y_dist = vertex1.y - vertex2.y dist = math.sqrt((x_dist**2)+(y_dist**2)) return round(dist) # initialize 2D matrix to store values def build_dist_matrix(self): self.distances = [[0 for x in range(self.cityCount)] for y in range(self.cityCount)] for i in range(self.cityCount): for j in range(self.cityCount): if i != j and self.distances[i][j] == 0: self.distances[i][j] = self.calculate_edge(self.vertices[i], self.vertices[j]) self.distances[j][i] = self.distances[i][j] def check_distance(self, vertex1, vertex2): city_dist = self.distances[vertex1.id][vertex2.id] return city_dist def nearestNeighborTSP(cities, start_city): start = cities.vertices[start_city] currentCity = start path = [currentCity.id] solution = 0 unvisited = set(city.id for city in cities.vertices[:]) unvisited.remove(start_city) while unvisited: edgeLength = float('inf') # determine shortest edge on current vertex for cityID in unvisited: if cities.check_distance(currentCity, cities.vertices[cityID]) < edgeLength: edgeLength = cities.check_distance(currentCity, cities.vertices[cityID]) nextCityID = cityID path.append(nextCityID) solution = solution + cities.check_distance(currentCity, cities.vertices[nextCityID]) unvisited.remove(nextCityID) currentCity = cities.vertices[nextCityID] solution = solution + cities.check_distance(currentCity, start) return solution, path def repetitive_NN(startpoints): solution = float('inf') for x in range(startpoints): distance, path = nearestNeighborTSP(cities, x) if(distance < solution): solution = distance final_path = path return(solution, final_path) start = time.time() # input file is last in command line args filename = sys.argv[-1] file_in = open(filename, 'r') # output is same filename but with .tour filetype file_out = open(filename + '.tour', 'w') cities = Graph() # add cities to graph as vertices for line in file_in: cityLine = line.strip() arr = list(map(int, cityLine.split())) cities.add_vertex(arr[0], arr[1], arr[2]) # calculate the distances and run algorithm once cities.build_dist_matrix() # determine algorithm by input size if cities.cityCount > 1000: # run christofides, no opt elif cities.cityCount > 500: solution, path = repetitive_NN(70) elif cities.cityCount > 250: solution, path = repetitive_NN(150) elif cities.cityCount > 100: solution, path = repetitive_NN(cities.cityCount) else: # run christofides with 2-opt # output first line is total distance, then city IDs file_out.write(str(solution) + '\n') for city in path: file_out.write(str(city) + '\n') print(city) file_in.close() file_out.close() finish = time.time() elapsed = (finish - start) * 1000 print("path length is ", solution) print("time taken was ", elapsed, " ms")
'''\033[1;31;45m] #\codigo de cor[estilo;texto;background m]''' print('\033[7;30mOlá mundo\033[m') print('\033[0;33;44mOlá mundo\033[m') print('\33[34mOlá mundo!\033[m') print('\033[31mOlá mundo!') cor = {'a' : '\033[34m', 'vm' : '\033[31m', 's' :'\033[m'} print(f"{cor['a']}Arthur{cor['vm']} amaral {cor['a']}de {cor['vm']}lima{cor['s']}") a = int(input('primeiro numero: ')) b = int(input('segundo numero: ')) c = int(input('terceiro numero:')) n = [a,b,c] print(f' O maior numero é: {max(n)}\n O menor numero é: {min(n)}') a = int(input('escreva um numero: ')) b = int(input('escreva outro numero:')) c = int(input('escreve outro numero: ')) if a > b and a > c: # primeiro metodo pra fazer print(f'{a} é o maior') elif b > a and b > c: print(f'{b} é o maior') else: print(f'{c} é o maior') m = a # Segundo metodo pra fazer if b < a and b < c: m = b elif c < a and c < b: m = c print(f'e o menor valor é {m}') from _datetime import date a = int(input('Qual ano deseja saber?(0 para ano atual): ')) if a == 0: a = date.today().year if a % 4 == 0 and a % 100 !=0 or a % 400 == 0: print(f'O ano é de {a} é Bissexo!') else: print(f'O ano de {a} não é bissexo!') v = int(input('Qual a velocidade do veiculo? \n')) c = (v-80)*7 if v > 80: print(f'Você foi multado!\nO valor da sua multa é de: {c}R$') else: print('Você não foi multado!') r1 = int(input('reta 1:')) r2 = int(input('reta 2: ')) r3 = int(input('reta 3:')) if r1 + r2 > r3 and r1 + r3 > r2 and r2 + r3 > r1: print('é possivel formar um triangulo') else: print('Não forma um triangulo') s = int(input('Seu salario: ')) if s >= 1250: n = s*1.1 else: n = s*1.15 print(f'Seu salario é {n:.2f}R$') a = float(input('Qual a distancia da viagem?\n')) if a <= 200: print(f'O valor da passagem é de:{a*0.5}R$') else: print(f'O valor da passagem é de:{a*0.45}R$') a = int(input('Digite um numero: ')) if a % 2 == 0: print('Seu numero é par') else: print('Seu numero é impar') from time import sleep from random import randint n = randint (0, 5) a = int(input('Escolha um numero:\n')) print('Aguarde!') sleep(2) if a == n: print('Parabens! você acertou :D') else: print(f'O numero era:{n}\nTente novamente!') from random import randint n = randint (0, 5) a = int(input('Escolha um numero:\n')) if a == n: print('Parabens! você acertou :D') else: print(f'O numero era:{n}\nTente novamente!') n1 = float(input('Sua primeira nota: ')) n2 = float(input('Sua segunda nota: ')) n3 = float(input('Sua terceira nota: ')) m = (n1+n2+n3)/3 print(f'Sua media é: {m:.2f}') if m >= 7: print('Parabens, você foi aprovado!') else: print('Que pena, você foi reprovado!') print('Boas ferias!')
import random l = input('primeiro:') j = input('Segundo: ') p = input('Terceiro: ') a = input('Quarto: ') r = [l, j, p, a] random.shuffle(r) print(f'O aluno escolhido foi {random.choice(r)}') print(f'A ordem de apresentação dos trabalhos {r}') #OU print(f'A ordem de apresentação dos trabalhos {random.sample(r,k=4)}') import math a = float(input('Digite o angulo:')) aa = math.radians(a) print(f'A tangente de {aa} é {math.tan(aa):.2f}\nO seno é {math.sin(aa):.2f}\nO cosseno é {math.cos(aa):.2f}\n' f'Em radianos é {math.radians(aa):.2f}') import math a = float(input('Digite o angulo:')) print(f'A tangente de {a} é {math.tan(a):.2f}\nO seno é {math.sin(a):.2f}\nO cosseno é {math.cos(a):.2f}\n' f'Em radianos é {math.radians(a):.2f}') a = int(input('Digite o primeiro cateto: ')) b = int(input('Digite o segundo cateto: ')) print(f'A hipotenusa é igual a: {(a**2 + b**2)**0.5}') import math a = float(input('Digite um numero decimal: ')) print(f'O valor é {a} e a parte inteira é {math.trunc(a)}') a = int(input('Digite o valor de A(termo X²): ')) b = int(input('Digite o valor de B(termo X): ')) c = int(input('Digite o valor de C(constante): ')) d = (b**2)-(4*a*c) print(f'O valor do Delta é {d} O valor de X1 = {(-b+d**0.5)/2*a} e X2 = {(-b-d**0.5)/2*a}') #------------------------------------------------------------------------ import math n = int(input('Digite um numero: ')) r = math.sqrt(n) print(f'A raiz é {r:.2f}') #ou simplificar fazendo: from math import sqrt n = int(input('digite uma raiz: ')) r = sqrt(n) print(f'A raiz é {r:.4f}')
def main(): text = input("Text: ") letters = 0 words = 1 sentences = 0 for c in text: if ord(c.lower()) >= ord("a") and ord(c.lower()) <= ord("z"): letters += 1 if c == " ": words += 1 if(c == '.' or c == '?' or c == '!'): sentences += 1 print(f"letters: {letters} words: {words} sentences: {sentences}") level = calculateLevel(letters, words, sentences) printGrade(level) def calculateLevel(letters, words, sentences): lettersPer100Words = float(letters) / float(words) * 100 sentencesPer100Words = float(sentences) / float(words) * 100 level = 0.0588 * lettersPer100Words - 0.296 * sentencesPer100Words - 15.8 return round(level) def printGrade(level): if level < 1: print("Before Grade 1") elif level > 16: print("Grade 16+") else: print(f"Grade: {level}") main()
countNum = 0 somaNum = 0 menorNum = pow(1000, 1000) maiorNum = -1 escolha = "S" while escolha != "N": num = int(input("Digite um número: ")) countNum += 1 somaNum += num if num < menorNum: menorNum = num if num > maiorNum: maiorNum = num escolha = input("Deseja continuar? [S / N] ").upper() print("A média dos números digitados é {:.1f}".format(somaNum / countNum)) print("O menor número digitado foi {}".format(menorNum)) print("O maior número digitado foi {}".format(maiorNum))
import math num = float(input('Digite um número real: ')) print('Sua parte inteira é {}'.format(math.floor(num)))
times = ("Athlético PR", "Atlético GO", "Atlético MG", "Bahia", "Botafogo", "RB Bragantino", "Ceará", "Corinthians", "Coritiba", "Flamengo", "Fluminense", "Fortaleza", "Goiás", "Grêmio", "Internacional", "Palmeiras", "Santos", "São Paulo", "Sport", "Vasco") print(f"Os 20 times do Brasileirão 2020 são: {times}") print(f"Os 5 primeiros são: {times[:5]}") print(f"Os 4 últimos são: {times[-4:]}") print(f"Os times orgaizados em ordem alfabética são {sorted(times)}") print(f"O Palmeiras está na posição {times.index('Palmeiras') + 1}")
''' num = int(input("Digite o primeiro termo para uma P.A.: ")) razao = int(input("Digite a razão da P.A.: ")) n = 1 while n < 11: if n == 1: print(num) else: num = num + razao print(num) n = n + 1 ''' num = int(input("Digite o primeiro termo para uma P.A.: ")) razao = int(input("Digite a razão da P.A.: ")) termos = 1 while termos != 0: termos = int(input("Quantos termos deseja mostrar? ")) if termos > 0: print(num) for i in range(1, termos + 1): num = num + razao print(num)
cidade = input("Digite o nome de uma cidade: ").strip() print("SANTO" in cidade.split()[0].upper())
from datetime import datetime ano = int(input("Digite seu ano de nascimento: ")) now = datetime.now() anoAtual = now.year idade = anoAtual - ano if idade == 18: print("Está na hora de você se alistar para o exército") elif idade < 18: print("Ainda não chegou a hora de você se alistar para o exército. Faltam {} anos".format(18 - idade)) else: print("Já se passaram {} anos para você se alistar para o exército".format(idade - 18))
lista = [] decisao = "S" while decisao.upper() == "S": num = int(input("Digite um valor inteiro para adicionar à lista: ")) if num in lista: print(f"O valor {num} já está na lista.") else: lista.append(num) decisao = input("Deseja continuar? ") lista.sort() print(f"Lista final: {lista}")
soma = 0 for i in range(1, 10): if i % 2 != 0 and i % 3 == 0: soma += i print("O resultado da soma é {}".format(soma))
palavras = ('programar', 'phyton', 'logica', 'desenvolvimento', 'string', 'curso', 'video', 'codificar', 'algoritmo', 'linguagem', 'programacao', 'pratica', 'teoria', 'javascript', 'automatizar', 'aprendizado') for p in palavras: print(f"\nNa palavra {p.upper()}, temos: ", end="") for letra in p: if letra.lower() in 'aeiou': print(f"{letra} ", end="")
numOriginal = int(input("Digite um número: ")) num = numOriginal fatorial = num while num > 1: fatorial = fatorial * (num - 1) num = num - 1 print("A fatorial de {} é igual a {}".format(numOriginal, fatorial))
def mapear(funcao, lista): ''' aplica uma função a cada elemento da lista ''' return list(funcao(elemento) for elemento in lista) def quadrado(x): ''' eleva o numero ao quadrado ''' return x**2 def raiz(x): ''' calcula a raiz quadrada do numero ''' return x**0.5 def divisaointeira(x,y): ''' x, y são números retorna quociente, resto, flag maior que 1, flag denominador 0 ''' if y != 0: return x//y, x%y, x>y, False else: return x//y, x%y, x>y, True #quociente, resto = divisaointeira(15,8) quociente, _, _, denominadorzero = divisaointeira(15,8) _, resto, maiorque1, _ = divisaointeira(15,8) print('Quociente: ', quociente, 'Resto: ', resto) print('>1: ', maiorque1, '/0: ', denominadorzero)
def dice(): import random min = 1 max = 6 roll_again = "yes" while roll_again == "yes" or roll_again == "y": print("Rolling the dices...") print("The values are....") print(random.randint(min, max)) print(random.randint(min, max)) roll_again = input("Roll the dices again?") def rps(): import random answer = input("Please enter rock, paper or scissors:") user = answer.lower() print ("You chose" , answer) command = ["rock" , "paper" , "scissors"] computer_choice = random.choice(command) if user == "rock" and computer_choice == "rock": print("I chose" , computer_choice) print("Draw!") elif user == "scissors" and computer_choice == "scissors": print ("I chose" , computer_choice) print("Draw!") elif user == "paper" and computer_choice == "paper": print ("I chose" , computer_choice) print("Draw!") elif user == "paper" and computer_choice == "rock": print ("I chose" , computer_choice) print("You win!") elif user == "rock" and computer_choice == "scissors": print ("I chose" , computer_choice) print("You win!") elif user == "scissors" and computer_choice == "paper": print ("I chose" , computer_choice) print("You win!") elif user == "rock" and computer_choice == "paper": print ("I chose" , computer_choice) print("I win!") elif user == "paper" and computer_choice == "scissors": print ("I chose" , computer_choice) print("I win!") elif user == "scissors" and computer_choice == "rock": print ("I chose" , computer_choice) print("I win!")
import os # création d'un dictionnaire avec des clés de type string mondictionnaire = {} mondictionnaire["pseudo"] = "Prolixe" mondictionnaire["mot de passe"] = "*" print(mondictionnaire) # Ca fonctionne aussi avec d'autres type pour les clé mon_dictionnaire = {} mon_dictionnaire[0] = "a" mon_dictionnaire[1] = "e" mon_dictionnaire[2] = "i" mon_dictionnaire[3] = "o" mon_dictionnaire[4] = "u" mon_dictionnaire[5] = "y" print(mon_dictionnaire) # Même des tuples echiquier = {} echiquier['a', 1] = "tour blanche" # En bas à gauche de l'échiquier echiquier['b', 1] = "cavalier blanc" # À droite de la tour echiquier['c', 1] = "fou blanc" # À droite du cavalier echiquier['d', 1] = "reine blanche" # À droite du fou # Première ligne des blancs echiquier['a', 2] = "pion blanc" # Devant la tour echiquier['b', 2] = "pion blanc" # Devant le cavalier, à droite du pion # Seconde ligne des blancs # encore plus loin avec des references à des fonctions def fete(): print("C'est la fête.") def oiseau(): print("Fais comme l'oiseau...") ... fonctions = {} fonctions["fete"] = fete # on ne met pas les parenthèses fonctions["oiseau"] = oiseau fonctions["oiseau"]() # on essaye de l'appeler # Autre syntaxe d'alimentation placard = {"chemise": 3, "pantalon": 6, "tee-shirt": 7} # suppression placard = {"chemise": 3, "pantalon": 6, "tee shirt": 7} del placard["chemise"] # ou placard = {"chemise": 3, "pantalon": 6, "tee shirt": 7} placard.pop("chemise") placard = {"chemise": 3, "pantalon": 6, "tee shirt": 7} # parcours du dictionnaire for vetement in placard: print(vetement) # Juste les cles for cle in placard.keys(): print(cle) # Juste les valeurs for val in placard.values(): print(val) fruits = {"pommes":21, "melons":3, "poires":31} for cle, valeur in fruits.items(): print("La clé {} contient la valeur {}.".format(cle, valeur)) inventaire = { "pommes": 22, "melons": 4, "poires": 18, "fraises": 76, "prunes": 51, } print(inventaire) # On change le sens de l'inventaire, la quantité avant le nom liste_inversee = {nb: fruit for fruit, nb in inventaire.items()} print(liste_inversee) inventaire = {fruit: nb for nb, fruit in sorted(liste_inversee.items(), reverse = True)} print(inventaire) # Tous les paramètres non nommés se retrouveront dans la variableen_listeet les paramètres nommés dans la variableen_dictionnaire. def fonction_inconnue(*en_liste, **en_dictionnaire): return 1
# Runtime: O(n); beats 96.2% # Space: O(1) # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def rob(self, root: TreeNode) -> int: def post(node=root): if not node: return 0, 0 l0, l1 = post(node.left) r0, r1 = post(node.right) return l1 + r1, max(node.val + l0 + r0, l1 + r1) return max(post())
# Runtime: O(n); beats 552.13% # Space: O(n) # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def rotateRight(self, head: ListNode, k: int) -> ListNode: if not head or not k: return head arr = []; curr = head while curr: arr.append(curr); curr = curr.next k = k % len(arr) if k == 0: return head dummy = ListNode() curr = dummy for i in range(len(arr)): idx = (len(arr) - k + i) % len(arr) curr.next = arr[idx] curr = curr.next curr.next = None return dummy.next
# 953. Verifying an Alien Dictionary - EASY # https://leetcode.com/problems/verifying-an-alien-dictionary/ # In an alien language, surprisingly they also use english lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters. # Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographicaly in this alien language. # Example 1: # Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz" # Output: true # Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted. # Example 2: # Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz" # Output: false # Explanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted. # Example 3: # Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz" # Output: false # Explanation: The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" > "app", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character (More info). def isAlienSorted(words, order) -> bool: order_dict = {} for counter, value in enumerate(list(order)): order_dict[value] = counter for word_i in range(len(words)-1): # always compare the next one left_word = words[word_i] right_word = words[word_i+1] for letter_i in range(max(len(left_word), len(right_word))): if letter_i >= len(right_word): return False if letter_i >= len(left_word): break if order_dict[left_word[letter_i]] > order_dict[right_word[letter_i]]: return False if order_dict[left_word[letter_i]] < order_dict[right_word[letter_i]]: break return True print(isAlienSorted(["hello","leetcode"], "hlabcdefgijkmnopqrstuvwxyz"), True) print(isAlienSorted(["word","world","row"], "worldabcefghijkmnpqstuvxyz"), False) print(isAlienSorted(["apple","app"], "abcdefghijklmnopqrstuvwxyz"), False) print(isAlienSorted(["abs","apple","app","jump"], "abcdefghijklmnopqrstuvwxyz"), False) print(isAlienSorted(["abs","app","apple","jump"], "abcdefghijklmnopqrstuvwxyz"), True)
# 234. Palindrome Linked List # https://leetcode.com/problems/palindrome-linked-list/ # Given a singly linked list, determine if it is a palindrome. # Example 1: # Input: 1->2 # Output: false # Example 2: # Input: 1->2->2->1 # Output: true # Follow up: # Could you do it in O(n) time and O(1) space? class ListNode: def __init__(self, val=None, next=None): self.val = val self.next = next def isPalindrome(head: ListNode) -> bool: node_list = [] while head: node_list.append(head.val) head = head.next while node_list: if len(node_list) == 1: break if node_list.pop(0) != node_list.pop(): return False return True def is_palindrome(head: ListNode) -> bool: def palindrome(node): if node == None: return True res = palindrome(node.next) nonlocal head if head.val != node.val: return False head = head.next return res return palindrome(head) def getHead(vals): head = ListNode(vals[0]) nxt = head for val in vals[1:]: nxt.next = ListNode(val) nxt = nxt.next return head # print(isPalindrome(getHead([1,2,2,1]))) # print(isPalindrome(getHead([1,2,4,2,1]))) print(is_palindrome(getHead([1,2,2,1]))) print(is_palindrome(getHead([1,2,4,2,1]))) print(is_palindrome(getHead([1,2,3,5,4,2,1]))) print(is_palindrome(getHead([1]))) print(is_palindrome(getHead([1,2]))) print(is_palindrome(getHead([1,1])))
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def pseudoPalindromicPaths (self, root: TreeNode) -> int: def palindrome(node=root, has=set()): if not node: return 0 newHas = has ^ set([node.val]) if not node.left and not node.right: return int(len(newHas) < 2) return palindrome(node.left, newHas) + palindrome(node.right, newHas) return palindrome()
# # @lc app=leetcode id=1455 lang=python3 # # [1455] Check If a Word Occurs As a Prefix of Any Word in a Sentence # # @lc code=start class Solution: def isPrefixOfWord(self, sentence: str, searchWord: str) -> int: for i, word in enumerate(sentence.split(' ')): if len(searchWord) <= len(word) and word[:len(searchWord)] == searchWord: return i + 1 return -1 # @lc code=end
# Runtime: O(n); beats 56.74% # Space: O(n) """ # Definition for a Node. class Node: def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): self.val = val self.left = left self.right = right self.next = next """ class Solution: def connect(self, root: 'Node') -> 'Node': if not root: return root queue = [root] while queue: nodes, prevNode = [], None for node in queue: if prevNode: prevNode.next = node if node.left: nodes.append(node.left) if node.right: nodes.append(node.right) prevNode = node queue = nodes return root
# 47. Permutations II # https://leetcode.com/problems/permutations-ii/ # Given a collection of numbers that might contain duplicates, return all possible unique permutations. # Example: # Input: [1,1,2] # Output: # [ # [1,1,2], # [1,2,1], # [2,1,1] # ] from typing import List from copy import deepcopy class Solution: def permuteUnique(self, nums: List[int]) -> List[List[int]]: result_set = set() def permute(arr, seen): if len(arr) == len(nums): result_set.add(tuple(arr)) return for i in range(len(nums)): if i in seen: continue seen.add(i) permute(arr+[nums[i]], seen) seen.remove(i) permute([], set()) return [list(res) for res in result_set] print(Solution().permuteUnique([1,1,2]))
# 104. Maximum Depth of Binary Tree - EASY # https://leetcode.com/problems/maximum-depth-of-binary-tree/ # Given a binary tree, find its maximum depth. # The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. # Note: A leaf is a node with no children. # Example: # Given binary tree [3,9,20,null,null,15,7], # 3 # / \ # 9 20 # / \ # 15 7 # return its depth = 3. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def maxDepth(root) -> int: def getDepth(node, depth=0): if node == None: return depth return max(getDepth(node.left, depth+1), getDepth(node.right, depth+1)) return getDepth(root, 0) root = TreeNode(3, TreeNode(9), TreeNode(20)) root.right.left = TreeNode(15) root.right.right = TreeNode(7) print(maxDepth(root), 3) print(maxDepth(None), 0)
# 1048. Longest String Chain - MEDIUM # https://leetcode.com/problems/longest-string-chain/ # Given a list of words, each word consists of English lowercase letters. # Let's say word1 is a predecessor of word2 if and only if we can add exactly one letter anywhere in word1 to make it equal to word2. For example, "abc" is a predecessor of "abac". # A word chain is a sequence of words [word_1, word_2, ..., word_k] with k >= 1, where word_1 is a predecessor of word_2, word_2 is a predecessor of word_3, and so on. # Return the longest possible length of a word chain with words chosen from the given list of words. # Example 1: # Input: ["a","b","ba","bca","bda","bdca"] # Output: 4 # Explanation: one of the longest word chain is "a","ba","bda","bdca". # Note: # 1 <= words.length <= 1000 # 1 <= words[i].length <= 16 # words[i] only consists of English lowercase letters. def longestStrChain(words) -> int: words.sort(key=lambda x: len(x)) words_map = {} global_max = 1 for word in words: result = 1 for i in range(len(word)): substring = word[:i] + word[i+1:] if substring in words_map: result = max(result, words_map[substring] + 1) words_map[word] = result global_max = max(result, global_max) print (words_map) return global_max print(longestStrChain(["a","b","ba","bca","bda","bdca"]), 4)
# 704. Binary Search - EASY # https://leetcode.com/problems/binary-search/ # Given a sorted(in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1. # Example 1: # Input: nums = [-1, 0, 3, 5, 9, 12], target = 9 # Output: 4 # Explanation: 9 exists in nums and its index is 4 # Example 2: # Input: nums = [-1, 0, 3, 5, 9, 12], target = 2 # Output: -1 # Explanation: 2 does not exist in nums so return -1 # Note: # You may assume that all elements in nums are unique. # n will be in the range[1, 10000]. # The value of each element in nums will be in the range[-9999, 9999]. def search(nums, target) -> int: left, right = 0, len(nums) - 1 while left <= right: mid = (left + right) // 2 if nums[mid] == target: return mid elif nums[mid] > target: right = mid - 1 else: left = mid + 1 return -1 print(search([-1, 0, 3, 5, 9, 12], 9), 4) print(search([-1, 0, 3, 5, 9, 12], 2), -1) print(search([-1], -1), 0)
# 63. Unique Paths II - MEDIUM # https://leetcode.com/problems/unique-paths-ii/ # A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). # The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). # Now consider if some obstacles are added to the grids. How many unique paths would there be? # An obstacle and empty space is marked as 1 and 0 respectively in the grid. # Note: m and n will be at most 100. # Example 1: # Input: # [ # [0,0,0], # [0,1,0], # [0,0,0] # ] # Output: 2 # Explanation: # There is one obstacle in the middle of the 3x3 grid above. # There are two ways to reach the bottom-right corner: # 1. Right -> Right -> Down -> Down # 2. Down -> Down -> Right -> Right def uniquePathsWithObstacles(obstacleGrid) -> int: rows, cols = len(obstacleGrid), len(obstacleGrid[0]) cache = {(rows-1, cols-1): 1} def paths(row, col): if row >= rows or col >= cols or obstacleGrid[row][col] == 1: return 0 if (row, col) in cache: return cache[(row, col)] cache[(row,col)] = paths(row + 1, col) + paths(row, col + 1) return cache[(row,col)] return paths(0,0) input = [ [0,0,0], [0,1,0], [0,0,0] ] print(uniquePathsWithObstacles(input), 2)
# 463. Island Perimeter - EASY # https://leetcode.com/problems/island-perimeter/ # You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. # Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). # The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. # Example: # Input: # [[0,1,0,0], # [1,1,1,0], # [0,1,0,0], # [1,1,0,0]] # Output: 16 # Explanation: The perimeter is the 16 yellow stripes in the image below: class Solution: def islandPerimeter(self, grid: List[List[int]]) -> int: if not grid or not grid[0]: return 0 perimeters = 0 queue = [] for row in range(len(grid)): for col in range(len(grid[0])): if grid[row][col] == 1: queue.append((row,col)) break dr = [-1, 1, 0, 0] dc = [0, 0, -1, 1] seen_set = set() while queue: row, col = queue.pop(0) if (row, col) in seen_set: continue seen_set.add((row, col)) for i in range(4): nr = row + dr[i] nc = col + dc[i] if nr >= 0 and nr < len(grid) and nc >= 0 and nc < len(grid[0]) and grid[nr][nc] == 1: queue.append((nr,nc)) else: perimeters = perimeters + 1 return perimeters # input1 = [[0,1,0,0], # [1,1,1,0], # [0,1,0,0], # [1,1,0,0]] # print(islandPerimeter(input1)) # input2 = [[1,1,1,1], # [1,1,1,1], # [1,1,1,1], # [1,1,1,1]] # print(islandPerimeter(input2)) # input3 = [[0,0,0,0], # [0,0,0,0], # [0,0,0,0], # [0,0,0,0]] # print(islandPerimeter(input3)) # input4 = [[0,0,0,0], # [0,0,0,0], # [0,1,0,0], # [0,0,0,0]] # print(islandPerimeter(input4)) # input5 = [[0,0,0,0], # [0,0,0,0], # [0,1,1,0], # [0,0,0,0]] # print(islandPerimeter(input5)) input6 = [[1,0]] print(islandPerimeter(input6))
# Runtime: O(nlogn); beats 98.66 # Space: O(n) # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def insertionSortList(self, head: ListNode) -> ListNode: if not head: return head dummy, node = ListNode(val=float('-inf'), next=head), head arr, node_map = [dummy.val], {dummy.val: dummy} while node: curr = node if node.val not in node_map: node_map[node.val] = node node, i = curr.next, bisect_left(arr, curr.val) curr.next, node_map[arr[i-1]].next = node_map[arr[i-1]].next, curr insort_left(arr, curr.val) node_map[arr[-1]].next = None return dummy.next
class Vehicle: def __init__(self,make,mileage,capacity): self.make=make self.mileage=mileage self.capacity=capacity #def get_fare(self): #print("fare of parent class") # raise NotImplementedError("must implement get fare method") #class Scooter(Vehicle): #def __init__(self,make,mileage,capacity): #Vehicle.__init__(self,make,mileage,capacity) #obj1=Scooter("abc",40,15) class Car(Vehicle): def __init__(self,make,mileage,capacity): Vehicle.__init__(self,make,mileage,capacity) def get_fare(self): fare_car=(self.capacity+self.mileage)+15/100 return fare_car class Bus(Vehicle): def __init__(self,make,mileage,capacity): Vehicle.__init__(self,make,mileage,capacity) def get_fare(self): fare_bus=(self.capacity+self.mileage)+25/100 return fare_bus #print(obj1.get_fare()) bus1=Bus("volvo",40,10) car1=Car("nano",30,10) print("Fare of bus1 is :",bus1.get_fare()) print("Fare of car1 is:",car1.get_fare())
import random from datetime import datetime def randomNumArrayGen(max, length): arr = [] for count in range(length): arr.append(int(round(random.random()*max))) return arr def bubbleSort(): unsorted = randomNumArrayGen(10000,100) endCheck = 1 #FOR TIMING # var d = new Date(); # var startTime = d.getTime(); #END TIMING for i in range(0,len(unsorted)): for n in range(0,(len(unsorted) - endCheck)): if unsorted[n] > unsorted[n+1]: temp = unsorted[n] unsorted[n] = unsorted[n+1] unsorted[n+1] = temp endCheck+=1 # FOR TIMING # var fdate = new Date(); # console.log("BUBBLE SORT: " + (fdate.getTime() - startTime) + "ms"); # END TIMING return unsorted now1 = datetime.now().microsecond print bubbleSort() now2 = datetime.now().microsecond print(str(now2 - now1) + " microseconds")
""" A connection designed for connecting and disconnecting other connections """ __author__ = "Ron Remets" import queue from communication.connection import Connection class Connector(Connection): """ A connection designed for connecting and disconnecting other connections """ def __init__(self, name, socket, connection_type): super().__init__(name, socket, connection_type) self.commands = queue.Queue() @staticmethod def parse_connector_command(command): """ Parse and return the arguments of the command. :param command: The string to parse. :return: The arguments of the command """ instruction = command[:command.index(":")] name = command[command.index(":") + 1:] return instruction, name
""" A class to organize a connection """ __author__ = "Ron Remets" import enum import logging import threading class ConnectionStatus(enum.Enum): """ The possible statuses of a connection """ NOT_STARTED = enum.auto() CONNECTING = enum.auto() CONNECTED = enum.auto() DISCONNECTING = enum.auto() DISCONNECTED = enum.auto() CLOSING = enum.auto() CLOSED = enum.auto() ERROR = enum.auto() class Connection(object): """ A class to organize a connection """ def __init__(self, name, socket, connection_type): self.name = name self.socket = socket self.type = connection_type self._running_lock = threading.Lock() self._connected_lock = threading.Lock() self._status_lock = threading.Lock() self.status = ConnectionStatus.NOT_STARTED self.connected = False self._set_running(False) @property def running(self): """ Check if the connection (socket) is running. :return: True if it is, otherwise False """ with self._running_lock: return self._running def _set_running(self, value): with self._running_lock: self._running = value @property def connected(self): """ Whether the socket is connected (Not if it is running, but if the buffers state were switched to the right state) :return: True if it is, otherwise False """ with self._connected_lock: return self._connected @connected.setter def connected(self, value): with self._connected_lock: self._connected = value @property def status(self): """ What the connection is currently doing :return: A ConnectionStatus enum value """ with self._status_lock: return self._status @status.setter def status(self, value): with self._status_lock: self._status = value def start(self): """ Start the connection by setting running to True """ logging.info(f"CONNECTIONS:Starting connection {self.name}") self._set_running(True) self.status = ConnectionStatus.CONNECTING def disconnect(self): """ close the threads that might crash if the other side closes. """ self.socket.shutdown() self.status = ConnectionStatus.DISCONNECTED def close(self): """ Close the connection. """ self.socket.close() self.status = ConnectionStatus.CLOSED
# Comments in python. As you may have notice this line starts with a hash sign (#). # Hash signs are not processed by the python interpreter. You can use hash signs to create comments # in your program to explain specific parts of the program, to creates notes, or to troubleshoot and/or # test parts of the program. # In the example below, the first line and third line will be printed, and the second line will be ignored. print('This is the first line') # print('This is the second line') print('This is the third line') # After running the program, remove the hash sign and run the program again.
#Binary Converter import program_exit n= 0 while n < 10: byte = input("Byte: ") byte = byte.lower() while len(byte) == 8: decimal = 0 for num in byte: decimal = decimal*2 + int(num) print(decimal) break if byte.lower() in ('exit'): print("Exiting software...") program_exit(2) #exits programs in 2 seconds and with no errors elif len(byte) > 8 or len(byte) < 8: print("Not an 8 bit byte, please try again")
""" 7. В одномерном массиве целых чисел определить два наименьших элемента. Они могут быть как равны между собой (оба минимальны), так и различаться. """ # Preprocess import random A = [random.randint(0, 10) for _ in range(10)] print(A) first_i = 0 second_i = 1 for i in range(len(A)): if A[first_i] > A[i]: first_i = i for i in range(len(A)): if A[second_i] > A[i] and i != first_i: second_i = i print(A[first_i], A[second_i])
""" 3. Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран. Например, если введено число 3486, надо вывести 6843. """ num = input("Введите число: ") mun = '' for i in num: mun = i + mun print(mun)
""" 2. По введенным пользователем координатам двух точек вывести уравнение прямой вида y = kx + b, проходящей через эти точки. """ print('Введите кординаты 2 точек') a = input('координаты a = ') b = input('координаты b = ') x1, y1 = map(int, a.split(',')) x2, y2 = map(int, b.split(',')) k = (y1 - y2) / (x1 - x2) b = y2 - k * x2 print(f'y = {k} * x + {b}')
""" 3. Массив размером 2m + 1, где m — натуральное число, заполнен случайным образом. Найдите в массиве медиану. Медианой называется элемент ряда, делящий его на две равные части: в одной находятся элементы, которые не меньше медианы, в другой — не больше медианы. Примечание: задачу можно решить без сортировки исходного массива. Но если это слишком сложно, используйте метод сортировки, который не рассматривался на уроках (сортировка слиянием также недопустима). """ import random array = [random.randint(0, 100) for _ in range(random.randint(2, 7) * 2 + 1)] print('array =', array) def median(arr): for i in arr: less, more = [], [] for j in arr: more.append(j) if j > i else less.append(j) if len(less) == len(more) + 1: return max(less) elif len(less) + 1 == len(more): return min(more) print('median =', median(array))
def cube(v): return v*v*v x= int(input("Enter a number: ")) print("From def() : " +str(cube(x))) c = lambda x: x*x*x print("From lambda : "+ str(c(x)))
class Person: #name = "sample" #age = 0 def __init__(self,name,age): self.name = name self.age = age ame=input("enter your name: ") ge=int(input("enter your age: ")) p1 = Person(ame,ge) page = 2119 - p1.age print("Hey",p1.name,",you will score century in year:",page)
statement=input("enter string: ") count1 = 0 count2 = 0 for i in range(len(statement)-1): count1 += statement[i:i+4] == 'Emma' for i in range(len(statement)-1): count2 += statement[i:i+4] == 'emma' count = count1 + count2 print("Emma appeared ", count, "times")
# 5.Write a program that prompts the user to enter an integer for today�s day of the week (Sunday is 0, Monday is 1, ..., and Saturday is 6). # Also prompt the user to enter the number of days after today for a future day and display the future day of the week. def dayfinder(dk): switcher={ 0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday' } print(switcher.get(dk,"Invalid Day")) day = int(input("Enter Number: ")) dk = day%7 dayfinder(dk) k = input("Want to check for more dates[Y/N]: ") while k == 'Y' or k == 'y': day = int(input("Enter Number: ")) dk = day%7 dayfinder(dk) k = input("Want to check for more dates[Y/N]: ")
# 11:07 PM, Feb 9th, @ dormitory # 面向对象,类的继承 # 继承 inherit # 类的继承基本理解,还要多写代码练习加深印象 class SchoolMember: def __init__(self, name, age): self.name = name self.age = age print('(Initilized SchoolMember: {0})'.format(self.name)) def tell(self): print('Name:{0} Age:{1}'.format(self.name, self.age)) # Teacher 类继承 SchoolMember 类 class Teacher(SchoolMember): # 初始化函数 def __init__(self, name, age, salary): # 调用父类 SchoolMember 的初始化函数 SchoolMember.__init__(self, name, age) # 补充子类的属性 self.salary = salary print('(Initilized Teacher: {0})'.format(self.name)) def tell(self): # 调用父类 SchoolMember 的方法 SchoolMember.tell(self) print('Salary: {0}'.format(self.salary)) # Student 类继承 SchoolMember 类 class Student(SchoolMember): def __init__(self, name, age, marks): SchoolMember.__init__(self, name, age) self.marks = marks print('(Initlized Student: {0})'.format(self.name)) def tell(self): SchoolMember.tell(self) print('Marks: {0}'.format(self.marks)) pass # Flora = SchoolMember('Flora', 25) # Denis = SchoolMember('Denis', 23) # Flora = Teacher('Flora', 29, 8000) # Denis = Student('Denis', 23, 99)
/** Program use for sorting array using selection sort. Write two method for swapping and find minimum value of a array.Then call these methods while looping through array elements. **/ def swap(array, i, j): temp = array[i] array[i] = array[j] array[j] = temp def find_min_index(array, start_index): min_value = array[start_index] min_index = start_index i = min_index + 1 while(i < len(array)): if min_value > array[i]: min_value = array[i] min_index = i i=i+1 return min_index def selection_sort(array): i = 0 while(i < len(array)): min_index = find_min_index(array, i) swap(array, i, min_index) i = i+1 return array array = [22, 11, 99, 88, 9, 7, 42]; print(selection_sort(array) == [7, 9, 11, 22, 42, 88, 99])
############################################################################### """ Question: LintCode: http://www.lintcode.com/en/problem/maximum-depth-of-binary-tree/ Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Example: Given a binary tree as follow: 1 / \ 2 3 / \ 4 5 The maximum depth is 3. Analysis: Divide & Conquer """ """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: The root of binary tree. @return: An integer """ def maxDepth(self, root): if root is None: return 0 left = self.maxDepth(root.left) right = self.maxDepth(root.right) return max(left, right) + 1
############################################################################### """ Question: LintCode: http://www.lintcode.com/en/problem/search-in-rotated-sorted-array/ Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array. Example: For [4, 5, 1, 2, 3] and target=1, return 2. For [4, 5, 1, 2, 3] and target=0, return -1. Analysis: Binary search. /| M/ | (situation 1) / | / | S/ | | ------------|------------- | | /E | / | / (situation 2) | /M' | / """ class Solution: """ @param A : a list of integers @param target : an integer to be searched @return : an integer """ def search(self, A, target): if len(A) == 0: return -1 start, end = 0, len(A) - 1 while start + 1 < end: mid = start + (end - start) / 2 if A[mid] == target: return mid if A[mid] > A[start]: # decide where middle is # situation 1, numbers between start and mid are sorted if A[start] <= target and target <= A[mid]: end = mid else: start = mid else: # situation 2, numbers between mid and end are sorted if A[mid] <= target and target <= A[end]: start = mid else: end = mid if A[start] == target: return start if A[end] == target: return end return -1 if __name__ == '__main__': s = Solution() print s.search([4, 5, 1, 2, 3], 1) print s.search([4, 5, 1, 2, 3], 5) print s.search([4, 5, 1, 2, 3], 0) print s.search([], 1)
from abc import ABCMeta, abstractmethod class AbstractGraph(metaclass=ABCMeta): @abstractmethod def insert_vertex(self, vertex): pass @abstractmethod def insert_edge(self, edge): pass @abstractmethod def vertices_adjacent(self, v1, v2): pass @abstractmethod def edges_adjacent(self, e1, e2): pass @abstractmethod def remove_vertex(self, vertex): pass @abstractmethod def remove_edge(self, edge): pass @abstractmethod def get_neighbourhood(self, vertex): pass @abstractmethod def has_vertex(self, v): pass @abstractmethod def has_edge(self, edge): pass @abstractmethod def clear(self): pass
DATA_DIR = "../data/" def parse_google_analogies(filename, anlgtype=None): """ Parse file and return a list of dicts. Google's analogy data has 4 space separated words per line, except for lines starting with ":", which indicate types of analogy. """ analogy_dicts = [] analogy_tupls = [] analogy_types = [] with open(DATA_DIR + filename) as f: skip_type = False for line in f: if line.startswith(":"): curr_type = line[2:-1] if anlgtype: if anlgtype != curr_type: skip_type = True continue else: skip_type = False analogy_types.append(curr_type) analogy_tupls.append([]) analogy_dicts.append({}) else: if anlgtype: if skip_type: continue else: pass w1,w2,w3,w4 = line.split() analogy_tupls[-1].append((w1, w2, w3, w4)) d0 = analogy_dicts[-1] d1 = d0.get(w1, {}) d2 = d1.get(w2, {}) d2[w3] = w4 d1[w2] = d2 d0[w1] = d1 return analogy_dicts, analogy_tupls, analogy_types
MyList=["pink","blue","green"] print(MyList) MyList.append("yellow") print(MyList)
from random import shuffle class Solution(object): def __init__(self, rects): """ :type rects: List[List[int]] """ self.points = [] for rect in rects: width_start = rect[0] height_start = rect[1] for width in xrange(abs(rect[0] - rect[2]) + 1): for height in xrange(abs(rect[1] - rect[3]) + 1): self.points.append([width_start + width, height_start + height]) shuffle(self.points) def pick(self): """ :rtype: List[int] """ if len(self.points) > 0: return self.points.pop() else: return None # Your Solution object will be instantiated and called as such: # obj = Solution(rects) # param_1 = obj.pick() rects = [[1, 1, 5, 5]] sol = Solution(rects) print sol.pick() print sol.pick() print sol.pick()
# 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 kthSmallest(self, root, k): """ :type root: TreeNode :type k: int :rtype: int """ self.count = k self.result = None def dfs(node): if self.result or not node: return dfs(node.left) self.count -= 1 if self.count == 0: self.result = node.val dfs(node.right) dfs(root) return self.result n1 = TreeNode(15) n21 = TreeNode(7) n22 = TreeNode(20) n31 = TreeNode(3) n32 = TreeNode(9) n1.left = n21 n1.right = n22 n21.left = n31 n21.right = n32 sol = Solution() print(sol.kthSmallest(n1, 3))
class Solution(object): def asteroidCollision(self, asteroids): """ :type asteroids: List[int] :rtype: List[int] """ stack = [] for ast in asteroids: if stack and stack[-1] > 0 and ast < 0: abs_ast = abs(ast) while stack and stack[-1] > 0 and stack[-1] < abs_ast: stack.pop() if stack: if stack[-1] == abs_ast: stack.pop() elif stack[-1] < 0: stack.append(ast) else: stack.append(ast) else: stack.append(ast) return stack sol = Solution() asts = [-2, -2, 1, -2] # asts = [5,10,-5] print(sol.asteroidCollision(asts))
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ last = tail = head while n > 0: tail = tail.next n -= 1 if not tail: return head.next while tail.next: last = last.next tail = tail.next last.next = last.next.next return head n0 = ListNode(0) n1 = ListNode(1) n2 = ListNode(2) n3 = ListNode(3) n4 = ListNode(4) n5 = ListNode(5) # n0.next = n1 n1.next = n2 # n2.next = n3 # n3.next = n4 # n4.next = n5 sol = Solution() new_head = sol.removeNthFromEnd(n1, 1) while new_head: print(new_head.val) new_head = new_head.next
class Solution: def tribonacci(self, n: int) -> int: if n == 0: return 0 elif n == 1: return 1 elif n == 2: return 1 else: t = [0, 1, 1] i = -1 while n > 2: i += 1 t[i % 3] = sum(t) n -= 1 return t[i % 3] sol = Solution() print(sol.tribonacci(25))
class Solution: def findIntegers(self, num): """ :type num: int :rtype: int """ x, y = 1, 2 res = 1 while num: if num & 3 == 3: res = 0 res += x * (num & 1) num >>= 1 x, y = y, x + y return res # self.res = 1 # self.visited = set([]) # def dfs(n): # if n <= num and n & 3 != 3: # self.res += 1 # n <<= 1 # dfs(n) # dfs(n + 1) # dfs(1) # return self.res # res = 0 # while num > 0: # temp = 3 # res += 1 # while temp <= num: # if temp & num == temp: # res -= 1 # break # temp <<= 1 # num -= 1 # return res + 1 sol = Solution() num = 84 print(sol.findIntegers(num))
# 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 findSecondMinimumValue(self, root): """ :type root: TreeNode :rtype: int """ if not root: return -1 min_val = root.val sec_min_val = -1 queue = [root] while queue: temp = queue.pop(0) if sec_min_val == -1: if temp.val > min_val: sec_min_val = temp.val else: if temp.val < min_val: sec_min_val = min_val min_val = temp.val elif sec_min_val > temp.val > min_val: sec_min_val = temp.val if temp.left: queue.append(temp.left) if temp.right: queue.append(temp.right) return sec_min_val # n1 = TreeNode(2) # n21 = TreeNode(2) # n22 = TreeNode(5) # n31 = TreeNode(5) # n32 = TreeNode(7) n1 = TreeNode(2) n21 = TreeNode(2) n22 = TreeNode(2) n1.left = n21 n1.right = n22 # n22.left = n31 # n22.right = n32 sol = Solution() print(sol.findSecondMinimumValue(n1))
class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ left = 0 right = len(s) - 1 dic = '0123456789abcdefghijklmnopqrstuvwxyz' while right > left: temp_left = s[left].lower() if temp_left not in dic: left += 1 continue temp_right = s[right].lower() if temp_right not in dic: right -= 1 continue if temp_left == temp_right: left += 1 right -= 1 else: return False return True sol = Solution() # s = "A man, a plan, a canal: Panama" # s = "race a car" s = '0p' print sol.isPalindrome(s)
class Solution(object): def arrayPairSum(self, nums): """ :type nums: List[int] :rtype: int """ nums.sort() idx = 0 res = 0 len_nums = len(nums) while idx < len_nums: res += nums[idx] idx += 2 return res sol = Solution() nums = [1,4,3,2] print(sol.arrayPairSum(nums))
class Solution(object): def searchMatrix(self, matrix, target): """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if not matrix or not matrix[0] or target is None: return False def bin_search(target, arr): left = 0 right = len(arr) - 1 while left <= right: mid = (left + right) / 2 if arr[mid] > target: right = mid - 1 elif arr[mid] < target: left = mid + 1 else: return target return (left, right) res = bin_search(target, [row[0] for row in matrix]) if type(res) == int: return True res = bin_search(target, matrix[min(res)]) return type(res) == int sol = Solution() # matrix = [ # [1, 3, 5, 7], # [10, 11, 16, 20], # [23, 30, 34, 50] # ] # target = 13 matrix = [[-10,-8,-6,-4,-3],[0,2,3,4,5],[8,9,10,10,12]] target = 0 print sol.searchMatrix(matrix, target)
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ if not root: return '' stack = [root] res = [] while stack: node = stack.pop() if node: res.append(str(node.val)) stack.append(node.left) stack.append(node.right) else: res.append('null') return ','.join(res) # if not root: # return [] # res = [] # queue = [root] # while queue: # node = queue.pop(0) # if not node: # res.append(None) # continue # res.append(node.val) # queue.append(node.left) # queue.append(node.right) # temp_queue = [] # for node in queue: # if node is None: # temp_queue.append(None) # temp_queue.append(None) # else: # temp_queue.append(node.left) # temp_queue.append(node.right) # if any(temp_queue): # res.extend([node.val if node is not None else None for node in temp_queue]) # queue = temp_queue # else: # queue = None # return res def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ if not data: return None vals = data[1:-1].split(',') root = TreeNode(int(vals[0])) stack = [(root, True)] for val in vals[1:]: node = None prnt, status = stack.pop() if val != 'null': node = TreeNode(int(val)) stack.append((node, True)) if status: prnt.left = node stack.append((prnt, False)) else: prnt.right = node return root # if not data: # return None # len_data = len(data) # for idx, val in enumerate(data): # if val is not None: # data[idx] = TreeNode(val) # for idx, node in enumerate(data): # if node is not None: # left_idx = idx * 2 + 1 # right_idx = idx * 2 + 2 # if left_idx < len_data: # node.left = data[left_idx] # if right_idx < len_data: # node.right = data[right_idx] # return data[0] # temp = TreeNode(val) # left_idx = idx * 2 + 1 # right_idx = left_idx + 1 # if left_idx < len_data and data[left_idx]: # temp.left = TreeNode(data[left_idx]) # if right_idx < len_data: # temp.right = TreeNode(data[right_idx]) # if not root: # root = temp # Your Codec object will be instantiated and called as such: # codec = Codec() # codec.deserialize(codec.serialize(root)) code = Codec() # arr = [1,2,3,None,None,4,5] # arr = [-1, 0, 1] arr = "[5,2,3,None,None,2,4,3,1]" head = code.deserialize(arr) print(code.serialize(head))
class Solution(object): def totalHammingDistance(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 res = 0 max_num = max(nums) temp = 1 while temp <= max_num: zeros = ones = 0 for num in nums: if num & temp: ones += 1 else: zeros += 1 res += ones * zeros temp <<= 1 return res sol = Solution() # nums = [4, 14, 2] nums = [6,1,8,6,8] print sol.totalHammingDistance(nums)
class Solution(object): def maxNumber(self, nums1, nums2, k): """ :type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[int] """ def prep(nums, k): extra = len(nums) - k if extra == 0: return nums stack = [] for num in nums: while extra and stack and stack[-1] < num: stack.pop() extra -= 1 stack.append(num) return stack[:k] def merge(a, b): return [max(a, b).pop(0) for _ in range(k)] return max(merge(prep(nums1, i), prep(nums2, k - i)) for i in range(k + 1) if i <= len(nums1) and k - i <= len(nums2)) sol = Solution() # nums1 = [3, 4, 6, 5] # nums2 = [9, 1, 2, 5, 8, 3] # k = 5 nums1 = [6, 7] nums2 = [6, 0, 4] k = 5 # nums1 = [3, 9] # nums2 = [8, 9] # k = 3 print(sol.maxNumber(nums1, nums2, k))
class Solution: def bulbSwitch(self, n: int) -> int: bound = 1 << n bulbs = bound - 1 curr = 1 res = 0 for step in range(2, n + 1): toggle = bound >> step while toggle > 0: bulbs ^= toggle toggle >>= step while curr < bound: if curr & bulbs: res += 1 curr <<= 1 return res sol = Solution() print(sol.bulbSwitch(3))
class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: List[int] """ a, b, ca, cb = 0, 0, 0, 0 for num in nums: if num == a: ca += 1 elif num == b: cb += 1 elif ca == 0: a, ca = num, 1 elif cb == 0: b, cb = num, 1 else: ca -= 1 cb -= 1 result = [] len_nums = len(nums) for num in [a, b]: c = nums.count(num) if c > len_nums / 3 and num not in result: result.append(num) return result nums = [1, 1, 2, 1, 2, 3, 2, 2, 1] sol = Solution() print(sol.majorityElement([0, 0, 0]))
""" Valid Anagram """ class Solution(object): def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ dict = {} for ch in s: if ch in dict: dict[ch] += 1 else: dict[ch] = 1 for ch in t: if ch in dict: dict[ch] -= 1 else: return False for k, v in dict.items(): if v != 0: return False return True
class Solution(object): def triangleNumber(self, nums): """ :type nums: List[int] :rtype: int """ if not nums or len(nums) < 3: return 0 nums = sorted(nums) len_nums = len(nums) count = 0 for i in range(2, len_nums): first, second = 0, i - 1 while first < second: if nums[first] + nums[second] > nums[i]: count += (second - first) second -= 1 else: first += 1 return count sol = Solution() a = [2, 2, 3, 4] print(sol.triangleNumber(None))
class MyHashSet(object): def __init__(self): """ Initialize your data structure here. """ self.hash = [[0] * 1000 for _ in range(1000)] def add(self, key): """ :type key: int :rtype: void """ self.hash[key // 1000][key % 1000] = 1 def remove(self, key): """ :type key: int :rtype: void """ self.hash[key // 1000][key % 1000] = 0 def contains(self, key): """ Returns true if this set contains the specified element :type key: int :rtype: bool """ return self.hash[key // 1000][key % 1000] == 1 # Your MyHashSet object will be instantiated and called as such: # obj = MyHashSet() # obj.add(key) # obj.remove(key) # param_3 = obj.contains(key) hash = MyHashSet() hash.add(1) hash.add(10) print(hash.contains(1)) hash.remove(1) print(hash.contains(1))
class Solution: def validPalindrome(self, s: str) -> bool: def recurse(l, r, d): while l < r: if s[l] == s[r]: l += 1 r -= 1 else: if d: return False else: if s[l + 1] == s[r] and s[l] == s[r - 1]: return recurse(l + 1, r, True) or recurse(l, r - 1, True) elif s[l + 1] == s[r]: l += 1 d = True elif s[l] == s[r - 1]: r -= 1 d = True else: return False return True return recurse(0, len(s) - 1, False) sol = Solution() s = "aguokepatgbnvfqmgmlcupuufxoohdfpgjdmysgvhmvffcnqxjjxqncffvmhvgsymdjgpfdhooxfuupuculmgmqfvnbgtapekouga" print(sol.validPalindrome(s))
# traffic light simulation from time import sleep class Counter: def __init__(self): self.n = 0 def tick(self): self.n += 1 return self.n def reset(self): self.n = 0 def getNumber(self): return self.n transferTable = {} transferTable['Red'] = {'wait':5, 'next':'Green'} transferTable['Green'] = {'wait':10, 'next':'Yellow'} transferTable['Yellow'] = {'wait':1, 'next':'Red'} # initialization c = Counter() state = 'Green' while True: print('State: %s t=%ds' % (state, c.getNumber())) # check time of waiting if c.getNumber() >= transferTable[state]['wait']: print('turn to next state(%s)' % transferTable[state]['next']) c.reset() state = transferTable[state]['next'] # tick, simulation for time pass sleep(1) c.tick()
# 使用矩陣快速冪計算費氏數列 import time def timing(func): def wrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) end_time = time.time() print(f"{func.__name__} took {(end_time - start_time)*1000:.0f} ms to execute") return result return wrapper class Matrix: def __init__(self, data): self.data = data def __str__(self): # return '\n'.join([' '.join([str(x) for x in row]) for row in self.data]) return str(self.data) def __mul__(self, other): a = self.data b = other.data c11 = a[0][0]*b[0][0] + a[0][1]*b[1][0] c12 = a[0][0]*b[0][1] + a[0][1]*b[1][1] c21 = a[1][0]*b[0][0] + a[1][1]*b[1][0] c22 = a[1][0]*b[0][1] + a[1][1]*b[1][1] return Matrix([[c11, c12], [c21, c22]]) def __imul__(self, other): a = self.data b = other.data c11 = a[0][0]*b[0][0] + a[0][1]*b[1][0] c12 = a[0][0]*b[0][1] + a[0][1]*b[1][1] c21 = a[1][0]*b[0][0] + a[1][1]*b[1][0] c22 = a[1][0]*b[0][1] + a[1][1]*b[1][1] self.data = [[c11, c12], [c21, c22]] return self def __pow__(self, power): # chatGPT ver # if power == 0: # return Matrix([[1, 0], [0, 1]]) # 返回單位矩陣 # elif power == 1: # return self # 返回自身 # elif power % 2 == 0: # m = self ** (power // 2) # return m * m # else: # return self * (self ** (power - 1)) # 自己實作的迭代版本 if power == 0: return Matrix([[1, 0], [0, 1]]) elif power > 0: cmd = bin(int(power))[3:] # 0b1xxxx result = Matrix(self.data) # i = 1 for c in cmd[3:]: result *= result if c == '1': # i = i * 2 + 1 result *= self # print('x2+1', i) # else: # i = i *2 # print('x2', i) return result else: # 暫時不實作負數版本 return None # 取得費氏數列 Fn 的值 def val(self): return self.data[0][1] @timing def fib(n): if n <= 0: return 0 return (Matrix([[1,1],[1,0]]) ** n).val() # for i in range(1, 20): # print(fib(i)) print(fib(10 ** 3)) print(fib(10 ** 4)) print(fib(10 ** 5)) # 0ms 1ms 16ms chatGPT ver # 182ms 300 ms 550 ms 自己實作版本 有 print 資訊 # 1ms 0ms 1ms 自己實作版本 無 print 資訊
# Vending machine simulation from time import sleep from random import random, choice class Machine: priceList = {'A':10, 'B':15, 'C':20} def __init__(self, items=None, deposit=50): self.income = 0 self.items = items or {'A':5, 'B':5, 'C':5} self.deposit = deposit def insertCoin(self, n): print('insert coin %d' % n) self.income += n return 'loadCoin' def _refund(self): if self.income: print('return coin %d' % self.income) self.income = 0 # send back coin TODO: API call def cancel(self): print('cancel') self._refund() return 'ready' def _buyItem(self, name): if self.items[name] > 0 and self.income >= self.priceList[name]: print('send a goods: %s' % name) self.items[name] -= 1 self.income -= self.priceList[name] # TODO: Need to confirm if there is enough balance self._refund() return 0 # success elif self.income < self.priceList[name]: print('Insufficient amount, needs %d coin(s)' % (self.priceList[name]-self.income)) return 1 # Insufficient amount elif self.items[name] <= 0: print('item %s is sold out' % name) return 2 # sold out else: print('something wrong, back to state<insertCoin>') return -1 def buyItem(self, name): respond = self._buyItem(name) if respond == 0: return 'ready' else: return 'loadCoin' def randwalk(state): cmdTable = {} cmdTable['ready'] = ['insertCoin', 'cancel'] cmdTable['loadCoin'] = ['insertCoin', 'cancel', 'buyItem'] coinList = [1, 5, 10, 50] itemList = ['A', 'B', 'C'] # other way: get machine.items at runtime cmd = choice(cmdTable[state]) if cmd == 'insertCoin': return cmd, choice(coinList) elif cmd == 'buyItem': return cmd, choice(itemList) else: return cmd m = Machine() s = 'ready' cmd = '' while True: print('state=%s' % s) cmd = randwalk(s) if type(cmd) is tuple: print('cmd=%s' % cmd[0]) s = getattr(m, cmd[0])(cmd[1]) # call m.cmd(arg) & get next state else: print('cmd=%s' % cmd) s = getattr(m, cmd)() sleep(1)
""" Cameron Bates AY250 homework 5 This is a set of functions to load the data provided from intrade about the republican nomination, the republican VP nomination and the presidential election into a sqlite3 database. It provides tow functions to retrieve data from this database mdall and pall mdall successively plots the probability of a candidate from north or south of the Mason Dixon line winning the nomination for each race. pall plots the difference between the the sum of all the probabilies that different candidates will win the election and 1. """ import sqlite3 import urllib2 import matplotlib.pyplot as plt import matplotlib.dates as mdates import string from os import listdir from numpy import loadtxt import datetime from BeautifulSoup import BeautifulSoup as bs import numpy as np def getdata(name): ''' This function takes a string in the format firstname_lastname and returns their city state party, birthday, and picture file location. It downloads a picture of them if one exists on wikipedia in order to do this. ''' #ambigous name cases if "Allen_West" in name: name = "Allen_West_(politician)" if "Jon_Huntsman" in name: name = "Jon_Huntsman,_Jr." if "John_Bolton" in name: name = "John_R._Bolton" #spoof the mozilla browser in order to get the page opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0')] print name infile = opener.open('http://en.wikipedia.org/w/index.php?title='+str(name)+"&printable=yes") page = infile.read() # parse the page using beautifulsoup and select the information box soup = bs(page) res = soup.find(attrs={'class':'infobox vcard'}) if res == None: res = soup.find(attrs={'class':'infobox biography vcard'}) res = str( res) rows = string.split(res,"<tr") city = None state = None birthday = None party = None #iterate over the rows to find city, state, and party for row in rows: if "Born" in row: parts = row.split("<br") sections = parts[-1].split(",") #print sections if "</a>" in sections[0]: city = sections[0].split("</a>")[0] city = city.split(">")[-1] else: city = sections[0].split("\n")[1] if len(sections) > 1: if "</a>" in sections[1]: state = sections[1].split("</a>")[0] state = state.split(">")[-1] else: state = sections[1] #print row if ",_" in parts[-1]: city = sections[0].split("/")[-1] state = sections[1].split("\"")[0] state = state.lstrip("_") if len(state.split("_"))> 1: state = state.split("_")[0] + " " + state.split("_")[1] #special cases for 3 candidates that don't use the stand formats if "Giuliani" in name: city = "Brooklyn" state = "New York" if "Romney" in name: city = "Detroit" state = "Michigan" if "Trump" in name: city = "Queens" state = "New York" if "Political" in row and "party" in row : #print row data = string.split(row,'td') if not 'Donald_Trump' in name: #print data[1] if len(string.split(data[1],">"))>2: #print data data = string.split(data[1],"title=\"")[-1] #cases for candidates that don't use the standard format if "United States Rep" in data: party = "Republican" else: party = string.split(data," ")[0] if "New Progressive" in data: party = "Republican" if "Rick_Perry" in name: party = "Republican" else: # special case for Donal Trump data = string.split(data[1],">")[1] party = string.split(data,"<")[0] #print party #party = string.split(row,"\"")[-2] #use beautifulsoup to find the birth date soup = bs(res) bday = str(soup.find(attrs={'class':'bday'})) if not 'None' in bday: birthday = string.split(bday,'>') if len(birthday) > 1: birthday = string.split(birthday[1],"<")[0] #use beautifulsoup to find the image file soup = bs(res) images = str(soup.findAll('img')) #download the image file image = string.split(images,"src") if len(image) > 1: image = string.split(image[1],"\"")[1] imagetype = string.split(image,".")[-1] filename = 'pictures/' + name + '.' + imagetype if True: opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0')] infile = opener.open('http:'+image) f = open(filename,'wb') f.write(infile.read()) f.close() else: filename = None #This must be downloaded seperately because he doesn't have an imaage on wikipedia if "Roy_Moore" in name: opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0')] infile = opener.open("http://blog.al.com/breaking/2009/06/large_RoyMoore.JPG") filename = 'pictures/' + name + '.jpg' f = open(filename,'wb') f.write(infile.read()) f.close() party = "Republican" #return data if "New York" in city: state = "New York" city = "New York" return city, state, party, birthday, filename def initdb(): ''' This function creates the races table in the database and populates it. It also creates the elections.db sqlite database if it doesnt exist as well as calling functions to fill the candidates and prediction data tables. ''' connection = sqlite3.connect("elections.db") cursor = connection.cursor() sql_cmd = """CREATE TABLE races (race_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, election_date DATE, url TEXT)""" cursor.execute(sql_cmd) race_data = [('Republican Nomination',"11/4/12",'http://www.intrade.com/v4/markets/?eventId=84328'), ('Presidential Election','11/4/12','http://www.intrade.com/v4/markets/?eventId=84326'), ('Republican VP Nominee','11/4/12','http://www.intrade.com/v4/markets/?eventId=90482')] for race in race_data: sql_cmd = ("INSERT INTO races (name, election_date, url) VALUES " + str(race)) cursor.execute(sql_cmd) #add candidate data to database parsecandidatewiki(cursor) #add prediction data to database connection.commit() cursor.close() loadpredictiondata() #save changes def parsecandidatewiki(cursor): ''' This creates the table of candidates in the database the is attached to the input cursor. It uses the filenames in the race_prediction_data folder. ''' folder = 'race_prediction_data' datafiles = listdir(folder) names = [] sql_cmd = """CREATE TABLE candidates (candidate_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, city TEXT, state TEXT, party TEXT, birthday DATE, mdline INT, picture_file TEXT)""" cursor.execute(sql_cmd) for name in datafiles: firstname = name.split("_")[0] lastname = name.split("_")[1] name = firstname+"_"+lastname if name not in names and "Any_other" not in name: names.append(name) city, state, party, birthday, filename = getdata(name) mdline = getlatitude(state) val = (name,city,state,party,birthday,mdline,filename) print val sql_cmd = """INSERT INTO candidates(name, city, state, party, birthday,mdline, picture_file) values (?,?,?,?,?,?,?)""" cursor.execute(sql_cmd,val) def getlatitude(state): ''' This function uses the yahoo API to determine whether a location that is entered as a string is north or south of the mason dixon line. ''' if state is not None: try: infile = urllib2.urlopen("http://where.yahooapis.com/geocode?q="+string.replace(state," ","_")+"&appid=CB84ju42") page = infile.read() soup = bs(page) res = str(soup.latitude) res = res.split("latitude>")[1] res = res.split("</")[0] if float(res) > 39.722201: return 1 else: return 0 except: print "not a state: ", state return 0 else: return 0 def loadpredictiondata(): ''' This function loads prediction data to the database elections.db from csv files located in the race_prediction_data folder. ''' connection = sqlite3.connect("elections.db") cursor = connection.cursor() sql_cmd = """CREATE TABLE predictions (id INTEGER PRIMARY KEY AUTOINCREMENT, candidate_id INTEGER, race_id INTEGER, date DATE, price FLOAT, volume FLOAT)""" cursor.execute(sql_cmd) folder = 'race_prediction_data' datafiles = listdir(folder) for item in datafiles: #load data from csv file marketdata = loadtxt(folder+ '/' + item,skiprows=1,delimiter=',', dtype = 'S7,S7,float,float,float,float,float') firstname = item.split("_")[0] lastname = item.split("_")[1] if "RepNom" in item: race = '\"Republican Nomination\"' elif "RepVP" in item: race = '\"Republican VP Nominee\"' elif "Pres" in item: race = '\"Presidential Election\"' #determine race_id sql_cmd = """SELECT race_id FROM races where name like """ + str(race) cursor.execute(sql_cmd) raceid = cursor.fetchall() #print raceid name = firstname+"_"+lastname #determine candidate_id sql_cmd = """SELECT candidate_id FROM candidates where name like """ + "\"" +str(name) + "\"" cursor.execute(sql_cmd) candidateid = cursor.fetchall() #print candidateid if len(candidateid) > 0: #insert data into database for row in marketdata: date = string.lstrip(row[0],'\"') year = string.rstrip(row[1],'\"') date = datetime.datetime.strptime(date+year,'%b %d %Y') date = date.strftime('%Y-%m-%d') price = row[-2] volume = row[-1] val = (candidateid[0][0],raceid[0][0],date,price,volume) sql_cmd = """INSERT INTO predictions(candidate_id, race_id, date, price, volume) values (?,?,?,?,?)""" cursor.execute(sql_cmd,val) connection.commit() cursor.close() def plotmdline(md,rid): ''' This function returns the sum of the probabilities of a candidate the is either north of the mason dixon line(md =1) or south of the mason dixon line (md =0) wins the race with the race id input (rid). ''' #select data from the database connection = sqlite3.connect("elections.db") cursor = connection.cursor() sql_cmd = """SELECT predictions.date, predictions.price from predictions left join candidates on candidates.candidate_id = predictions.candidate_id where candidates.mdline=""" + str(md) + """ AND predictions.race_id="""+ str(rid) + """ ORDER BY predictions.date ASC""" cursor.execute(sql_cmd) result = cursor.fetchall() #sum the data for each date prevdate = result[0][0] dates = [] price = [] psum = 0 for item in result: if item[0] in prevdate: psum = psum + item[1] else: price.append(psum) psum = 0 dates.append(item[0]) prevdate = item[0] price.append(psum) #return the prices and dates return price, dates #for item in result: def comparemd(rid,name): ''' This function compares the probability of a candidate from north of the mason dixon line winning to that of one south of the mason dixon line winning normalized to one. the inputs are the race id (rid) and the name of the race. ''' north, ndates = np.array(plotmdline(1,rid))#[0:1206] south, sdates = np.array(plotmdline(0,rid)) ratio = [] finaldates = [] #compare when there is data for both on a given day for index, date in enumerate(ndates): for index2, date2 in enumerate(sdates): if date == date2: if (north[index]+south[index2]) >0: ratio.append(north[index]/(north[index]+south[index2])) else: ratio.append(0) finaldates.append(datetime.datetime.strptime(date,"%Y-%m-%d")) #Plot a figure of the two probabilities fig = plt.figure() ax = fig.add_subplot(111) ax.plot(finaldates,ratio,label='North wins ' + name) plt.hold(True) ax.plot(finaldates,1-np.array(ratio),label='South wins ' + name) plt.xlabel("Date") plt.ylabel("probability of winning") plt.legend(loc=2) plt.hold(False) fig.autofmt_xdate() plt.show() def mdall(): ''' This function plots the probability of a candidate from north or south of the mason dixon line winning for all the races in the races table. ''' connection = sqlite3.connect("elections.db") cursor = connection.cursor() sql_cmd = "SELECT race_id, name FROM races" cursor.execute(sql_cmd) result = cursor.fetchall() for item in result: comparemd(item[0],item[1]) def pall(): ''' This function plots the difference between the sum of the probabilities of a republican or Barack Obama winning in comparison to 1. ''' #This gets data for republican candidates connection = sqlite3.connect("elections.db") cursor = connection.cursor() sql_cmd = """SELECT predictions.date, predictions.price from predictions left join candidates on candidates.candidate_id = predictions.candidate_id where predictions.race_id=2 and candidates.party like \"Republican\" ORDER BY predictions.date ASC""" cursor.execute(sql_cmd) result = cursor.fetchall() #Sum all the data for each date prevdate = result[0][0] dates = [] price = [] psum = 0 for item in result: if item[0] in prevdate: psum = psum + item[1] else: price.append(psum) psum = 0 dates.append(item[0]) prevdate = item[0] price.append(psum) #Get the prediction data for Barack Obama sql_cmd = """SELECT predictions.date, predictions.price from predictions left join candidates on candidates.candidate_id = predictions.candidate_id where predictions.race_id=2 and candidates.name like \"Barack_Obama\" ORDER BY predictions.date ASC""" cursor.execute(sql_cmd) result = cursor.fetchall() dprice = [] ddates = [] total = [] finaldates = [] for item in result: dprice.append(item[1]) ddates.append(item[0]) #sum the probabilities for all shared dates for index, date in enumerate(dates): for index2, date2 in enumerate(ddates): if date == date2: total.append(100-(price[index]+dprice[index2])) finaldates.append(datetime.datetime.strptime(date,"%Y-%m-%d")) #plot the result fig = plt.figure() ax = fig.add_subplot(111) ax.plot(finaldates,total) yearsFmt = mdates.DateFormatter('%m-%d-%Y') ax.xaxis.set_major_formatter(yearsFmt) fig.autofmt_xdate() plt.xlabel("Date") plt.ylabel("Total probability deficit (%)") plt.show() def selectcandidatedata(results): # select the information for the candidate of interest connection = sqlite3.connect("elections.db") cursor = connection.cursor() sql_cmd = """SELECT predictions.date, predictions.price from predictions left join candidates on candidates.candidate_id = predictions.candidate_id where predictions.race_id=""" + str(results.race) + """ and candidates.name like \"%""" + str(results.candidate) + """%\" ORDER BY predictions.date ASC""" cursor.execute(sql_cmd) result = cursor.fetchall() dprice = [] ddates = [] #iterate over the requested data to find the requested date for item in result: dprice.append(item[1]) ddates.append(item[0]) #print item[0] if item[0] in results.date: price = item[1] print "Candidate: ", results.candidate, " Date: ", item[0], " probability: ", item[1], "%" return dprice, ddates, price def plotprobability(dprice,ddates,results, price): #change the dates to datetime objects for plotting finaldates = [] for date in ddates: finaldates.append(datetime.datetime.strptime(date,"%Y-%m-%d")) #plot the result fig = plt.figure() ax = fig.add_subplot(111) ax.plot(finaldates,dprice) yearsFmt = mdates.DateFormatter('%m-%d-%Y') ax.xaxis.set_major_formatter(yearsFmt) fig.autofmt_xdate() plt.hold(True) plt.plot(datetime.datetime.strptime(results.date,"%Y-%m-%d"),price,'ro') plt.xlabel("Date") plt.ylabel("Probability of winning (%)") plt.show()
# coding=utf-8 import time import math import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt class cls_Environment: """ The environment class """ def __init__(self): """init function, called then object is created""" self._t0 = time.clock() # get current time # Runtime variables self._runtime_max = 0 # initialise variable for the number of steps until success self._stepsize = 0.1 # step size. The sampling rate how often the agent "sees" the environment between its # actions self._ode_iterations = 100 # variable for the number of iteration the odeint does. self._ode_variables = 10 # variable to define the end of an array for the odeint results. # definition of road self._road_width_right = -10 # total road with in forward direction self._road_width_left = 0 # total road with in oncoming direction self._number_of_lanes_right = 2 # number of lanes in the forward direction self._number_of_lanes_left = 0 # number of lanes in the oncoming direction self._obstacle_width = 0 # negativ because directional vector of obstacle is negativ # car characteristic self._car_length_front = 1.6 # length from the center of gravity to the front wheels of the car self._car_length_back = 1.4 # length from the center of gravity to the back wheels of the car self._car_side_slip_rigidity_back = 150000 # car side slip rigidity in the back self._side_slip_rigidity_front = self._car_side_slip_rigidity_back * 0.6 # car side slip rigidity in the front self._car_inertia = 4000 #1000 # car inertia self._car_mass = 2000 #500 # mass of the car self._msr = 50.0 # max sensor range, how far the agent can "see" # sensor information self._number_of_sections = 13 # number of sections per side self._sections = [6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6] # array of sensors indexes self._angle = 3 # degress of how wide each sections is # initial values self._init_lane = 0.0 # initialise the variable for the initial lane self._agent_pos_global_init = np.array([0.0, self._init_lane]) # get the agents initial position using the # init_lane function self._x_value_obstacle = 0 # initialise the variable for the x coordiante of the obstacle self._free_yaw_befor_after_obst = 30 # define how many maters before the obstacle the agent is allowed to # have a greater yaw angle self._y_values_obstacle1 = 0 # initialise a variable for the y coordiante of the obstacle self._y_values_obstacle2 = 0 # initialise a variable for the y coordiante of the obstacle self._y_values_obstacle = 0 # initialise a variable for the y coordiante of the obstacle self._agent_yaw_global_init = 0.0 # variable for the initial yaw angle self._speed_init = 5.0 # variable for the initial speed in m/s self._delta_speed = 0.5 # variable for the rate with which the agent changes the speed. Only # relevant to experiments with speed control self._steering_angle_init = 0 # variable for the initial steering angle self._delta_steering_angle = 0.5 # variable for the rate with which the agent changes the # steering angle # decay options self._speed_decay = 0 # speed decay rate. How much the agent is slowed down at each step self._speed_decay_offset = 1 # value to make sure speed is not negativ # ^^ agent cant deal with this concept. doesnt learn to speed up. # changeable variables self._agent_pos_global = self._agent_pos_global_init # initialise a variable for the global position of # the agent self._agent_yaw_global = 0.0 # initialise a variable for the current yaw angle in rad self._agent_speed = self._speed_init # initialise a variable for the current speed self._steering_angle = self._steering_angle_init # initialise a variable for the current steering angle self._current_runtime = 0.0 # counter for the number of steps # win, lose parameters self._dist_to_crash_right = -10.0 # define how far right the agent is allowed to go before crashing self._dist_to_crash_left = 0.0 # define how far left the agent is allowed to go before crashing self._dist_to_crash_x = 7.1 # distance to obstacle after which agent crashes in [m] self._dist_to_crash_y = 0.2 # dist left and right of obst that cause crash in [m] self._win_reward = 100 # reward granted if agent wins self._lose_reward = -100 # reward granted if agent lose self._min_dist_to_success = 10 # distance to cover to be able to win self._speed_crash = 3.0 # min speed. if agent goes slower then crash self._speed_crash_max = 7.0 # max speed. if agent goes faster then crash self._yawangle_crash = 1.5708 # max yaw angle in rad before the obstacle (1.5708 = 90°) # defined in self._free_yaw_befor_after_obst self._yawangle_crash_open_road = 1.5708 #0.139626 # 0.174533 # max yaw on the open road (0.174533 = 10°; 0.139626 = 8°) # misc variables self._agent_pos_global_holder = np.array([[0, 0]]) # initialise holder to hold the agents position in order # to be plot the path the agent took self._max_speed = 16.0 # agent cant go faster than this value self._min_speed = 1.0 # agent cant fo slower than this self._max_steering_angle = [-20.0, 20.0] # max and min steering angle. agent cant steer further than this def reset(self): """reset function to reset the environment and deliver initial state""" self._agent_pos_global_holder = np.array([[0, 0]]) # reset holder to hold the agents position in order # to be plot the path the agent took self._current_runtime = 0 # reset counter for the number of steps self._runtime_max = np.random.randint(30, 45) # randomly (within limits) define how many steps the agent has # to take for it to be successful for this episode self._init_lane = self._pos_agent_initial_lane() # value in y direction where the agent and the obst # are at init self._agent_pos_global_init = np.array([0, self._init_lane]) # put agent in starting place self._agent_pos_global = self._agent_pos_global_init # variable for the current position of the agent. # Initialised with the initial position self._obstacle_width = - (np.random.randint(2, 5) + np.random.random()) # randomly (within limits) define how # wide the obstacle should be for this episode self._x_value_obstacle = np.random.randint(30, 120) # randomly (within limits) define how far away the obstacle # should be # randomly define in what lane the obstacle should be self._y_values_obstacle1 = self._pos_agent_initial_lane() - (self._obstacle_width / 2) self._y_values_obstacle2 = self._init_lane - (self._obstacle_width / 2) # self._y_values_obstacle = np.random.choice(a=[self._y_values_obstacle1, self._y_values_obstacle2], p=[0.8, 0.2]) self._agent_yaw_global = 0.0 # current yaw angle of the agent self._agent_speed = self._speed_init # current speed initialised with the initial speed self._steering_angle = self._steering_angle_init # current steering angle initialised with the initial # steering angle dist_vec = self._calc_dist_to_boundary() # calculate the distance to the surroundings. Boundary and obstacle s0 = self._build_state(dist_vec) # build the state with dist measurements # append position to holder. delete the first entry to delete the move from [0,0] to init position self._agent_pos_global_holder = np.append(self._agent_pos_global_holder, [self._agent_pos_global_init], axis=0) self._agent_pos_global_holder = np.delete(self._agent_pos_global_holder, 0, 0) runtime = self._get_run_time() # get current time return s0, self._agent_pos_global, dist_vec, runtime # return values to caller def step(self, nn_action): """step function to "move" through the episode""" _ = self._execute_action(nn_action) # call function to execute the action dist_vec = self._calc_dist_to_boundary() # calculate the distances to surroundings done, done_reason = self._check_done(dist_vec) # check if ep is terminated s_next = self._build_state(dist_vec) # build the next state reward = self._calc_reward(done) # calc the reward for transition # some housekeeping and setting the done return variable if done == 0: done_info = 0 done = False elif done != 0: if done == 1: done_info = 1 elif done == -1: done_info = -1 else: done_info = 0 done = True self._current_runtime += self._stepsize # increment the number of steps taken self._agent_pos_global_holder = np.append(self._agent_pos_global_holder, [self._agent_pos_global], axis=0) # append position to be able to plot runtime = self._get_run_time() # get current time return s_next, reward, done, self._agent_pos_global, dist_vec, runtime, done_info, done_reason # return the next state, the reward "done" information and some debug and stat variables. def render(self): """function to render the path of the agent""" space_on_side = 2 def fcn(p_vec, gamma, d_vec): point = p_vec + gamma * d_vec return point point = [0, 0] road_right = np.array([[0, self._dist_to_crash_right]]) road_left = np.array([[0, self._dist_to_crash_left]]) if (self._agent_pos_global[0] + self._msr) < self._x_value_obstacle: length = self._x_value_obstacle + 10 else: length = self._agent_pos_global[0] + self._msr gamma = 1 while gamma < length: point = fcn(np.array([0, self._dist_to_crash_right]), gamma, np.array([1, 0])) road_right = np.append(road_right, [point], axis=0) point = fcn(np.array([0, self._dist_to_crash_left]), gamma, np.array([1, 0])) road_left = np.append(road_left, [point], axis=0) gamma += 1 p_obst = np.array([self._x_value_obstacle, self._y_values_obstacle]) obst = np.array([[self._x_value_obstacle, self._y_values_obstacle]]) gamma = 0.2 while gamma < abs(self._obstacle_width): point = fcn(p_obst, gamma, np.array([0, -1])) obst = np.append(obst, [point], axis=0) gamma += 0.2 ray_holder = [] yawangle = self._agent_yaw_global p_agent = self._agent_pos_global for idx, s in enumerate(self._sections): alpha = math.radians(s * self._angle) + yawangle d_agent_ray = np.array([np.cos(alpha), np.sin(alpha)]) ray = np.array([p_agent]) point = p_agent gamma = 1 while (np.sqrt((point[0]-p_agent[0])**2 + (point[1]-p_agent[1])**2)) < self._msr: temp = np.sqrt((point[0]-p_agent[0])**2 + (point[1]-p_agent[1])**2) point = fcn(p_agent, gamma, d_agent_ray) ray = np.append(ray, [point], axis=0) gamma += 1 ray_holder.append(ray) plt.xlim(self._dist_to_crash_left + space_on_side, self._dist_to_crash_right - space_on_side) for ray in ray_holder: plt.plot(ray[:, 1], ray[:, 0], 'b') plt.plot(self._agent_pos_global_holder[:, 1], self._agent_pos_global_holder[:, 0], 'g') plt.plot(road_right[:, 1], road_right[:, 0], 'r') plt.plot(road_left[:, 1], road_left[:, 0], 'r') plt.plot(obst[:, 1], obst[:, 0], 'r') plt.grid() plt.show() return 0 def _calc_reward(self, done): """calculate the reward""" # done == 0: all ok; done == -1: fail; done == 1: win # on crash reward: lose reward if done == -1: reward = self._lose_reward # reward if no crash and time is up and a min of progress has been made elif done == 1: reward = self._win_reward else: reward = 0 return reward def _build_state(self, dist_vec): """build state from x, y coordinates to matrix vector""" number_var = self._number_of_sections + 6 nn_input_vec = np.full(number_var, 0, dtype=np.float32) length_dist_vec = len(dist_vec[1]) for idx in range(length_dist_vec): nn_input_vec[idx] = dist_vec[1, idx] def curr_lane(): """function to find current lane""" if 0 > self._agent_pos_global[1] > self._road_width_right: curr_lane_type = 0 elif 0 < self._agent_pos_global[1] < self._road_width_left: curr_lane_type = 10 else: curr_lane_type = 20 return curr_lane_type def lane_left(): """function to find left lane""" if self._number_of_lanes_left == 0: lane_to_left = self._agent_pos_global[1] - (self._road_width_right / self._number_of_lanes_right) else: lane_to_left = self._agent_pos_global[1] + (self._road_width_left / self._number_of_lanes_left) if 0 > lane_to_left > self._road_width_right: lane_type_left = 0 elif 0 < lane_to_left < self._road_width_left: lane_type_left = 10 else: lane_type_left = 20 return lane_type_left def lane_right(): """function to find right lane""" lane_to_right = self._agent_pos_global[1] + (self._road_width_right / self._number_of_lanes_right) if 0 > lane_to_right > self._road_width_right: lane_type_right = 0 elif 0 < lane_to_right < self._road_width_left: lane_type_right = 10 else: lane_type_right = 20 return lane_type_right nn_input_vec[length_dist_vec + 0] = curr_lane() # current lane type nn_input_vec[length_dist_vec + 1] = lane_left() # lane type left nn_input_vec[length_dist_vec + 2] = lane_right() # lane type right nn_input_vec[length_dist_vec + 3] = self._agent_speed # current speed nn_input_vec[length_dist_vec + 4] = self._steering_angle # current steering angle nn_input_vec[length_dist_vec + 5] = self._agent_yaw_global # Yaw angle return nn_input_vec def _check_done(self, dist_vec): """check if episode has to terminate""" # done == 0: all ok; done == -1: fail; done == 1: win p_obst = np.array([self._x_value_obstacle, self._y_values_obstacle]) reason = 'unknown' done = 0 # Check if dist to obst is too low if ((p_obst[1] + self._dist_to_crash_y) > self._agent_pos_global[1] > (p_obst[1] + self._obstacle_width - self._dist_to_crash_y)) and ((p_obst[0] - self._dist_to_crash_x) < self._agent_pos_global[0] < p_obst[0]): done = -1 return done, 'crash obst' # hit left or right road limit if (self._agent_pos_global[1] > self._dist_to_crash_left) or (self._agent_pos_global[1] < self._dist_to_crash_right): done = -1 return done, 'hit boundry' # limit yaw angle in general but allow for greater yaw angle around obstacle if (self._x_value_obstacle - self._free_yaw_befor_after_obst) < self._agent_pos_global[0] < \ (self._x_value_obstacle + self._free_yaw_befor_after_obst): if (self._agent_yaw_global > self._yawangle_crash) or (self._agent_yaw_global < (-self._yawangle_crash)): done = -1 return done, 'yaw angle around obst' elif (self._agent_yaw_global > self._yawangle_crash_open_road) or (self._agent_yaw_global < (-self._yawangle_crash_open_road)): done = -1 return done, 'yaw angle open road' # if agent becomes too slow if self._agent_speed < self._speed_crash: done = -1 return done, 'speed to low' # if agent becomes too fast if self._agent_speed > self._speed_crash_max: done = -1 return done, 'speed to high' # if min dist is not covered when time is up if (self._current_runtime > self._runtime_max) and (self._agent_pos_global[0] < self._min_dist_to_success): done = -1 return done, 'min dist to win not coverd at runtime' if (self._current_runtime > self._runtime_max) and (self._agent_pos_global[0] > self._min_dist_to_success) \ and (done != -1): done = 1 return done, 'WIN' return done, reason def _execute_action(self, action): """function to execute the action. calling the function to calc motion""" if action == 3: #0 if self._agent_speed < self._max_speed: self._agent_speed += self._delta_speed delta_x, delta_y, psi = self._execute_motion(self._agent_speed, self._steering_angle) elif action == 4: #1 if self._agent_speed > self._min_speed: self._agent_speed -= self._delta_speed delta_x, delta_y, psi = self._execute_motion(self._agent_speed, self._steering_angle) elif action == 1: #2 # left (positiv angle) if self._steering_angle < self._max_steering_angle[1]: self._steering_angle += self._delta_steering_angle delta_x, delta_y, psi = self._execute_motion(self._agent_speed, self._steering_angle) elif action == 2: #3 # right (negativ angle) if self._steering_angle > self._max_steering_angle[0]: self._steering_angle -= self._delta_steering_angle delta_x, delta_y, psi = self._execute_motion(self._agent_speed, self._steering_angle) elif action == 0: #4 delta_x, delta_y, psi = self._execute_motion(self._agent_speed, self._steering_angle) else: delta_x, delta_y, psi = 0, 0, 0 if self._agent_speed > (self._speed_decay + self._speed_decay_offset): self._agent_speed -= self._speed_decay self._agent_speed = float("{0:.4f}".format(self._agent_speed)) # update the global class variables delta_pos = self._cos_transformation(delta_x, delta_y, self._agent_yaw_global) self._agent_pos_global = delta_pos self._agent_yaw_global += psi return 1 def _cos_transformation(self, local_x, local_y, psi): """function for coordinate transformation""" T = np.array([[np.cos(psi), -np.sin(psi), self._agent_pos_global[0]], [np.sin(psi), np.cos(psi), self._agent_pos_global[1]], [0, 0, 1]]) pos_loc = np.array([local_x, local_y, 1]) pos_global = T.dot(pos_loc) return_val = np.array([pos_global[0], pos_global[1]]) return return_val def _calc_dist_to_boundary(self): """function to calculate the distance to the surroundings""" dist_holder = np.zeros([2, self._number_of_sections]) p_obst = np.array([self._x_value_obstacle, self._y_values_obstacle]) p_agent = self._agent_pos_global yawangle = self._agent_yaw_global d_agent_orth = np.array([-np.sin(yawangle), np.cos(yawangle)]) # positiv 90° rotation p_road_limit_left = np.array([0, self._dist_to_crash_left]) p_road_limit_right = np.array([0, self._dist_to_crash_right]) b_obst = p_obst - p_agent b_road_left = p_road_limit_left - p_agent b_road_right = p_road_limit_right - p_agent def calc_intersection(a, b): """calculate the x, y of the intersection of two lines""" try: multipliers = np.linalg.solve(a, b) intersection = p_agent + d_agent_ray * multipliers[0] return intersection except np.linalg.linalg.LinAlgError: return np.array(['e', 'e']) def calc_dist(intersection): """calculate the distance to the intersection""" sensor_ray = intersection - p_agent dist = np.sqrt(sensor_ray[0]**2 + sensor_ray[1]**2) return dist def calc_intersec_side(intersection): """calculate if the intersection is ahed or behind""" side = d_agent_orth[1] * (intersection[0] - p_agent[0]) + d_agent_orth[0] * (intersection[1] - p_agent[1]) return side def append_dist_obst(idx, dist): """append the dist to obstacle to the holder""" if dist < self._msr: dist_holder[0, idx] = dist else: dist_holder[0, idx] = self._msr def append_dist(idx, dist): """append the dist to boundary to the holder""" if dist < self._msr: dist_holder[1, idx] = dist else: dist_holder[1, idx] = self._msr if dist_holder[1, idx] > dist_holder[0, idx]: dist_holder[1, idx] = dist_holder[0, idx] for idx, s in enumerate(self._sections): alpha = math.radians(s * self._angle) + yawangle d_agent_ray = np.array([np.cos(alpha), np.sin(alpha)]) a_obst = np.array([[np.cos(alpha), 0], [np.sin(alpha), 1]]) intersection_obst = calc_intersection(a_obst, b_obst) if intersection_obst[0] != 'e' and (calc_intersec_side(intersection_obst) > 0): if p_obst[1] > intersection_obst[1] > (p_obst[1] + self._obstacle_width): dist = calc_dist(intersection_obst) append_dist_obst(idx, dist) else: dist_holder[0, idx] = self._msr else: dist_holder[0, idx] = self._msr a_road = np.array(np.array([[np.cos(alpha), -1], [np.sin(alpha), 0]])) intersection_road_left = calc_intersection(a_road, b_road_left) if intersection_road_left[0] != 'e' and (calc_intersec_side(intersection_road_left) > 0): dist = calc_dist(intersection_road_left) append_dist(idx, dist) elif intersection_road_left[0] == 'e': append_dist(idx, dist) intersection_road_right = calc_intersection(a_road, b_road_right) if intersection_road_right[0] != 'e' and (calc_intersec_side(intersection_road_right) > 0): dist = calc_dist(intersection_road_right) append_dist(idx, dist) elif intersection_road_left[0] == 'e': append_dist(idx, dist) return dist_holder def _execute_motion(self, v, delta_degree): """function to execute the motion of a single track model with an odeint""" if v == 0: return 0, 0, 0 delta = math.radians(delta_degree) # side slip rigidity s_s_r_f = self._side_slip_rigidity_front * np.cos(delta) s_s_r_b = self._car_side_slip_rigidity_back # car sizing l_f = self._car_length_front l_b = self._car_length_back # inertia and mass c_i = self._car_inertia c_m = self._car_mass # Differential equation # psipp = ((((np.arctan((v * np.sin(beta) - l_f * psip) / (v * np.cos(beta)))) + delta) * s_s_r_f * l_f) - # ((np.arctan((v * np.sin(beta) - l_f * psip) / (v * np.cos(beta)))) * s_s_r_b * l_b)) / c_i # psip = yawrate # yawratep = ((((np.arctan((v * np.sin(beta) - l_f * yawrate) / (v * np.cos(beta)))) + delta) * s_s_r_f * l_f) - # ((np.arctan((v * np.sin(beta) - l_f * yawrate) / (v * np.cos(beta)))) * s_s_r_b * l_b)) / c_i # functions of derivatives def dy_fn_psi(y, t, v, delta, l_f, l_b, s_s_r_f, s_s_r_b, c_i, c_m): yawangle, yawrate, sideslipangle, dist = y alpha_front = (np.arctan((v * np.sin(sideslipangle) - l_f * yawrate) / (v * np.cos(sideslipangle)))) + delta alpha_back = np.arctan((v * np.sin(sideslipangle) + l_b * yawrate) / (v * np.cos(sideslipangle))) F_y_front = alpha_front * s_s_r_f F_y_back = alpha_back * s_s_r_b a_y = (F_y_front + F_y_back) / c_m dydt = [yawrate, (F_y_front * self._car_length_front - F_y_back * self._car_length_back) / c_i, yawrate - (a_y * np.cos(sideslipangle) / v), v] return dydt # initial integration values t = np.linspace(0, self._stepsize, (self._stepsize * self._ode_iterations + 1)) y0 = [0.0, 0.0, 0.0, 0.0] # call of the ode solver sol_psi = odeint(dy_fn_psi, y0, t, args=(v, delta, l_f, l_b, s_s_r_f, s_s_r_b, c_i, c_m)) # sol_psi[:,0] = yaw angle # sol_psi[:,1] = yaw rate # sol_psi[:,2] = slip angle # sol_psi[:,3] = abs(dist) # process return variables psi = sol_psi[self._ode_variables, 0] dist = sol_psi[self._ode_variables, 3] delta_x = np.cos(psi) * dist delta_y = np.sin(psi) * dist return delta_x, delta_y, psi # psi in radians def _pos_agent_initial_lane(self): """determine an initial lane""" lane_array = [] position = (self._road_width_right / self._number_of_lanes_right) / 2 for i in range(self._number_of_lanes_right): lane = position + i * (self._road_width_right / self._number_of_lanes_right) lane_array.append(lane) np_lane_array = np.array(lane_array) initial_lane_pos = np.random.choice(np_lane_array) return initial_lane_pos def _get_run_time(self): """get current time""" act_time_temp = time.clock() - self._t0 return act_time_temp
class Student(object): def __init__(self,subject, name, roll, marks): self.name = name self.subject = subject self.roll = roll self.marks = marks def getsubject(self): return self.subject def getmarks(self): return self.marks def getroll(self): return self.roll def __str__(self): return self.name + ' : ' + str(self.getsubject()) + ' :: ' + str(self.getroll()) +' ::: '+ str(self.getmarks()) def Markss(rec, name,subject, roll, marks): rec.append(Student(name,subject, roll, marks)) return rec Record = [] x = 'y' while x == 'y': subject = input('Enter the subject: ') name = input('Enter the name of the student: ') roll = input('Enter the roll number: ') marks = input('Marks: ') Record = Markss(Record, name, subject, roll, marks) x = input('another student? y/n: ') n = 1 for el in Record: print(n,'. ', el) n = n + 1
""" https://leetcode.com/problems/longest-substring-without-repeating-characters/ Example 1: Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: s = "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: s = "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. Example 4: Input: s = "" Output: 0 Constraints: 0 <= s.length <= 5 * 104 s consists of English letters, digits, symbols and spaces. """ def lengthOfLongestSubstring(s): hmap = {} j = 0 l = 0 ll = 0 print (s) for i in range(len(s)): print ("%s=%s max=%s" % (i, s[i], ll)) x = hmap.get(s[i], None) if x is None: hmap[s[i]] = i l += 1 else: j = max(j, x + 1) l = i - j + 1 ll = max(ll, l) print ('len=%s j=%s' % (l, j)) hmap[s[i]] = i ll = max(ll, l) #print (hmap) print (s[j:i+1]) return ll s = 'abcabcbb' #s = 'bbbbb' #s = 'pwwkew' #s = 'pwwkewabcdeabaghiabcdefgh' #s = 'pwwkewabcdpqrstuvwxyzeabaghiabcdefgh' print (lengthOfLongestSubstring(s))
""" https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/ Input: head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12] Output: [1,2,3,7,8,11,12,9,10,4,5,6] Input: head = [1,2,null,3] Output: [1,3,2] """ def flatten(head): curnode = head while curnode: childnode = curnode.child if childnode: curnode.child = None prev = curnode.next curnode.next = childnode childnode.prev = curnode while childnode.next: childnode = childnode.next childnode.next = prev if prev: prev.prev = childnode curnode = curnode.next return head