text
stringlengths
37
1.41M
import matplotlib.pyplot as plt from random_walk import RandomWalk while True: rw = RandomWalk(100) rw.fill_walk() # sets the dimensions for the plot plt.figure(figsize=(5, 5)) plt.plot(rw.x_values, rw.y_values,lw=1, ) # plot the first and last points /// Green = start /// Red = End plt.scatter(0, 0, c='green', s=50) plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', s=50) # remove the axes plt.axis('off') plt.show() # exit loop stop = input('Stop (y/n): ') if stop == 'y': break else: continue
from math import * def parite(a): if(a%2==0): print('le nombre est pair') else: print('le nombre est impaire') def polynome(a,b,c): d = pow(b,2) - 4 * a * c print(d) if(d==0): s = -b / 2*a float(s) print(s, 'est la solution ') elif(d > 0): sa = -b - sqrt(d) / 2*a float(sa) sb = -b + sqrt(d) / 2*a float(sb) print(sa, sb, 'sont les solutions de l equation') else: print('il n y a pas de solution') def bissextile(a): if(a%4==0 and a%100!=0 or a%400==0): print('l annee ', a, ' est bissextile') else: print('l annee ',a, 'n est pas bissextile') def convert(n): if(n<0): return 'Must be an positiv int' elif(n==0): return '' else: return(convert(n//2)+str(n%2)) print(convert(4589461)) def facto(n): if(n<2): return 1 else: return(facto(n-1)*n) print(facto(5)) def syracuse(n): if(n%2==0): n = n / 2 print(n) return (syracuse(n)) else: n = 3 * n + 1 print(n) return (syracuse(n)) def flot(n,acc): if (acc == 1): if (n>=0.5 and n!= 1.0): return "1" return "0" if(n == 1.0): return "0" + flot(1.0,acc-1) else: if (str(n)[0]=="1"): n -= 1 n *= 2 return str(n)[0] + flot(n,acc-1) def mantiss(n): ent = int(n) dec = n - int(n) #Conversion binaire binEnt = convert(ent) binDec = flot(dec,23-len(str(ent))) print(binEnt + binDec) exposant = (len(str(binEnt))) - 1 print(exposant) binExp= convert(exposant+127) print(binExp) print(binEnt, binDec, binExp) binEnt = binEnt[1:] print(binEnt, binDec, binExp) flott = binDec+binEnt+binExp if(n>0): flott = "0" + flott else: flott = "1" + flott print(flott, len(str(flott)))
import pandas as pd import numpy as np df = pd.DataFrame([['dog', True, 5], ['cat', False, 1]], columns=['animal', 'bark', 'age']) df.head() # np.where(df['animal'] > 2, True, False) df['hasError']= np.where(df['age'] > 2, 'True', 'False' ) df.head() print df
import math x=25 #y=5 #a=x+y #b=x-y #c=x/y #d=x%y #print("Addition is :",a) #print("Subtraction is :",b) #print("Division :",c) #print("Module is :",d) #print(math.sqrt(x)) #greeting = "hello" #name = "Siva" #message = greeting +" "+ name #print(message) # Boolean or Logical variabls # != or <> #== #< #> #<= #>= #and #or #not result = 4<5 print(result) #print(type(result)) result2 = not (5>2) print(result2) print(result or result2) # or either one is true its fine print(result and result2)
################### # Midterm # Due: Tuesday, November 28 2017 ################### # Array Almost Product # # Write a function that, given a list of integers, will return a list of # integers 'output' wherein the value of output[i] is the product of all the # numbers in the input array except for input[i]. # # You will lose points if your solution uses division. # Your solution should run in O(n) time. # Your solution should not allocate any space other than the output list. # # Example(s) # ---------- # Example 1: # Input: [2,3,4,5] # Output should be [3*4*5, 2*4*5, 2*3*4] # Output: [60, 40, 30, 24] # # Example 2: # Input: [3,6,9,-3,2,-2] # Output: # [648, 324, 216, -648, 972, -972] # # Parameters # ---------- # arr : List[int] # A list of integers. You may assume len(arr) > 1 # # Returns # ------- # List[int] # Returns a list where every element of the list is the product of # all the numbers in the input list except for the number at the index # being evaluated. # def array_almost_product(arr): round_one = [] agg = 1 for i in range(0, len(arr)): if i == 0: round_one.append(1) else: round_one.append(agg*arr[i-1]) agg = agg*arr[i-1] round_two = [] agg = 1 for i in range(len(arr)-1, -1, -1): if i == (len(arr)-1): round_two.append(1) else: round_two.insert(0, agg*arr[i+1]) agg = agg*arr[i+1] final = [] for i in range(0, len(arr)): final.append(round_one[i]*round_two[i]) return final #print(array_almost_product([2,3,4,5])) #print(array_almost_product([3,6,9,-3,2,-2])) # Pascal's Triangle # # Write a function that, given an index i, returns the i'th row of Pascal's Triangle. # # This Wikipedia page on Pascal's triangle may be useful: # https://en.wikipedia.org/wiki/Pascal%27s_triangle # # Your solution should run in O(i) time and use O(i) space. # # Example(s) # ---------- # Example 1: # Input: 2 # Output: [1,2,1] # # Example 2: # Input: 6 # Output: [1,6,15,20,15,6,1] # # Parameters # ---------- # i : int # The row index of the row of Pascal's Triangle you are searching for # # Returns # ------- # List[int] # Returns the i'th row of Pascal's Triangle as a list of ints # def pascals_triangle(i): pascals_line = [1] for j in range(0, i): pascals_line.append(pascals_line[j]*(i-j)/(j+1)) return pascals_line #print(pascals_triangle(2)) #print(pascals_triangle(6)) # Alive People # # Write a function that, given a list of strings representing a person's birth year: age of death, # will return the year that had the most people alive (inclusive). If there are multiple years that tie, return the earliest. # You can think of a birthdate and a deathdate as a range of years. Of all the birth years in the list, find the one where the highest # amount of people in the list were still alive. # # Examples # ---------- # Example 1: # Input: ["1920: 80", "1940: 22", "1961: 10"] # Output: 1961 # # Example 2: # Input: ["2000: 46", "1990: 17", "1200: 97", "1995: 20"] # Output: 2000 # # Parameters # ---------- # people : List[string] # A list of strings each representing a birth year and final age # # # Returns # ------- # int # Returns earliest year with the most people alive # def alive_people(people): birth_year = [] death_year = [] ages = [] for i in people: temp_one = i[0:4] temp_two = i[6:8] birth_year.append(int(temp_one)) ages.append(int(temp_two)) for i in range(0, len(people)): death_year.append(birth_year[i]+ages[i]) people_alive = [] birth_years = get_years(birth_year) for i in range(0, len(birth_years)): count = 0 for j in range(0, len(birth_year)): if is_alive(birth_years[i], birth_year[j], death_year[j]) == True: count+=1 people_alive.append(count) max_year = birth_years[people_alive.index(max(people_alive))] for i in range(0, len(birth_years)): if people_alive[i] == max(people_alive) and max_year > birth_year[i]: max_year = birth_year[i] return max_year def get_years(years): births = [] for i,j in enumerate(years): if j not in births: births.append(j) return births def is_alive(year, birth, death): if year >= birth and year <= death: return True else: return False #print(alive_people(["1920: 80", "1940: 22", "1961: 10"])) #print(alive_people(["2000: 46", "1990: 17", "1200: 97", "1995: 20"])) #print(alive_people(["2000: 46", "1990: 17", "1200: 97", "1993: 2", "1992: 8", "1993: 4", "1990: 8"])) # String, My One True Love # # Your favorite course staff member really likes strings that have the same occurences of letters. # This means the staff member likes "aabbcc" and "ccddee" and even strings like "abcabcabc" # # But the person who wrote all of your homewokrs wants to trick the staff with really long string, # that either could be the string that the staff member likes, or something that becomes such a string # when you remove a single character from the string. # # Your goal is to return True if it's a string that the homework creator made # and False otherwise. # # Restrictions # ------------ # Inputs are only given as lower case alphabets, without punctuation, spaces, etc. # Your solution must run in O(n) time. # # Example(s) # ---------- # Example 1: # Input: "abcbabcdcdda" # There is 3 a's, 3 b's, 3 c's, and 3 d's. That means it is a very likable string! # Output: # True # # Example 2: # Input: "aaabbbcccddde" # Again there are 3 a's, 3 b's, 3 c's, and 3 d's. However, we also have 1 e! # We can remove this string however, and it will become a likeable string, so this is valid. # Output: # True # # Example 3: # Input: "aaabbbcccdddeeffgg" # This string is similar to the other ones, except with 2 e's, f's and g's at the end. # To make this string likable, we need to remove the 2 e's, f's, and g's or we can remove # one a, b, c, and d. However all of these require more than one removal, so it becomes invalid. # Output: # False # # Parameters # ---------- # the_string : str # The string to check whether it is likeable or not. # # Returns # ------- # bool # True if the string is likable, or removing a single character makes it likable. # False if the string is not likeable, and we need to remove more than 1 character to become likable. def string_my_one_true_love(the_string): letters = get_letters(the_string) counts = [] for i in range(0, len(letters)): temp = the_string.count(letters[i]) counts.append(temp) if len(set(counts)) > 2: return False if len(set(counts)) == 1: return True numbers = get_nums(counts) instances = [0, 0] for i,j in enumerate(counts): if j == numbers[0]: instances[0]+=1 elif j == numbers[1]: instances[1]+=1 if instances[0] > 1 and instances[1] > 1: return False else: return True def get_letters(string): letters = [] for i,j in enumerate(string): if j not in letters: letters.append(j) return letters def get_nums(numbers): nums = [] for i,j in enumerate(numbers): if j not in nums: nums.append(j) return nums #print(string_my_one_true_love("abcbabcdcdda")) #print(string_my_one_true_love("aaabbbcccddde")) #print(string_my_one_true_love("aaabbbcccdddeeffgg")) #print(string_my_one_true_love("aaaahfiieeqwertyuioasdghjjojo")) #print(string_my_one_true_love("aaaaaabbbbbbccccccdddffdddeeeeee")) #print(string_my_one_true_love("aaaaaabbbbbbccccccdddfdddeeeeee")) #print(string_my_one_true_love("sjfhefvbejfvkfsjfhkdscbrekvuievbcieucfegskcbdhkhecbhkscbhdkhscbheksceiecbfkshcbkdsfc")) #print(string_my_one_true_love("qqqqqqqqqqhhhhhhhhhhhiiiiiiiiiiyyyyyyyyyy")) # Longest Palindromic Substring # # Given a string, find the longest substring that is a palindrome. If # # Ideal runtime: o(n), but we will give full credit for o(n^2) solutions. # # RESTRICTIONS: # There is guarunteed to be exactly 1 longest palindrome # # Example(s) # ---------- # Example 1: # Input: "ABBAC" # # Output: # "ABBA" # # Example 2: # Input: "A" # # Output: # "A" # # Parameters # ---------- # word: str # String input # # Returns # ------- # String # Longest Palindrome substring def longest_palindrome_substring(word): results = [] if len(word) == 1: return word else: for i in range(0, len(word)): for j in range(0, i): sub_str = word[j:i+1] if sub_str == sub_str[::-1]: results.append(sub_str) max_index = 0 for i in range(1, len(results)): if len(results[i]) > len(results[max_index]): max_index = i return results[max_index] #print(longest_palindrome_substring("ABBAC")) #print(longest_palindrome_substring("A")) # Longest Unique Substring # # Given a string, find the longest unique substring # # Ideal runtime: o(n). full credit only given for o(n). # Do not consider case. Therefore, 'A' and 'a' are considered the same character # # RESTRICTIONS: # There is guarunteed to be exactly 1 longest unique substring # # Example(s) # ---------- # Example 1: # Input: "zzAabcdefFgg" # # Output: # "abcdef" # # Example 2: # Input: "AA" # # Output: # "A" # # Parameters # ---------- # word: str # String input # # Returns # ------- # String # Longest unique substring def longest_unique_substring(word): max_len = 0 longest = "" for i in range(0, len(word)): sub_str = word[i:].lower() chars = set() for j,c in enumerate(sub_str): if c in chars: break else: chars.add(c) else: j+=1 if j > max_len: max_len = j longest = word[i:i+j] return longest #print(longest_unique_substring("zzAabcdefFgg")) #print(longest_unique_substring("AA")) #print(longest_unique_substring("AWsefghyAasvevevfverv")) # Three Sum # # Given an array S of n integers and constant 'target', are there elements a, b, c in S such that # a+b+c = target? Find all unique triplets in the array which gives the sum of target. # return a 2d list, where all inner lists are triplets. There may be more than # one pair of triplets. # # Runtime: o(n^2) will get full credit. # # # Example(s) # ---------- # Example 1: # Input: [-1, 0, 1, 2, -1, -4], 0 # # Output: # [ # [-1, 0, 1], # [-1, -1, 2] # ] # # # Parameters # ---------- # arr: array # array of numbers # # target: int # target integer # # Returns # ------- # 2d array # 2d list, inner lists are triplets that add up to target. def three_sum(arr, target): new_arr = sorted(arr) final_arr = [] for i in range(len(new_arr)): temp = target - new_arr[i] j = i+1 k = len(new_arr)-1 while j < k: s_sum = new_arr[j] + new_arr[k] if s_sum < temp: j+=1 elif s_sum > temp: k-=1 else: sum_arr = [new_arr[i], new_arr[j], new_arr[k]] if sum_arr not in final_arr: final_arr.append(sum_arr) j+=1 k-=1 return final_arr #print(three_sum([-1, 0, 1, 2, -1, -4], 0)) #print(three_sum([-1, 0, 1, 2, -1, -4], 0)) #print(three_sum([-1, 0, 1, 4, 0, 6, -1, 1], 5)) # Zero Sum # # Return True if a subarray (not any element) summed can create 0. # Otherwise return False. # # Time Complexity # ------------ # Optimal time complexity is O(n). You can assume the running time of updating a dictionary is O(1) # # You CANNOT assume the order given will be sorted. # # Example(s) # ---------- # Example 1: # Input: zero_sum([0, 1, 2, 3, 4, 5]) # We need to see if a subarray can create 0. # The first element gives us 0. So there is a subarray that can create 0. # Output: # True # # Example 2: # Input: zero_sum([10, 20, -20, 3, 21, 2, -6]) # We need to see if a subarray can create 0. # The subarray [20, -20] can create zero. # Output: # True # # Parameters # ---------- # arr: array # array of numbers def zero_sum(arr): sums = {} total = 0 for i in arr: total += i try: if i == 0 or total == 0 or sums[total] == 1: return True else: sums[total] = 1 except: sums[total] = 1 return False #print(zero_sum([0, 1, 2, 3, 4, 5])) #print(zero_sum([10, 20, -20, 3, 21, 2, -6])) #print(zero_sum([1, 2, 3, 4, 5, 6])) #print(zero_sum([1, 2, -2, 3, 4, 5, 1, 3, -9])) #print(zero_sum([2, -6, 4, 1, 2, 3, 4, 5, 6])) # Stair Stepping # # One day, Alice's power went out in her house. # Because Alice is currently in 374, she decided to count how many distinct ways she can climb up her staircase (from the bottom to the last stair). Alice is able to skip some stairs because she has very long legs. # Help Alice determine the number of distinct ways she can climb up the staircase given the number of stairs on the staircase (stairs) and the maximum number of stairs she can skip at each one of her steps (skip). # # Time Complexity # --------------- # Optimal time complexity is O(stairs). # Example 1: # stairs = 3 # skip = 0 # # # # ## # ### # 123 # # Alice cannot skip any stairs, so there is only one way. # BOTTOM -> 1 -> 2 -> 3 # # Example 2: # stairs = 3 # skip = 1 # # # # ## # ### # 123 # # Alice can skip one stair at most, so there are 3 ways. # BOTTOM -> 1 -> 2 -> 3 # BOTTOM -> 1 -> 3 # BOTTOM -> 2 -> 3 # # Example 3: # stairs = 5 # skip = 2 # # # # ## # ### # #### # ##### # 12345 # # Alice can skip two stairs at most, so there are 13 ways. # # BOTTOM -> 1 -> 2 -> 3 -> 4 -> 5 # BOTTOM -> 1 -> 2 -> 3 -> 5 # BOTTOM -> 1 -> 2 -> 4 -> 5 # BOTTOM -> 1 -> 3 -> 4 -> 5 # ... # ... # ... # BOTTOM -> 3 -> 5 # # Note that Alice must start at the "0th" step and finish exactly at the Nth step where N is the number of stairs. def staircase_ways(stairs, skip): ways = [1] + [None] * stairs for i in range(1, stairs+1): ways[i] = sum(ways[max(0, i-(skip+1)):i]) return ways[stairs] #print(staircase_ways(3, 0)) #print(staircase_ways(3, 1)) #print(staircase_ways(5, 2)) # Odd One Out # # Given an array of 2n + 1 integers where each integer except one is duplicated, return the number that only appears once in the array. # # Time complexity # --------------- # Optimal time complexity is O(n). Try to only use O(1) space/memory. # # Example 1: # arr = [10] # Answer is 10. # # Example 2: # # arr = [3, 2, 1, 3, 2, 4, 4] # Answer is 1. # # # Example 3: # arr = [-1, 1, 0, 5, 0, 2, 1, 2, 5] # Answer is -1. def odd_one_out(arr): for i in range(0, len(arr)): temp = arr[i] if arr.index(temp) == (len(arr) - arr[::-1].index(temp) - 1): return temp #print(odd_one_out([10])) #print(odd_one_out([3, 2, 1, 3, 2, 4, 4])) #print(odd_one_out([-1, 1, 0, 5, 0, 2, 1, 2, 5])) #print(odd_one_out([-1, 2, 3, 5, 5, 3, 2, -1, 4, 5,6,7,8,7,6,5,8,9,9,2,3,5,6,7,7,6])) # Circular Shift # # Given an array (arr) and a shift value (k), shift the array to the # right by k. If the rightmost element will become out of bounds, move # it to the front of the array (hence circular shift). # # Time complexity # --------------- # Optimal complexity is O(len(arr)). Try using only O(1) space/memory # # Example 1: # arr = [1, 2, 3, 4, 5] # k = 1 # Returns [5, 1, 2, 3, 4] # # Example 2: # arr = [1, 2, 3, 4, 5] # k = 2 # Returns [4, 5, 1, 2, 3] # # Example 3: # arr = [1, 2, 3] # k = 10 # Returns [3, 1, 2] def circular_shift(arr, k): r = k % len(arr) return arr[-r:] + arr[:-r] #print(circular_shift([1, 2, 3, 4, 5], 1)) #print(circular_shift([1, 2, 3, 4, 5], 2)) #print(circular_shift([1, 2, 3], 10)) # Reverse Linked List # # Given a linked list, reverse it in-place # # Time Complexity # --------------- # Optimal time complexity is O(n). Try to use only O(1) memory. class Node: def __init__(self, data=None, next_node=None): self.data = data self.next_node = next_node def reverse_list(head): if head == None: return None current = head previous = None while current != None: tail = current.next_node current.next_node = previous previous = current current = tail return previous
help(round) round(1.56666,ndigits=4) help(print) a = 10 b = 20 print(a,b,sep=' xYx ', end='\t', flush=True) print(10) import sys import time for i in range(10): print(i, end =' ') sys.stdout.flush() time.sleep(1) for i in range(10): print(i, end=' ', flush=True) def least_difference(a, b, c): diff1 = abs(a-b) print('diff 1',diff1) diff2 = abs(b-c) print('diff 2',diff2) diff3 = abs(a-c) print('diff 3',diff3) return min(diff1, diff2, diff3) print('Total least difference',least_difference(1,2,3)) print( "Total 1:", least_difference(1, 5, 10), "\nTotal 2:", least_difference(10, 20, 40), "\nTotal 3:", least_difference(30, 60, 90) ) help(least_difference) def least_difference(a, b, c): """ Return Value of A,B,C >>> least_difference(1, 2, 3) 1 """ diff1 = abs(a - b) diff2 = abs(b - c) diff3 = abs(a - c) return min(diff1, diff2, diff3) help(least_difference) def least_difference(a, b, c): """ Return the smallest difference between any two numbers among a, b, c """ diff1 = abs(a - b) diff2 = abs(b - c) diff3 = abs(a - c) min(diff1, diff2, diff3) print( least_difference(1, 10, 100), least_difference(1, 10, 10), least_difference(5, 6, 7) ) mystery = print() print(mystery) print(1, 2, 3, sep = ' < ') print(1, 2, 3) def greet(who="Colin"): print("Hello", who) greet() greet(who="Kaggle") greet("world") def mult_by_five(x): return 5 * x def call(fn, arg): """Call fn on arg""" return fn(arg) def squared_call(fn, arg): """Call fn on the result of calling fn on arg""" return fn(fn(arg)) print( call(mult_by_five, 1), squared_call(mult_by_five, 2), sep = '\n' ) def mod_5(x): """Return the remainder of x after dividing by 5""" return x % 5 print( 'Which number is biggest?', max(100, 51, 14), 'Which number is the biggest modulo 5?', max(100, 51, 14, key=mod_5), sep = '\n' )
# Import everything from DriveLibraries to allow interaction with the robot, and to create a Robot object from DriveLibraries import * # Used for running a mission in a killable way import multiprocessing # Some things need delays from time import sleep # Define variables with null values so they can be used as global variables later Missions = None mission = None robot = None programs = [] numPrograms = 0 loopIndex = 0 # count is used to determine which mission should be run, starts at 1 not 0 count = 1 def init(confFile): """ Creates a ``Robot`` oject named ``robot`` using the filename given in ``confFile``, loads all mission functions from ``Missions.py`` into ``programs`` alphabetically, using the three-character prefix on all mission function names, and shows the first mission name on the display. """ # Declare global variables global programs global numPrograms global robot global Missions # Instantiate a Robot object named "robot" robot = Robot(confFile) # Now that a robot object exists, the mission programs, which need a robot object, can be imported import Missions # This is how the menu auto-adds missions. dir() returns a list of all objects contained in whatever it was given. # However, there are a lot more objects than just the mission functions in Missions.py, so the list needs to be pruned. programs = dir(Missions) # Setting up some varibles for pruning i = 0 index = -1 length = len(programs) # This will repeat the mission check on every element of the list of all objects in Missions.py while i < length: # This checks if the name of the object currently being checked starts with a##, like all missions should. if not ((programs[index][0] == "a") and (programs[index][1].isnumeric()) and (programs[index][2].isnumeric())): # If it does not, the object will be removed from the programs list, as it is not a mission programs.pop(index) else: # If it is, the index varible wil be decreased by one to skip over the mission program the next time around # (the scan starts at the back of the list). index -= 1 # Increment i by 1 every loop cycle i += 1 # Now that the only things left in programs are missions, the length of programs can be used as the number of missions # (used in AddCount and MinusCount, for rollover). numPrograms = len(programs) # Clear the display robot.disp.clear() # Dislpay the first mission name (the [3:] is a string split; it prevents the a## from being displayed) robot.disp.text_grid(programs[0][3:], font=robot.fonts.load('timR24')) def runCurrentMission(): """ Gets the currently selected mission from ``Missions.py`` and runs it. Once the mission has completed, it stops the motors and allows them to glide to allow for manual robot positioning. """ # Finds the object in Missions.py that has the same name as the currently selected mission # (count - 1 is used because count starts at 1 not 0), and creates the function pointer # method_to_call, which is the selected mission method_to_call = getattr(Missions, programs[count - 1]) # Runs the selected mission method_to_call() # Stops the drive motors and allows them to glide robot.rm.off(brake=False) robot.lm.off(brake=False) # Attempts to stop auxillary motors. If there are none, the try blocks will fail and the program will continue try: robot.m1.off(brake=False) except: pass try: robot.m2.off(brake=False) except: pass def initthread(): """ Creates the ``mission`` process that is used to run missions while being able to abort said mission. This is also done in ``run()``, but needs to be done before other things will work properly """ # Declare mission as a global variable because it is being edited global mission # Create a process that will call runCurrentMission mission = multiprocessing.Process(target=runCurrentMission) def run(): """ Called when the center button is pressed, this creates a process to run the current mission, reset the gyro to zero, then start the mission. """ # Declare mission as a global variable because it is being edited global mission # Create a process that will call runCurrentMission mission = multiprocessing.Process(target=runCurrentMission) # Reset the gyro angle to zero robot.zeroGyro() # Start the mission process mission.start() def display(): """ Display the currently selected mission on the screen """ # Read the currently selected mission from the programs list, using count # The [3:] is a string split so the a## prefix is not displayed, and 1 is subtracted # from count because count starts at one, while list indexes start at zero. name = programs[count - 1][3:] # Display the mission name on the screen, in 24pt Times New Roman robot.disp.text_grid(name, font=robot.fonts.load('timR24')) def abort(): """ Kills the current mission process, stops the motors and allows them to glide, and undoes auto-advance """ # Kill the mission process mission.terminate() # Wait for it to completely finish mission.join() # Stop the drive motors robot.lm.off(brake=False) robot.rm.off(brake=False) # Attempts to stop auxillary motors. If there are none, the try blocks will fail and the program will continue try: robot.m1.off(brake=False) except: pass try: robot.m2.off(brake=False) except: pass # Undo the auto-advance so the mission could easily be redone minusCount() display() def addCount(): """ Increases the ``count`` variable by one, resetting to one when numPrograms would have been ecxeeded """ # Declare count as global because it is being edited global count # Take the modulo of count and numPrograms (to rollover), then add one count = (count % numPrograms) + 1 def minusCount(): """ Decreases the ``count`` variable by one, resetting to numPrograms when count would have gone below 1 """ # Declare count as global because it is being edited global count # (count + (numPrograms - 2)) % numPrograms is equal to two less than count, with the desired rollover behavior. # However, that is decreasing by two, and its range is zero to numPrograms - 1. Thus, 1 is added to the result to # correct the range and decrease by only one. count = ((count + (numPrograms - 2)) % numPrograms) + 1 def checkDrift(): """ Turns the brick light green if the gyro reports a rate within one degree/second of zero, and red otherwise. This is used as a signal to the user that the gyro may be drifting. """ # Read the gyro angle and rate. Angle and rate mode is consistantly used because switching modes resets the angle. ar = robot.gs.angle_and_rate # angle_and_rate returns a list; this function only needs rate rate = ar[1] # Check if the reported rate is outside of 1 degree/second from zero if rate < -0.5 or rate > 0.5: # If it is, turn both lights red (lights are turned off to clear) robot.led.all_off() robot.led.set_color('LEFT', 'RED') robot.led.set_color('RIGHT', 'RED') else: # Otherwise, reset the lights to green robot.led.reset() def displaySensor(): """ Periodically displays the color and gyro sensor values at the bottom of the screen. """ # loopIndex is equal to zero every hundeth loop cycle, so this function only runs that frequently. # This is to prevent flickering of the printout. if loopIndex == 0: # Draws a white rectangle where the sensor values will be. This effectively clears only # that section of the screen. robot.disp.rectangle(False, 0, 89, 177, 120, 'white', 'white') # Display commands do not take effect until update() is called robot.disp.update() # Displays the current calibrated color sensor RLI reading in the correct place in 10pt Courier New robot.disp.text_pixels("P1, Color:" + str(robot.correctedRLI), False, 40, 90, font=robot.fonts.load('courR10')) # Displays the current gyro sensor angle reading robot.disp.text_pixels("P2, Gyro:" + str(robot.correctedAngle), False, 40, 100, font=robot.fonts.load('courR10')) # Apply pending changes robot.disp.update() def calibrate(): """ Provides a UI wrapper for the built-in ``robot.gs.calibrate`` function to calibrate the gyro Use: When called, the brick lights will turn yellow, the robot will emit a low pitched beep that is not used anywhere else, and when calibration is complete, the robot will emit a normal beep and the lights will turn green again. The robot should be completely still between the two beeps while the lights are yellow. """ # Turn the lights yellow (clearing first) robot.led.all_off() robot.led.set_color('LEFT', 'YELLOW') robot.led.set_color('RIGHT', 'YELLOW') # Unique low pitched beep (Don't touch the robot!) robot.spkr.beep('-f 369.99') # Calibrate the gyro robot.gs.calibrate() # Ensure calibration has completely finished sleep(1) # Normal beep (Calibration finished; safe to touch robot) robot.spkr.beep() # Reset the lights to green robot.led.reset()
""" Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 (both included). The numbers obtained should be printed in a comma-separated sequence on a single line. Hints: Consider use range(#begin, #end) method """ if __name__ == '__main__': begin = int(input("Ingrese rango de inicio ")) end = int(input("Ingrese rango final ")) lista = [] for x in range(begin, end): if x % 7 == 0 and x % 5 != 0: lista.append(x) print(lista)
# This file holds the minimax implementation. import random, sys, math from state import State, X, O, BLANK # Return the move which the A.I. should take for the current state of the board. # @arg state should be an instance of state.State # @arg depth is the limit on the search depth. It is not supported at this time, however, because the search space is small enough to search in its entirety. # @arg is_seeking_max is True if the current player is X and False if the current player is O def minimax(state, depth, is_seeking_max): if BLANK not in state.cells: raise Exception('minimax should not be called on a terminal state') if state.get_winner(): raise Exception('minimax should not be called on a terminal state') if depth == 0: raise Exception('depth should not be 0 on first minimax call') if state.get_is_pristine(): # Randomly choose between corners and center return random.choice([ State.decode(x) for x in ['A1','A3','B2','C1','C3']]) else: score = _minimax_recursive(state, depth, is_seeking_max) return state.move # Return the most favourable score for the player who is indicated by the is_seeking_max argument. # This function also sets a field `move` on `state` # This should be called only by the `minimax` function. def _minimax_recursive(state, depth, is_seeking_max): # Handle terminal state winner = state.get_winner() if winner != BLANK: return winner * sys.maxsize # Recurse else: free_cells = state.get_free_cells() if len(free_cells) == 0: return 0 random.shuffle(free_cells) # Recurse next_states = _get_next_states(state, free_cells, is_seeking_max) # next_state.prev = state scores = [_minimax_recursive(s, depth-1, not is_seeking_max) for s in next_states] comparison_fn = max if is_seeking_max else min # Get best score, next_state, move = comparison_fn(list(zip(scores, next_states, free_cells)), key=lambda x: x[0]) # Remeber that each 'score' is a tuple of (score, choice) state.move = move if abs(score) > 999: score /= 2 # penalize slower victories return score # Create new states for all possible moves indicated by `free_cells`. These # will be used in our search of the game tree. def _get_next_states(state, free_cells, is_seeking_max): cell_value = 1 if is_seeking_max else -1 next_states = [state.clone() for x in free_cells] for i, cell in enumerate(free_cells): next_states[i].set(cell, cell_value) return next_states # This is a heuristic to compute a value for a given state so that the most # favourable state among a selection of possible future states can easily be # identified. def calc_score(state): working = 0 def worth(triplet): if triplet[0] == triplet[1] == triplet[2]: return sys.maxsize * triplet[0] elif BLANK not in triplet: return 0 else: return sum(triplet)*2 # Horizontal for r in range(3): triplet = state.cells[r::3] working += worth(triplet) # Vertical for c in range(3): triplet = state.cells[c*3:(c+1)*3] working += worth(triplet) # Diagonal working += worth(state.cells[0::4]) # 0,4,8 working += worth(state.cells[2:7:2]) # 2,4,6 # Add points for corners and center working += sum(state.cells[0::2]) # Return return working
#print("Elegir una operacion:\n1:area del circulo\n2:Ley de gases nobles\n3:formula de la distancia en MRUV\n4:ley dde gravitacion universal\n5:Pitagoras\n6:volmen del cilindro\n7:area del triagulo") def sumar(a,b): sum = a + b return sum def restar(x,y): resta = x - y return resta def multiplicar(x,y): mult = x*y return mult def dividir(x,y): div = x/y return div def area_ciculo(r): S = 3.1416 * pow (r,2) return S def Presion (V,n,R,T): P = (n*R*T)/V return P def Volumen(P,n,R,T): V = (n*R*T) / P return V def Numero_moles(P,V,R,T): n = (P*V) / (R*T) return n def Constante(P,V,n,T): R = (P*V) / (n*T) return R def Temperatura(P,V,n,R): T = (P*V) / (n*R) return T def distancia(v,t,a): d = ( v * t ) + (1/2)* a * pow(t,2) return d def ley_de_gravitacion_universal(G,m1,m2,r): F = (G*m1*m2)/(pow(r,2)) return F def pitagoras_cateto(a,c): import math b = math.sqrt(pow(a,2) - pow(c,2)) return b def pitagoras_hipotenusa(b,c): import math a = math.sqrt(pow(b,2) + pow(c,2)) return a def volumen_cilindro (r,h): V = 3.1416 * pow(r,2) * h return V def area_triangulo(b,h): A = (b*h)/2 return A def main(): calculadora() def calculadora(): print('Selecciona una operacion: \n1:suma-\n2:resta\n3:multiplicacion\n4:division\n5:area del circulo\n6:Ley de gases nobles\n7:formula de la distancia en MRUV\n8:ley dde gravitacion universal\n9:Pitagoras\n10:volmen del cilindro\n11:area del triagulo\n12:terminamos') print("ingresar el numero de la operacion que desea realizar:") opcion = int(input()) #while (opcion <=4): if opcion == 1: print ("Suma") x = float(input("Primer numero: ")) y = float(input ("Segundo numero: ")) print ("La suma es:", sumar(x,y)) elif opcion == 2: print ("Resta") x = float(input("Primer numero: ")) y = float(input("Segundo numero: ")) print("La resta es:", restar(x,y)) elif opcion == 3: print ("Multiplicacion") x = float(input("Primer numero: ")) y = float(input("Segundo numero: ")) print ("La multiplicacion es: ", multiplicar(x,y)) elif opcion == 4: print ("Division") x = float(input("Primer numero: ")) y = float(input("Segundo numero: ")) print ("la division es:", dividir(x,y)) elif opcion == 5: print("Area del circulo, la formula es igual a:S=π(r^2)") r = int(input("Ingresar el radio: ")) if r == 0: print("El radio no puede ser 0") elif r < 0: print("el radio no puede ser negativo") elif r > 0: print("El area del circulo es:",area_ciculo(r)) elif opcion == 6: print("Ley de gases nobles, la formula es igual a: P*V = n*R*T\nDonde:\nP=presion\nV:Volumen\nn:Numero de moles\nR:Constante de los gases ideales\nT: Temperatura") print("Que desea calcular:\n1:Presion\n2:Volumen\n3:Numero de moles\n4:Constante de los gases ideales\n5: Temperatura") ley = int(input()) if ley == 1: print ("Presion") V = float(input("Ingrese el Volumen: ")) n = float(input("Ingrese el numero de moles: ")) R = float(input("Ingrese la Constante de los gases: ")) T = float(input("Ingrese la Temperatura: ")) print("La presion es:",Presion (V,n,R,T)) elif ley ==2: print ("Volumen") P = float(input("Ingrese la Presion: ")) n = float (input("Ingrese el numero de moles: ")) R = float(input("Ingrese la Constante de los gases: ")) T = float(input("Ingrese la Temperatura: ")) print("El volumen es:",Volumen (P,n,R,T)) elif ley == 3: print ("numero de moles") P = float(input("Ingrese la Presion: ")) V = float(input("Ingrese el Volumen: ")) R = float(input("Ingrese la Constante de los gases: ")) T = float(input("Ingrese la Temperatura: ")) print("El numero de moles es:",Numero_moles (P,V,R,T)) elif ley == 4: print ("Constante de los gases ideales") P = float(input("Ingrese la Presion: ")) V = float(input("Ingrese el Volumen: ")) n = float(input("Ingrese el numero de moles: ")) T = float(input("Ingrese la Temperatura: ")) print("La constante de los gases ideales es:",Numero_moles (P,V,n,T)) elif ley == 5: print ("Temperatura") P = float(input("Ingrese la Presion: ")) V = float(input("Ingrese el Volumen: ")) n = float(input("Ingrese el numero de moles: ")) R = float(input("Ingrese la Constante de los gases: ")) print("La temperatura es:",Numero_moles (P,V,n,R)) else: print ("entrada no valida") elif opcion == 7: print (" distancia en MRUV") v = float(input("Ingrese la velocidad inicial: ")) t = float(input("Ingrese el tiempo: ")) a = float(input("Ingrese el aceleracion: ")) print("La distancia recorrida es:",distancia(v,t,a)) elif opcion == 8: print("Fuerza gravitatoria, cuya formula es:F = (G*m1*m2)/(r^2)\nDonde:\nG:es la contante de gravitacion universal cuyo valor es G = 6,67*10^-11 [N·m^2/kg^2]\nm1 y m2: son las masas de los cuepos que interaccionan\nr: es la distancia que los separa.") m1 = float(input("Ingrese la masa del primer cuerpo en [Kg]: ")) m2 = float(input("Ingrese la masa del segundo cuerpo en [Kg]: ")) r = float(input("Ingrese la distancia que separa a dichos cuerpos: ")) G = 6.67 * pow(10,-11) print("La distancia recorrida es:",ley_de_gravitacion_universal(G,m1,m2,r)) elif opcion == 9: print("Teorema de pitagoras, cuya pormula es a^2 = b^2 + c^2, Donde:\na:hipotenusa\nb,c:catetos") print("que desea calcular:\n1:cateto\n2:hipotenusa") pitagoras = int(input()) if pitagoras == 1: print("cateto") a = float(input("Ingresar la hipotenusa: ")) b = float(input("Ingresar el cateto que se tiene como dato: ")) if a < b: print ("la hipotenusa no puede ser mas pequeña que un cateto") else: print("El cateto es igual a :", pitagoras_cateto(a,b)) elif pitagoras == 2: print("Hipotenusa") b = float(input("Ingresar el pimer cateto: ")) c = float(input("Ingresar el segundo cateto: ")) print("La hipotenusa es igual a :", pitagoras_hipotenusa(b,c) ) elif opcion == 10: print ("Volumen del cilindro") r = float(input("ingrese en radio de la base: ")) h = float(input("Ingrese la altura del cilindro: ")) print("El volumen del cilindro es: ",volumen_cilindro (r,h)) elif opcion == 11: print("Area del triángulo") b = float(input("Ingrese la base de triangulo")) h = float(input("Ingrese la altura del triangulo")) print("El area del triangulo es: ", area_triangulo(b,h) ) elif opcion == 12: print("Adios") else: print ("No es opcion Valida") main()
class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items) - 1] def size(self): return len(self.items) p = ['id','+','id','*','id',' '] #p = ['id','*','id','-','id','*','id',' '] #p = ['id','+','id','*','id','*','id','-','id','+','id',' '] #p = ['id','/','id','-','id','+','id','*','id','-','id','+','id',' '] #p = ['id','-','(','id','+','id',')',' '] #p = ['id','*','(','id','*','id','+','id',')','*','id',' '] a = [] b =[] c = [] d = [] gata = False plus = False minus = False ori = False imparte = False identificator = True parDesch = False parInch = False sir = ['E'] v = 0 def E(): print 'am intrat in E()' global sir, a, b, c, d, v global plus global minus global ori global imparte global identificator global parDesch global parInch for i in range(len(sir)): if sir[i] == 'E': sir.pop(i) sir.insert(i, 'E1') sir.insert(i, 'T') print sir T() Eprim() def T(): global sir,a,b,c,d,v global plus global minus global ori global imparte global identificator global parDesch global parInch for i in range(len(sir)): if sir[i] == 'T': if i != 0: sir.insert(i,'T1') sir.insert(i,'F') sir.remove('T') print sir F() Tprim() else: sir.remove('T') sir.insert(0,'T1') sir.insert(0,'F') print sir F() Tprim() def F(): global sir,a,b,c,d,v global identificator global parDesch global parInch if identificator == False and parDesch == False: VeziUrm() for i in range(len(sir)): if sir[i] == 'F': if identificator == True: #sir.remove('F') sir.insert(i,'id') sir.remove('F') print sir identificator = False #VeziUrm(p) if parDesch == True: sir.insert(i,')') sir.insert(i,'E') sir.insert(i,'(') parDesch = False sir.remove('F') E() def Eprim(): global sir,a,b,c,d,v,s1,gata global ori global imparte global plus global minus global identificator global parDesch global parInch if gata == False: if identificator == False and parDesch == False: VeziUrm() if plus == True and parInch == False: for i in range(len(sir)): if sir[i] == 'E1': sir.insert(i,'T') sir.insert(i,'+') plus = False print sir T() Eprim() elif minus == True and parInch == False: for i in range(len(sir)): if sir[i] == 'E1': sir.insert(i,'T') sir.insert(i,'-') minus = False print sir T() Eprim() #if identificator == True and parInch == False: #if sir.__contains__('E1'): #sir.remove('E1') #print sir elif parInch == True: for i in range(len(sir)): if sir[i] == 'E1': sir.pop(i) parInch = False break #print identificator, parInch, parDesch, plus, minus, ori, imparte elif identificator == False and parInch == False and parDesch == False and plus == False and minus == False and ori == False and imparte == False: if sir.__contains__('E1'): sir.remove('E1') print sir def VeziUrm(): global s1 if s1.size() != 0: CeUrmeaza(s1.pop()) def Tprim(): global sir,s1 global gata global plus global minus global ori global imparte global identificator global parDesch global parInch if gata == False: if identificator == False and parDesch == False: VeziUrm() if ori == True: for i in range(len(sir)): if sir[i] == 'T1': sir.insert(i,'F') sir.insert(i,'*') ori = False print sir F() Tprim() elif imparte == True: for i in range(len(sir)): if sir[i] == 'T1': sir.insert(i,'F') sir.insert(i,'/') imparte = False print sir F() Tprim() else: sir.remove('T1') print sir def CeUrmeaza(x): global plus global minus global ori global imparte global identificator global parDesch global parInch global gata if x == '+': plus = True #print '+' elif x == '-': minus = True #print '-' elif x == '*': ori = True #print '*' elif x == '/': imparte = True #print '/' elif x == 'id': identificator = True #print 'id' elif x == '(': parDesch = True #print '(' elif x == ')': parInch = True elif x == ' ': gata = True #print 'spatiu' def Genereaza(token): global sir,v global identificator, plus, minus, ori, imparte global parDesch global parInch VeziUrm() if token == '+': for i in range(len(sir)): if sir[i] == 'E1': sir.insert(i,'T') sir.insert(i,'+') plus = False print sir T() Eprim() if token == '-': for i in range(len(sir)): if sir[i] == 'E1': sir.insert(i, 'T') sir.insert(i, '-') minus = False print sir T() Eprim() if token == '*': for i in range(len(sir)): if sir[i] == 'T1': sir.insert(i,'F') sir.insert(i,'*') ori = True print sir F() Tprim() if token == '/': for i in range(len(sir)): if sir[i] == 'T1': sir.insert(i, 'F') sir.insert(i, '/') imparte = True print sir F() Tprim() if token == 'id': for i in range(len(sir)): if sir[i] == 'E': if i != 0: sir.insert(i,'E1') sir.insert(i,'T') c.remove('E') identificator = True print sir T() Eprim() else: sir.insert(0,'E1') sir.insert(0,'T') print sir sir.remove('E') T() Eprim() def Parcurge(p1): global sir,p,s1 p1 = p[:] print 'sirul este', p element = s1.pop() print len(p) print sir Genereaza(element) s1 = Stack() for i in reversed(range(len(p))): s1.push(p[i]) print Parcurge(p)
""" 用for循環實現1~100之間的偶數求和 Version: 0.1 Author: 骆昊 Date: 2018-03-01 """ sum = 0 # 可以產生一個2到100的偶數序列,其中的2是步長,即數值序列的增量。 for x in range(2, 101, 2): sum += x print(sum)
def mensagem(): print('CALCULADORA') print('+ ADIÇÃO ') print('- SUBTRAÇÃO') print('* MULTIPLICAÇÃO') print('/ DIVISÃO') print('Pressione outra tecla para sair') def operacao(op, x, y): if (op == '+'): return (x + y) if (op == '-'): return (x - y) if (op == '*'): return (x * y) if (op == '/'): return (x / y) mensagem() while True: op = input('Qual operação deseja fazer ?') if op == '+' or op == '-' or op == '*' or op == '/': x = int(input('Digite o primeiro valor:')) y = int(input('Digite o segundo valor:')) resultado = operacao(op, x, y) print('o resultdao é {}'.format(resultado)) print('----------------------------------') mensagem() else: break
#get numbers a = float(input()) b = float(input()) #store them in a tuple tup = (a ,b) print(tup) #swap the numbers (a, b) = (b, a) print(tup)
# annual_salary = float(input("Enter your annual salary:\n>>>")) # portion_saved = float(input("Enter the percent of your salary to save, as a decimal: ​)\n>>>")) # total_cost = float(input("Enter the cost of your dream home:​\n>>>")) # portion_down_payment = float(total_cost)*0.25 # current_savings = 0.0 # annual_rate = 1.04 # months = 0 # while current_savings < portion_down_payment: # if months == 0: # print("only starting") # months +=1 # current_savings += annual_salary/12*portion_saved # print(current_savings, months) # else: # print("getting close") # months +=1 # current_savings = current_savings*annual_rate/12+annual_salary/12*portion_saved # print(current_savings, months) # print("Number of months:", months) def problem(): annual_salary = float(input("Enter your annual salary:\n>>>")) monthly_salary = annual_salary/12.0 portion_saved = float(input("Enter the percent of your salary to save, as a decimal: ​\n>>>")) total_cost = float(input("Enter the cost of your dream home:​\n>>>")) portion_down_payment = float(total_cost)*0.25 current_savings = 0.0 annual_rate = 0.04 months = 0 while current_savings < portion_down_payment: if months == 0: print("only starting") months +=1 current_savings += monthly_salary*portion_saved print(current_savings, months) else: print("getting close") months +=1 current_savings += current_savings*annual_rate/12+monthly_salary*portion_saved print(current_savings, months) print("Number of months:", months) problem() while input("Do you want to calculate other values?(Y\\N)\n>>>") == "Y": problem() print("Goodbye!")
Given: Two positive integers a and b , each less than 1000. Return: The integer corresponding to the square of the hypotenuse of the right triangle whose legs have lengths a and b. def hypo(a, b): return math.sqrt(a**2 + b**2)
#!/usr/bin/python # This will be a tutorial in lists. Adding, remove, slicing, and dicing. This will also be a # straight script. No functions here. Notice it also has the "she-bang" open which means it # can be run independently. so, instead of "python allaboutlist.py", it can be ran (on Linux) # ./allaboutlists.py (make sure it has the correct permissions!) # let's create an empty list a_list = [] # now, loop through and populate is with numbers for i in range(0, 10): print "adding " + str(i) a_list = a_list + [i] print "new list: " + str(a_list) # let's do the loop again, but instead of a 0-based numbering system let's make it a 1-based # numbering system for i in range(0, 10): a_list[i] = a_list[i] + 1 print "corrected list: " + str(a_list) # now, we'll show off some slicing print "beginning of the list to the fourth element: " + str(a_list[:5]) print "from the third element in the list to the end: " + str(a_list[3:]) print "from the second element of the list to the seventh: " + str(a_list[2:8]) # let's remove some elements from the end, and then show and count what's left for i in range(0,4): x = a_list.pop() print "removing " + str(x) print "new list: " + str(a_list) + " with " + str(len(a_list)) + " elements" # let's append some things NOT integars a_list.extend([True]) a_list.extend(["red"]) a_list.extend(['y']) # now the current list print str(a_list) # let's delete the list and try to print it again. (this will fail) del a_list print str(a_list)
#reverse using list method list=[1,2,3,4] list.reverse() print(list) #print uppercase letter of a string string="Hello WorlD" for i in string: if(i.isupper()): print(i) #split on user input from comma and made a list of it a=input("enter a string") #eg--1,2,33,566 l=[] l1=[] for i in a: l=a.split(",") for i in l: l1.append(int(i)) print(l1) #pallindrome or not s1=input("enter string") if(s1==''.join(reversed(s1))): print("pallindrome") else: print("not pallindrome") #shallow copy nd deep copy #deep copy example import copy l1=[1,[3,7],[4,5],8] l2=copy.deepcopy(l1) l1[2][1]=99 print(l1) print(l2) #if b is a DEEP COPY of a,then b=[a copy]; #b nd a point to different location; #shallow copy example import copy l1=[1,[3,7],[4,5],8] l2=copy.copy(l1) l1[2][1]=99 l1[0]=88 print(l1) print(l2) # if b is a SHALLOW COPY of a,for premitive data b=[a assign];and for objects b=[A retain]; #b nd a both point to same memory location
#make a list l1=[] n=int(input("no of inputs")) for i in range (0,n): a=input() l1.append(a) print(l1) #add two list l2=['google','apple','facebook','microsoft','tesla'] l3=[] b=len(l2) c=n+b; for i in range(0,n): l3.append(l1[i]) for j in range(0,5): l3.append(l2[j]) print(l3) #count no of times an object occur l4=['1','2','1','2','3','1'] print(l4.count('1')) #create list nd sort l5=[] n=int(input("no of inputs")) for i in range (0,n): a=int(input()) l5.append(a) l5.sort() print(l5) #merge two array nd sort a=[1,4,8] b=[3,5] c=a+b; c.sort(); print(c); #even odd no in a list l6=[1,2,1,3,1,4,1] c=0 count=0 for i in l6: if not i % 2: count=count+1 else: c=c+1 print("even no.",count) print("odd no.",c) #reverse a tupple a=(1,2,3) b=a[::-1] print(b) #find min nd max of tupple a=(1,2,3,4,5) print(min(a)) print(max(a)) #string to be uppercase s="hello" print(s.upper()) #tell string to be numeric or not s=input("enter string") print(s.isdigit()) #replace world with name s="hello world" print(s.replace("world","tripta jindal"))
def getTable(): table = [] for i in range(3): line = input().split() table.append(line) return table x = False o = False verify = False countX = 0 countO = 0 quant = int(input()) for i in range(quant): tab = getTable() for h in range (3): for t in range (3): if(tab[h][t])== 'O': countO= countO+1 elif(tab[h][t]) == 'X': countX = countX + 1 for j in range(3): if(tab[j][0] == tab[j][1] == tab [j][2]): if(tab[j][0] != '_'): if(tab[j][0] == 'X'): if(x): verify = True else: x = True else: if(o): verify = True else: o = True for k in range(3): if(tab[0][k] == tab[1][k] == tab [2][k]): if(tab[0][k] != '_'): if(tab[0][k] == 'X'): if(x): verify = True else: x = True else: if(o): verify = True else: o = True if((tab[0][0] == tab [1][1] == tab[2][2]) or (tab[0][2] == tab[1][1] == tab[2][0])): if(tab[1][1] != '_'): if(tab[1][1] == 'X'): if(x): verify = True else: x = True else: if(o): verify = True else: o = True if(verify): print("ILEGAL") elif(countX >= countO): if ((countX == countO+ 1) or (countX==countO)): if(x): if(o): print("ILEGAL") else: if(countX <= countO): print("ILEGAL") else: print("X_VENCEU") else: if(o): if(countX > countO): print("ILEGAL") else: print("O_VENCEU") else: print("EM_ANDAMENTO") else: print("ILEGAL") else: print("ILEGAL") o = False x = False verify = False countX = 0 countO = 0
from bst import BST from lista import LinkedList from random import randint import time ONE_SECOND = 1000 REPEATS = 10 instances = [1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000] def fill_increasing(size): array = [] for i in range(size): array.append(i) return array def fill_random(size): array = [] max_element_size = size * 100 for i in range(size): array.append(randint(0, max_element_size)) return array def time_clock(array, structure): start_time_append = time.time() for run in range(REPEATS): for i in array: structure.append(i) end_time_append = time.time() time_append = round((end_time_append - start_time_append) * ONE_SECOND / REPEATS, 3) start_time_find = time.time() for run in range(REPEATS): for i in array: structure.find(i) end_time_find = time.time() time_find = round((end_time_find - start_time_find) * ONE_SECOND / REPEATS, 3) return { 'append': time_append, 'find': time_find } def linked_increasing(size): linked_list = LinkedList() array = fill_increasing(size) times = time_clock(array, linked_list) print(f"Linked, append, {size} size, increasing, {round(times['append'] / size, 5)}") print(f"Linked, find, {size} size, increasing, {round(times['find'] / size, 5)}") def linked_random(size): linked_list = LinkedList() array = fill_random(size) times = time_clock(array, linked_list) print(f"Linked, append, {size} size, random, {round(times['append'] / size, 5)}") print(f"Linked, find, {size} size, random, {round(times['find'] / size, 5)}") def bst_increasing(size): bst = BST() array = fill_increasing(size) times = time_clock(array, bst) print(f"BST, append, {size} size, increasing, {round(times['append'] / size, 5)}") print(f"BST, find, {size} size, increasing, {round(times['find'] / size, 5)}") def bst_random(size): bst = BST() array = fill_random(size) times = time_clock(array, bst) print(f"BST, append, {size} size, random, {round(times['append'] / size, 5)}") print(f"BST, find, {size} size, random, {round(times['find'] / size, 5)}") def main(): for instance in instances: try: linked_increasing(instance) linked_random(instance) bst_increasing(instance) bst_random(instance) except RuntimeError as re: print(f'Error in {re}') main()
from typing import List class Result(): """ This is a version of the monad Result Habitually, we should not be able to access the ok value, or the error value. It's one of the core concept of a monad. A monad is like a box. You always need to pass the box to other function, and when you want to open the box to see what's inside, you absolutely need to tell what to do if it's an error and what to do if it's a success(ok) For now, we can access the ok and error value for ease of use, but we should use the match function that make mandatory to tell the result what to do in both cases. By being able to use the ok and error value, it makes the Result class to be used with less restreint. """ __create_key = object() def __init__(self, create_key, ok=None, error=None): assert(create_key == Result.__create_key), \ "Result objects must be created using Result.create" self.ok = ok self.error = error @classmethod def ok(cls, ok): return Result(cls.__create_key, ok=ok) @classmethod def error(cls, error): return Result(cls.__create_key, error=error) def is_ok(self): return self.ok is not None def is_error(self): return self.error is not None def match(self, ok_function, error_function): """ The method match demands you to tell what to do in both cases, without giving you especially both values. Concept of the monad(box). """ if self.is_ok(): ok_function(self.ok) else: error_function(self.error) class ResultUtils(): @staticmethod def map_ok(result:Result, map_function): """ Maps a result by passing a function of type a -> b Parameters: map_function: function of type a -> b Returns a result with ok value equals to the mapping function over the ok value Returns the result if the result is error Example: Result(ok=a:str) -> map_ok(a:str -> b:int) -> Result(ok=b:int) Railway If is_ok OK = a:str ------- a:str -> b:int -------- Ok = b:int Err = None ------------------------------- Err = None If is_error OK = None ---------- a:str -> b:int --------- Ok = None Err = msg:str ----------------------------------- Err = msg:str """ if result.is_ok(): return Result.ok (map_function(result.ok)) else: # Error result propagation. If we are in error state, we stay in error state return result @staticmethod def map_error(result:Result, map_function): """ Maps a result by passing a function of type a -> b Parameters: map_function: function of type a -> b Returns a result with error value equals to the mapping function over the error value Returns the result if the result is ok Result(err=ex:Exception) -> map_error(ex:Exception -> msg:str) -> Result(err=msg:str) Railway If is_ok OK = None ========================================= Ok = b:int Err = ex:Exception ======== ex:Exception -> msg:str ======== Err = msg:str If is_error OK = a:str ========================================= Ok = a:str Err = None ========= ex:Exception -> msg:str ======= Err = None """ if result.is_error(): return Result.error (map_function(result.error)) else: # Ok result propagation. If we are in Ok state, we stay in Ok state return result @staticmethod def bi_map(result:Result, map_ok_function, map_error_function): """ Syntax sugar It's simply a way to handle map_ok, and map_error in one function call """ if result.is_ok(): return ResultUtils.map_ok(result, map_ok_function) else: return ResultUtils.map_error(result, map_error_function) @staticmethod def bind_ok(result:Result, function): """ Binds a result with a function of type a -> Result(ok, error) Parameters: function: function of type a -> Result(ok, error) Sometimes we want to plug a function of type a -> Result(ok, error) in the railway system. Per example, using map would return: MAP_OK OK = success:Response ======= map_ok(success:Response -> result:Result(ok=a:str, err=None)) ======= Ok = result:Result(ok=a:str, err=None) Err = None ========================================================================================= Err = None The returned type is Result(ok=result:Result(ok=a:str, err=None), err=None), so a result in a result. It is not what we want, we want a single result like this: BIND_OK OK = success:Response ========== bind_ok(success:Response -> result:Result(ok=a:str, ============= Ok = a:str Err = None **This Err is not returned anymore** err=None)) ============= Err = None """ if result.is_ok(): return function(result.ok) else: # Error result propagation. If we are in error state, we stay in error state return result @staticmethod def bind_error(result:Result, function): """ Take a look at bind_ok. It's same but when we are in error state. This fonction allow a result in error state to return in a success state. """ if result.is_error(): return function(result.error) else: return result @staticmethod def tee_error(result:Result, side_effect_function): """ tee_error is used for side effect function, functions that returns None. The most common side effect function is the print function. Example: TEE_ERROR OK=None ================================================ Ok=None Err=ex:Exception =========================================== Err=ex:Exception tee_error(print(ex.Message)) -> None It will print the error without altering the result returned; to be use by another process. """ if result.is_error(): side_effect_function(result.error) return result @staticmethod def tee_ok(result:Result, side_effect_function): """ tee_ok is used for side effect function, functions that returns None. The most common side effect function is the print function. Example: TEE_OK tee_ok(print(f'The dataset {response.dataset_id} has been created with success.)) -> None OK= response:Response ================================================================================================== Ok=response:Response Err=None =============================================================================================================== Err=None We didn't apply changes to the result, we just called a side effect and returned the result; to be use by another process needing the response. """ if result.is_ok(): side_effect_function(result.ok) return result @staticmethod def bi_tee(result:Result, side_effect_ok, side_effect_error): """ Syntax sugar To declare to side effect for both result states in one function call. """ if result.is_ok(): side_effect_ok(result.ok) else: side_effect_error(result) return result @staticmethod def extract(results: List[Result]): values = [] for result in results: if result.is_ok(): values.append(result.ok) return values
#! coding: utf-8 import time # import time module import datetime # import datetime module time.clock() # Set clock start print(time.ctime()) # print current time in format 'Tue May 24 14:09:17 2016’ print(time.localtime().tm_year) # Current time year print(time.localtime().tm_yday) # Current year day print(time.strftime("%d %m. %Y %H:M",time.gmtime())) print(datetime.datetime.strptime("19 Sep. 2012 10:15", "%d %b. %Y %H:%M")) time_1 = datetime.datetime.now() + datetime.timedelta(days = -1) # Create datetime tuple with current day minus one day now = datetime.datetime.now() print('Time delta', (now - time_1).days) # Check the difference with time delta print("Script execution time: %f4.2" % time.clock())
#!/usr/bin/python # Electricty CSV Parser and Calculator import argparse import csv import datetime def rates_calc(_file): """ Takes a csv of the rates on a per day basis and their cost per kWh Returns a 2 dimential list of kWh X time period X per day """ with open(_file, 'rb') as ratesfile: reader = csv.reader(ratesfile) return list(reader) def data_calc(_file, rates="", firstX="", restX="", first_var=""): """ Takes a csv file with "StartDate,EndDate,Usage" where each row is a 30 min interval Returns an array of cost per day """ total_cost = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0} today = {} current = 0 with open(_file, 'rb') as csvfile: stringformat = "%d/%m/%Y %I:%M:%S %p" reader = csv.DictReader(csvfile) for row in reader: billable_time = datetime.datetime.strptime(row['StartDate'], stringformat) # Day of Year date = billable_time.strftime('%j') # day is the day of the week as an integer, where Monday is 0 and Sunday is 6. day = int(billable_time.weekday()) # time is the Hour hour = int(billable_time.hour) # end_date = datetime.datetime.strptime(row['EndDate'], stringformat) kwh_usage = float(row['ProfileReadValue']) # print(day, time, kwh_usage) if rates: total_cost[day] += (float((rates[hour][day])) * kwh_usage) if firstX: if current != date: current = date today[date] = kwh_usage today[date] += kwh_usage if rates: return total_cost if firstX: # We have caluclated all usage per day for days, value in today.iteritems(): if float(value) > float(first_var): rest = float(value) - float(first_var) now_value = float(firstX) * float(first_var) + float(rest) * float(restX) else: now_value = float(firstX) * float(first_var) today[days] = now_value return today if __name__ == "__main__": parser = argparse.ArgumentParser(description="Electriciy CSV parser") parser.add_argument("--data-csv", "-c", action="store", required=True, help="CSV Data File") parser.add_argument("--rates-csv", "-r", action="store", help="Rates CSV Files") parser.add_argument("--first-kwh-rate", "-f", action="store", help="Starting rate for X kWh") parser.add_argument("--next-kwh-rate", "-n", action="store", help="Rate for after kWh") parser.add_argument("--first-kwh", "-k", action="store", help="The X kWh variable") parser.add_argument("--supply-charge", "-s", action="store", required=True, help="Daily Supply Cost (Cents)") parser.add_argument("--debug", action="store_true", help="Turn on Debugging") args = parser.parse_args() # rates_map contains [<time>][date] # for 0:00 -> 0:59 on Tuesday it would be [0][1] # for 13:00 -> 13:59 on Sunday it would be [13][6] if args.rates_csv: quarter = 0 rates_map = rates_calc(args.rates_csv) if args.debug: print(rates_map) for day, value in data_calc(args.data_csv, rates_map).items(): quarter += (value/100) print("Day: {} - Cost: {}".format(day, value/100)) charge = float(90*float(args.supply_charge)/100) print("Quarter Cost: {} + {} = {}".format(quarter, charge, (quarter + charge))) elif args.first_kwh: day_cost = data_calc( args.data_csv, firstX=args.first_kwh_rate, restX=args.next_kwh_rate, first_var=args.first_kwh) yearly_cost = 0 for day, value in day_cost.iteritems(): yearly_cost += value/100 yearly_cost += float(args.supply_charge)/100 print("Yearly Cost: {}".format(yearly_cost))
from time import sleep from threading import * class Hello(Thread): # To use Thread we need to use "run" method. Other name will not work here def run(self): for i in range(5): print("Hello") sleep(1) class Hi(Thread): def run(self): for i in range(5): print("Hi") sleep(1) T1 = Hello() T2 = Hi() # Start is internal method of Thread T1.start() # To avoid the collision sleep(0.2) T2.start() # This will print after completion of both Thread. In here we are saying wait for other thread by using join T1.join() T2.join() print("Bye")
class Competition: __raise_amount = 1.10 def __init__(self, name, prize): self.__name = name self.__prize = prize def get_name(self): return self.__name def get_prize(self): return self.__prize def raise_prize(self): self.__prize = self.__prize * self.__raise_amount class Cycling(Competition): def __init__(self, name, prize, country): Competition.__init__(self, name, prize) # Whenever we use parent class name then it is mandatory to pass self parameter self.__country = country def get_country(self): return self.__country class Cycling1(Competition): def __init__(self, name, prize, country): super().__init__(name, prize) # If we are using super() then we don't need to pass self parameter self.__country = country def get_country(self): return self.__country
import unittest from coin import coin_check class CoinTest(unittest.TestCase): def test_for_quartar(self): coin = coin_check({'weight': 5.670, 'diameter': .955, 'thickness': 1.75}, 'QUARTER') assert coin == True def test_for_penny(self): coin = coin_check({'weight': 2.5, 'diameter': .75, 'thickness': 1.52}, 'PENNY') assert coin == False def test_for_nickel(self): coin = coin_check({'weight': 5.0, 'diameter': .835, 'thickness': 1.95}, 'NICKEL') assert coin == True def test_for_dime(self): coin = coin_check( {'weight': 2.268, 'diameter': .705, 'thickness': 1.35}, 'DIME') assert coin == True if __name__ == '__main__': unittest.main()
def permute(arr, l, r): # n! if l == r: print(arr) for i in range(l,r+1): arr[l], arr[i] = arr[i], arr[l] permute(arr, l+1, r) arr[l], arr[i] = arr[i], arr[l] def combination(arr): pass arr = [1, 2, 3] permute(arr,0,2) combination(arr)
# https://leetcode.com/problems/same-tree/ class node: def __init__(self, data): self.data = data self.left = self.right = None def issame(root1, root2): if root1 and root2: if root1.data != root2.data: return False return issame(root1.left, root2.left) and issame(root1.right, root2.right) else: return root1 == root2 root1 = node(1) root1.left = node(2) root1.right = node(3) root2 = node(1) root2.left = node(2) root2.right = node(3) print(issame(root1, root2))
# example of training a final classification model from keras.models import Sequential from keras.layers import Dense import numpy as np from sklearn.datasets.samples_generator import make_blobs from sklearn.preprocessing import MinMaxScaler # generate 2d classification dataset X, y = make_blobs(n_samples=100, centers=2, n_features=2, random_state=1) scalar = MinMaxScaler() scalar.fit(X) X = scalar.transform(X) # define and fit the final model ''''' model = Sequential() model.add(Dense(4, input_dim=2, activation='relu')) model.add(Dense(4, activation='relu')) model.add(Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam') model.fit(X, y, epochs=200, verbose=0) # new instances where we do not know the answer Xnew, _ = make_blobs(n_samples=3, centers=2, n_features=2, random_state=1) Xnew = scalar.transform(Xnew) # make a prediction ynew = model.predict_classes(Xnew) # show the inputs and predicted outputs for i in range(len(Xnew)): print('X = {}, Predicted = {}'.format(Xnew[i], ynew[i])) ''''' print(X) print(y)
import collections, itertools, random class ChessGame: """ Controller class to be used with ChessGUI.py. All logic for chess game should be implemented here. TODO: implement castling and en passant in _get_piece_moves. Pawns also need to be able to move two spots at the beginning of the game and be traded for highest value piece if they make it to other side """ BLACK = 'black' WHITE = 'white' Piece = collections.namedtuple('Piece', ['name', 'color']) def __init__(self): """ WHTIE always goes first """ self.__turn_info = { 'turn': ChessGame.WHITE } self.init_board() def init_board(self): """ Maintain game board as a dict and keep location of player pieces in sets No top level classes should have access to self.__board """ self.__board = dict() order = ['rook', 'knight', 'bishop', 'queen', 'king', 'bishop', 'knight', 'rook'] for j, name in enumerate(order): self.__board[(0, j)] = ChessGame.Piece( name, ChessGame.WHITE) self.__board[(7, j)] = ChessGame.Piece( name, ChessGame.BLACK) self.__board[(1, j)] = ChessGame.Piece('pawn', ChessGame.WHITE) self.__board[(6, j)] = ChessGame.Piece('pawn', ChessGame.BLACK) self.__players = { ChessGame.WHITE: set(), ChessGame.BLACK: set() } for color in (ChessGame.BLACK, ChessGame.WHITE): self.__players[color] = {(x, y) for (x, y), piece in self.__board.iteritems() if piece.color == color } return def get_turn(self): """ Get the current turn color """ return self.__turn_info['turn'] def get_player_piece_locs(self, mycolor): """ Get piece locations for @mycolor - return None for invalid @mycolor """ if mycolor not in (ChessGame.BLACK, ChessGame.WHITE): return None return self.__players[mycolor] def get_opponent_color(self, mycolor): """ Get the opponent of @mycolor """ if mycolor == ChessGame.BLACK: return ChessGame.WHITE elif mycolor == ChessGame.WHITE: return ChessGame.BLACK else: raise NotImplementedError() def get_piece_dict(self, mycolor): """ Get piece locations and pieces for @mycolor """ pieces = { (x, y) : self.get_piece(x, y) for (x, y) in self.__players[mycolor] } if None in pieces.values(): raise ValueError() return pieces def in_bounds(self, x, y): """ Board locations must be strictly in [0, 8) """ return x >= 0 and x < 8 and y >= 0 and y < 8 def piece_at(self, x, y): """ Determine if x,y is a piece """ return ((x, y) in self.__board and isinstance((self.__board[(x, y)]), self.Piece)) def get_piece(self, x, y): """ Get piece at (x,y) - Use this function rather than accessing self.__board directly """ if self.in_bounds(x, y) and self.piece_at(x, y): return self.__board[(x, y)] return None def is_enemy(self, x, y, mycolor): """ Determine if piece at (x,y) is an enemy """ piece = self.get_piece(x, y) if piece: return piece.color != mycolor return False def has_winner(self): """ Determine if BLACK or WHITE has a win. - return None if no win """ if self.color_check_mate(ChessGame.BLACK): return ChessGame.WHITE elif self.color_check_mate(ChessGame.WHITE): return ChessGame.BLACK else: return None def color_in_check(self, mycolor): """ Determine whether mycolor is in check """ opponent = self.__players[self.get_opponent_color(mycolor)] x, y = None, None for (u, v) in self.__players[mycolor]: piece = self.get_piece(u, v) if not piece: raise ValueError() if self.get_piece(u, v).name == 'king': x, y = u, v break for (u, v) in opponent: if (x, y) in self._get_piece_moves(u, v): return True return False def color_check_mate(self, mycolor): """ Determine whether mycolor is in check-mate """ if not self.color_in_check(mycolor): return False incheck = True for (x, y) in self.__players[mycolor]: moves = self._get_piece_moves(x, y) for to in moves: res, captured = self._make_move((x, y), to) if not self.color_in_check(mycolor): incheck = False self._unmake_move(to, (x, y), captured) if not incheck: return False return incheck def make_move(self, at, to): """ Wrapper for internal _make_move that advances turn for ChessGame instances """ made, captured = self._make_move(at, to) if made: self._advance_turn() return made, captured def _advance_turn(self): """ Update move color; for internal use only """ self.__turn_info['turn'] = ChessGame.BLACK if self.__turn_info['turn'] == ChessGame.WHITE else ChessGame.WHITE def _make_move(self, at, to): """ Make a move for a piece at @at to @to - first verify that the move is valid - an invalid move is one that isn't on the board or one where there's no piece to move - next, see if we need to capture (remove from opponents pieces) - finally, replace whatever was at u,v with what as at board; report success return NONE (no move to be made), TRUE (move succeeded), FALSE (move puts opponent in check) along with CAPTURED to simplify code used by AI/GUI """ x, y = at u, v = to piece = self.get_piece(x, y) if not piece: return None, None if piece.color != self.get_turn(): return None, None if at == to or to not in self._get_piece_moves(x, y): return None, None color = piece.color captured = None if self.is_enemy(u, v, color): captured = self.get_piece(u, v) del self.__board[(u, v)] self.__players[self.get_opponent_color(color)].remove((u, v)) self.__board[(u, v)] = piece del self.__board[(x, y)] self.__players[piece.color].remove((x, y)) self.__players[piece.color].add((u, v)) ret = True if self.color_in_check(color): self._unmake_move(to, at, captured) ret = False self._check_integrity() return ret, captured def _unmake_move(self, at, to, captured=None): """ Unmake a move for a piece moved to @at back to @to - if we're out of bounds, or there's no piece at u,v then we can't do anything - captured is the result of a capture, or None if nothing was captured - exchange whatever is at u,v with whatever is at x,y """ u, v = at x, y = to if not self.in_bounds(x, y) or not self.in_bounds(u, v): return False piece = self.get_piece(u, v) if not piece: raise ValueError() if isinstance(captured, ChessGame.Piece): opponent = self.get_opponent_color(piece.color) self.__board[(u, v)] = captured self.__players[opponent].add((u, v)) else: del self.__board[(u, v)] self.__board[(x, y)] = piece self.__players[piece.color].add((x, y)) self.__players[piece.color].remove((u, v)) self._check_integrity() return True def _check_integrity(self): """ Check the integrity of the board - make sure that each piece in a players piece set is in the board - the union of the piece sets must cover the board exactly """ count = 0 for (x, y) in self.__players[ChessGame.BLACK].union( self.__players[ChessGame.WHITE]): assert (x, y) in self.__board count += 1 assert count == len(self.__board) def get_moves(self, x, y): """ Top-level function that should be used ONLY by GUI/AI (do not use with ChessGame.py) - gets moves that won't the moving player in check - should not be used in ChessGame.py..._make_move makes calls to _get_piece_moves and we could induce infinite recursion by replacing that call with a call to get_moves TODO: think about making this a static function, accessible with ChessGame.get_piece_moves(boards, x, y) """ if not self.piece_at(x, y): return set() moves = self._get_piece_moves(x, y) legal = set(moves) at = x, y for to in moves: res, captured = self._make_move(at, to) if not res: legal.remove(to) else: self._unmake_move(to, at, captured) self._check_integrity() return legal def _get_moves_indirection(self, x, y, direc, moves=[]): """ Get sequential moves in a given direction recursively - handle attack moves with the move function """ compass = { 'up' : (x-1, y), 'down' : (x+1, y), 'left' : (x, y-1), 'right' : (x, y+1), 'd1' : (x-1, y+1), 'd2' : (x+1, y-1), 'd3' : (x+1, y+1), 'd4' : (x-1, y-1) } u, v = compass[direc] if not self.in_bounds(u, v): return moves if self.piece_at(u, v): return [(u, v)] + moves return [(u, v)] + self._get_moves_indirection(u, v, direc, moves) def _get_piece_moves(self, x, y): """ Get moves for a piece at location @x, @y. Should NOT be called by GUI/AI - @x denotes the row on the board. Increases in x imply downward movement - @y denotes the column on the board """ piece = self.get_piece(x, y) moves = [] if not piece: return moves if piece.name == 'rook' or piece.name == 'queen': direcs = ['up', 'down', 'left', 'right'] moves = [self._get_moves_indirection(x, y, direc) for direc in direcs] elif piece.name == 'bishop' or piece.name == 'queen': direcs = ['d1', 'd2', 'd3', 'd4'] for direc in direcs: moves += self._get_moves_indirection(x, y, direc) elif piece.name == 'king': moves = [(x-1, y-1), (x-1, y), (x-1, y+1), (x, y-1), (x, y+1), (x+1, y-1), (x+1, y), (x+1, y+1)] elif piece.name == 'knight': moves = [(x-1, y-2), (x-2, y-1), (x-2, y+1), (x-1, y+2), (x+1, y+2), (x+2, y+1), (x+1, y-2), (x+2, y-1)] elif piece.name == 'pawn': if piece.color == ChessGame.BLACK: moves = [(x-1, y), (x-1, y-1), (x-1, y+1)] else: moves = [(x+1, y), (x+1, y-1), (x+1, y+1)] tmp = list(moves) for u, v in tmp: if v != y and not self.is_enemy(u, v, piece.color): moves.remove((u, v)) if v == y and self.is_enemy(u, v, piece.color): moves.remove((u, v)) mycolor = piece.color valid = set() for (u, v) in moves: if not self.in_bounds(u, v): continue if not self.get_piece(u, v): # board is blank valid.add((u, v)) if self.is_enemy(u, v, mycolor): valid.add((u, v)) return valid
print 'This is a test file for Fizzbuzz:' for i in range(1,20): # Test with range from 1 to 19. if not i % 15: # When a % b is none-zero, true. print 'FizzBuzz', elif not i % 5: # The if elif structure must be ordered from least occured scenerio. print 'Buzz', elif not i % 3: print 'Fizz', else: print i, # print anything else. print '\n\nOO code:' class Swift(object): def fizzbuzz(self, n): return ['Fizz' * (not i % 3) + 'Buzz' * (not i % 5) or str(i) for i in range(1, n+1)] res = Swift() print res.fizzbuzz(20) # Test with number 20
from node import Node class Queue: def __init__(self, value): self.first = Node(value) self.last = self.first self.length = 1 def enqueue(self, value): new_link = Node(value) if self.length == 0: self.first = new_link self.last = new_link elif self.length == 1: self.last = new_link self.first.link = self.last else: self.last.link = new_link self.last = self.last.link self.length += 1 print(f"{value} added to queue! Queue is of length {self.length}") def dequeue(self): if self.length == 0: print("Queue empty! Nothing to do here.") else: value = self.first.value self.first = self.first.link self.length -= 1 print(f"{value} removed from queue! Queue is of length {self.length}") def length(self): return self.length
# Zadanie 1 - while # Napisz mini-encyklopedię Trójmiasta # Program powinien prosić użytkownika o podanie pojęcia dopóki nie wpisze on komendy "koniec" # Wszystkie hasła i komendy powinny być obsługiwane niezależnie od wielkości liter. # W odpowiedzi na znane hasła powinien wypisać odpowiednią informację (treść dowolna): # Dla "Gdańsk" lub "gdansk": # "Miasto na prawach powiatu w północnej Polsce w województwie pomorskim, położone nad Morzem Bałtyckim # u ujścia Motławy do Wisły nad Zatoką Gdańską." # Dla "Sopot": # "Najdłuższe drewniane molo w Europie i kluby." # Dla "Gdynia": # "Contrast Cafe i Teatr Muzyczny!" # Dla wszystkich innych haseł: # "Przepraszam, nie mam informacji na ten temat." czy_wyjsc = False while czy_wyjsc == False: haslo = input("Podaj haslo: ") haslo = haslo.lower() if haslo == 'gdansk': print("Miasto na prawach powiatu w północnej Polsce w województwie pomorskim, położone nad Morzem Bałtyckim u ujścia Motławy do Wisły nad Zatoką Gdańską.") elif haslo == 'sopot': print("Najdłuższe drewniane molo w Europie i kluby.") elif haslo == 'gdynia': print("Contrast Cafe i Teatr Muzyczny!") elif haslo == 'koniec': czy_wyjsc = True else: print("Przepraszam, nie mam informacji na ten temat.") # Zadanie 2 - while # Wypisz liczby należące do ciągu Fibonacciego mniejsze od 100 x = 0 y = 1 while y < 100: print(y) x = y y = x + y # Zadanie 3 - while # Do programu echo v2 dopisz wersję premium # W normalnym trybie program powinien powtarzać to co wpisze użytkownik. # Po wpisaniu tajnego hasła "tajny-kod-premium-2019" program będzie wypisywał bardziej skomplikowane echo: # całość tekstu, całośc tekstu małymi literami, połowa tekstu małymi literami, 1/4 tekstu małymi literami, "..." # Wszystko rozdzielone spacją, długości fragmentów zaokrąglone w dół # # Np.: na hasło "Echo" # "Echo echo ec e ..." # na hasło "Ala ma kota" # "Ala ma kota ala ma kota ala m al ..." # na hasło "AA" # "AA aa a <puste> ..." # Zadanie 4 - for # Dla liczb od 1 do 100 (włacznie) # Jeśli podzielna tylko przez 3 to napisz Fizz # Jeśli podzilena tylko przez 5 to napisz Buzz # Jeśli podzielna przez 3 i przez 5 to napisz FizzBuzz for liczba in range(1, 101): if liczba % 3 and liczba % 5: print('FizzBuzz') if liczba % 3: print('Fizz') elif liczba % 5: print('Buzz') # Zadanie 5 - for # Napisz licznik litery "a" w tekscie # Program powinien przyjąć od użytkownika dowolny tekst, # a następnie wypisać liczbę wystąpień znaku "a" (tylko małej) # Zadanie zrealizuj przy pomocy pętli for # # Np.: dla tekstu "Ala ma kota" # Wynik to 3 tekst = "Ala ma kota" ilosc_a = 0 for znak in tekst: if znak == 'a': ilosc_a = ilosc_a + 1 print("Wynik to: " + str(ilosc_a)) # Zadanie 6 - for # Napisz program który zobrazuje indeksowanie stringów # Program powinien przyjąć od użytkownika dowolny tekst, # a następnie wypisać co linię kolejny znak w cudzysłowie, jego indeks dodatni i indeks ujemny # # Np.: # Podaj tekst: # rafal # "r" 0 -5 # "a" 1 -4 # "f" 2 -3 # "a" 3 -2 # "l" 4 -1 fraza = input("Podaj tekst: ") dlugosc_frazy = len(fraza) index = 0 for znak in fraza: print(f'"{znak}" {index} -{dlugosc_frazy-index}' ) index = index + 1 # Zadanie 7 # Przyjmij dowolny tekst od użytkownika # Policz ile jest samogłosek, a ile spółgłosek i wypisz wynik # Zadanie 8 # Pobierz liczbę od użytkownika (upewnij się, że faktycznie jest to liczba) # Wymaluj pramidę tej wysokości z liter "M" # Np.: dla liczby 4 # # M # MMM # MMMMM # MMMMMMM pietra = input("Podaj liczbe") if pietra.isnumeric() == False: print('Nie podałeś liczby') pietra = int(pietra) for liczba in range(0, pietra): if (liczba == 0): print( (pietra-liczba) * " " + "M" ) else: print( (pietra-liczba) * " " + ((2*liczba)+1) * "M" ) # Spróbuj rozwiązać zadanie na dwa sposoby - z użyciem i bez użycia metody center() typu string # Zadanie 9 - najtrudniejsze i największe # Napisz gre "kółko i krzyżyk" # Wyświetlaj aktualny stan planszy przy pomocy znaków 'o', 'x', '-' w trzech wierszach # Np.: # # --x # -x- # oo- # # Naprzemiennie pytaj gdzie postawić 'x', a gdzie 'o' przyjmując numer pozycji od 1 do 9 # Tzn.: # # 123 # 456 # 789 # # Zakończ grę gdy jedna ze stron wygra, lub wszystkie miejsca będą zapełnione # (BONUS - zakończ również, gdy nie ma możliwości wygranej, np. w takim ułożeniu: # xxo # oox # x-- ) # # Na razie wyświetlaj wszystko po kolei, jedno pod drugim/ # # Przykładowe wyjście # # Kołko i krzyżyk! # # --- # --- # --- # # Gdzie postawić 'x': 1 # # x-- # --- # --- # # Gdzie postawić 'o': 5 # # x-- # -o- # --- # # I tak dalej
""" Euler 23 Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers. """ import timeit start_time = timeit.default_timer() import math def divisors(n): yield 1 largest = int(math.sqrt(n)) + 1 for i in range(2, largest): if n % i == 0: yield i if i < n / i: yield n / i def is_abundant(n): if sum(divisors(n)) > n: return True return False abundants = set(n for n in xrange(12,29124) if is_abundant(n)) odd_abundants = sorted(set(n for n in abundants if n%2==1)) def is_abundant_sum(n): if n%2 == 1: for a in odd_abundants: if a >= n: return False x = n-a if x in abundants: return True return False else: if n > 46: return True for a in abundants: if a >= n: return False x = n-a if x in abundants: return True return False not_abundant_sums = [n for n in xrange(1,29124) if not is_abundant_sum(n)] result = sum(not_abundant_sums) print result print "Time: " + str(timeit.default_timer() - start_time)
""" ########## CS 229 Machine Learning ########### ########## Programming Assignment 4 ########## Parts of the code (cart and pole dynamics, and the state discretization) are adapted from code available at the RL repository http://www-anw.cs.umass.edu/rlr/domains.html This file controls the pole-balancing simulation. You need to write code in places marked "CODE HERE" only. Briefly, the main simulation loop in this file calls cart_pole.m for simulating the pole dynamics, get_state.m for discretizing the otherwise continuous state space in discrete states, and show_cart.m for display. Some useful parameters are listed below. NUM_STATES: Number of states in the discretized state space You must assume that states are numbered 1 through NUM_STATES. The state numbered NUM_STATES (the last one) is a special state that marks the state when the pole has been judged to have fallen (or when the cart is out of bounds). However, you should NOT treat this state any differently in your code. Any distinctions you need to make between states should come automatically from your learning algorithm. After each simulation cycle, you are supposed to update the transition counts and rewards observed. However, you should not change either your value function or the transition probability matrix at each cycle. Whenever the pole falls, a section of your code below will be executed. At this point, you must use the transition counts and reward observations that you have gathered to generate a new model for the MDP (i.e., transition probabilities and state rewards). After that, you must use value iteration to get the optimal value function for this MDP model. TOLERANCE: Controls the convergence criteria for each value iteration run. In the value iteration, you can assume convergence when the maximum absolute change in the value function at any state in an iteration becomes lower than TOLERANCE. You need to write code that chooses the best action according to your current value function, and the current model of the MDP. The action must be either 1 or 2 (corresponding to possible directions of pushing the cart). Finally, we assume that the simulation has converged when 'NO_LEARNING_THRESHOLD' consecutive value function computations all converged within one value function iteration. Intuitively, it seems like there will be little learning after this, so we end the simulation here, and say the overall algorithm has converged. Learning curves can be generated by calling plot_learning_curve.m (it assumes that the learning was just executed, and the array time_steps_to_failure that records the time for which the pole was balanced before each failure are in memory). num_failures is a variable that stores the number of failures (pole drops / cart out of bounds) till now. Other parameters in the code are described below: GAMMA: Discount factor to be used The following parameters control the simulation display; you dont really need to know about them: pause_time: Controls the pause between successive frames of the display. Higher values make your simulation slower. min_trial_length_to_start_display: Allows you to start the display only after the pole has been successfully balanced for at least this many trials. Setting this to zero starts the display immediately. Choosing a reasonably high value (around 100) can allow you to rush through the initial learning quickly, and start the display only after the performance is reasonable. """ import numpy as np import numpy.random as rand import show_cart as sc import plot_learning_curve as plc import get_state as gs import cart_pole as cp def simulate(): # Simulation parameters pause_time = 0.001 min_trial_length_to_start_display = 0 display_started = 0 NUM_STATES = 163 FAILED_STATE = NUM_STATES - 1 GAMMA = 0.995 TOLERANCE = 0.01 NO_LEARNING_THRESHOLD = 20 # End parameter list # Time cycle of the simulation. time = 0 # You should reach convergence well before this. max_failures = 500 # These variables perform bookkeeping (how many cycles was the pole # balanced for before it fell). Useful for plotting learning curves. time_steps_to_failure = np.zeros((max_failures, 1)) num_failures = 0 time_at_start_of_current_trial = 0 # Starting state is (0 0 0 0) # x, x_dot, theta, theta_dot represents the actual continuous state vector x = 0.0 x_dot = 0.0 theta = 0.0 theta_dot = 0.0 # state is the number given to this state - you only need to consider # this representation of the state. state = gs.get_state(x, x_dot, theta, theta_dot) if (min_trial_length_to_start_display == 0) or (display_started == 1): sc.show_cart(x, x_dot, theta, theta_dot, pause_time) ### CODE HERE: Perform all your initializations here ### # Assume no transitions or rewards have been observed # Initialize the value function array to small random values (0 to 0.10, # say) # Initialize the transition probabilities uniformly (ie, probability of # transitioning for state x to state y using action a is exactly # 1/NUM_STATES). Initialize all state rewards to zero. transition_counts = np.zeros((NUM_STATES, NUM_STATES, 2)) transition_probabilities = np.ones((NUM_STATES, NUM_STATES, 2)) / NUM_STATES reward_counts = np.zeros((NUM_STATES, 2)) reward = np.zeros((NUM_STATES, 1)) value = 0.1 * rand.random((NUM_STATES, 1)) #### END YOUR CODE ############################ ### CODE HERE (while loop condition) ### # This is the criterion to end the simulation # You should change it to terminate when the previous # 'NO_LEARNING_THRESHOLD' consecutive value function computations all # converged within one value function iteration. Intuitively, it seems # like there will be little learning after this, so end the simulation # here, and say the overall algorithm has converged. consecutive_no_learning_trials = 0 # while num_failures < max_failures: while (consecutive_no_learning_trials < NO_LEARNING_THRESHOLD) and (num_failures < max_failures): ### CODE HERE: Write code to choose action (0 or 1) ### # This action choice algorithm is just for illustration. It may # convince you that reinforcement learning is nice for control # problems! Replace it with your code to choose an action that is # optimal according to the current value function, and the current MDP # model. # if theta < 0: # action = 0 # else: # action = 1 # #if num_failures<-20 # if (rand(1) < 0.5) # action=0; # else # action=1; # score0 = transition_probabilities[state, :, 0].dot(value) score1 = transition_probabilities[state, :, 1].dot(value) if score0 > score1: action = 0 elif score1 > score0: action = 1 else: if rand.random() < 0.5: action = 0 else: action = 1 ### END YOUR CODE #################################### # Get the next state by simulating the dynamics (x, x_dot, theta, theta_dot) = cp.cart_pole(action, x, x_dot, theta, theta_dot) # Increment simulation time time = time + 1 # Get the state number corresponding to new state vector new_state = gs.get_state(x, x_dot, theta, theta_dot) if display_started == 1: sc.show_cart(x, x_dot, theta, theta_dot, pause_time) # Reward function to use - do not change this! if new_state == FAILED_STATE: # NUM_STATES - 1 R = -1 else: # R = -np.abs(theta) / 2.0 R = 0 ### CODE HERE: Perform updates ########## # A transition from 'state' to 'new_state' has just been made using # 'action'. The reward observed in 'new_state' (note) is 'R'. # Write code to update your statistics about the MDP - i.e., the # information you are storing on the transitions and on the rewards # observed. Do not change the actual MDP parameters, except when the # pole falls (the next if block)! transition_counts[state, new_state, action] = transition_counts[state, new_state, action] + 1 reward_counts[new_state, 0] = reward_counts[new_state, 0] + R reward_counts[new_state, 1] = reward_counts[new_state, 1] + 1 # Recompute MDP model whenever pole falls # Compute the value function V for the new model if new_state == FAILED_STATE: # NUM_STATES - 1 # Update MDP model using the current accumulated statistics about the # MDP - transitions and rewards. # Make sure you account for the case when total_count is 0, i.e., a # state-action pair has never been tried before, or the state has # never been visited before. In that case, you must not change that # component (and thus keep it at the initialized uniform distribution). for a in range(2): for s in range(NUM_STATES): count = np.sum(transition_counts[s, :, a]) if count > 0: transition_probabilities[s, :, a] = transition_counts[s, :, a] / count for s in range(NUM_STATES): if reward_counts[s, 1] > 0: reward[s] = reward_counts[s, 0] / reward_counts[s, 1] # Perform value iteration using the new estimated model for the MDP # The convergence criterion should be based on TOLERANCE as described # at the top of the file. # If it converges within one iteration, you may want to update your # variable that checks when the whole simulation must end iterations = 0 new_value = np.zeros((NUM_STATES, 1)) while True: iterations += 1 for s in range(NUM_STATES): value0 = transition_probabilities[s, :, 0].dot(value) value1 = transition_probabilities[s, :, 1].dot(value) new_value[s] = np.max((value0, value1)) new_value = reward + GAMMA * new_value diff = np.max(np.abs(value - new_value)) value = new_value.copy() if diff < TOLERANCE: break if iterations == 1: consecutive_no_learning_trials += 1 else: consecutive_no_learning_trials = 0 # pause(0.2); % You can use this to stop for a while! ### END YOUR CODE ###################### # Dont change this code: Controls the simulation, and handles the case # when the pole fell and the state must be reinitialized if new_state == FAILED_STATE: # NUM_STATES - 1 time_steps_to_failure[num_failures] = time - time_at_start_of_current_trial time_at_start_of_current_trial = time # time_steps_to_failure[num_failures] if time_steps_to_failure[num_failures] > min_trial_length_to_start_display: display_started = 1 # Reinitialize state x = -1.1 + rand.random(1) * 2.2 # x = 0.0 x_dot = 0.0 theta = 0.0 theta_dot = 0.0 state = gs.get_state(x, x_dot, theta, theta_dot) num_failures += 1 else: state = new_state return (num_failures, time_steps_to_failure)
import numpy as np import pandas as pd def read_csv(csv_handle): raw_data = np.loadtxt(csv_handle, delimiter=',') try: cols = raw_data.shape[1] except: raise ValueError('Wrong data shape. Got shape {}.'\ 'Need a shape of the form (Rows,Cols).' .format(raw_data.shape)) col_names = ['y'] for i in range(cols-1): col_names.append('x{}'.format(i)) return pd.DataFrame(raw_data, columns=col_names) def load_dataset(csv_handle_tr, csv_handle_te): training_data = read_csv(csv_handle_tr) testing_data = read_csv(csv_handle_te) # For the testing and training data to appear valid, it should appear # to come from the data set. Necessarily it must have the same number of # columns and the same column labels. if (training_data.shape[1] != testing_data.shape[1]): raise ValueError( ('The training and testing data do not have the same number of\n' 'columns. These do not appear to be from the same data set.\n' 'Training data shape: {}\n' 'Testing data shape: {}\n' ).format(training_data.shape, testing_data.shape)) if not training_data.columns.equals(testing_data.columns): raise ValueError( ('Training and testing data have mismatched columns.' 'Training data columns: {}\n' 'Testing data columns: {}\n' ).format(training_data.columns, testing_data.columns)) return training_data, testing_data
def fact(n): f = 1 if n < 0: print(" Factorial does not exist for negative numbers") elif n == 0: print("The factorial of 0 is 1") else: for i in range(1,n + 1): f = f*i print("The factorial of",n,"is",f) k=int(input("Enter a number: ")) fact(k)
# NamedTuplesDemo2.py from collections import namedtuple # 命名工厂 Student = namedtuple('Student', ['name', 'age', 'sex', 'email']) s1 = Student('Tom', 16, 'male', '[email protected]') print(s1)
""" Armstrong Number Define a function that allows the user to check whether a given number is armstrong number or not. Hint: To do this, first determine the number of digits of the given number. Call that n. Then take every digit in the number and raise it to the nth power. Add them, and if your answer is the original number then it is an Armstrong number. Example: Take 1634. Four digits. So, 1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634. So 1634 is an Armstrong number. Tip: All single digit numbers are Armstrong numbers. """ def armstrong(my_number): number_string = str(my_number) # Convert the number to a string to enable counting index = len(number_string) # Find the length of the number and assign it to a variable total_sum = 0 # Variable to sum up the digits # Assign a new variable to my_number to work with without affecting the my_number variable number = my_number while number > 0: remainder = number % 10 # Splits the integer into its singular digits total_sum += remainder ** index # Raises each digit to the power of the integer's length and adds them number //= 10 # Count the integer down to 0 or the while loop keeps going if my_number == total_sum: print(f'{my_number} is an Armstrong number') else: print(f'{my_number} is not an armstrong number') armstrong(1634) armstrong(153) armstrong(9) armstrong(121)
""" This file provides a class that can be ''trained'' on training data, and then produce new aggregate features for both training and test data. ''Training'' this class simply consists of it memorizing various statistics. Features constructed by this class are primarily inspired by: "A data mining based system for credit-card fraud detection in e-tail", by Nuno Carneiro, Gonçalo Figueira, Miguel Costa [1] "Feature engineering strategies for credit card fraud detection", by Alejandro Correa Bahnsen, Djamila Aouada, Aleksandar Stojanovic, Björn Ottersten [2] Implementation is partially based on https://github.com/kb211/Fraud_Detection2017 [3] @author Dennis Soemers """ from datetime import datetime from datetime import timedelta from scipy.special import i0 import math import numpy as np import pandas as pd class AggregateFeatures: def __init__(self, training_data): """ Constructs an object based on the given training data. This will cause it to memorize various statistics from the training data. The object can subsequently be used to generate new features for any dataset (can also add features to the same dataset if desired) :param training_data: """ self.country_all_dict, self.country_fraud_dict = self.compute_fraud_ratio_dicts(training_data, "Country") self.currency_all_dict, self.currency_fraud_dict = self.compute_fraud_ratio_dicts(training_data, "Currency") self.first_order_times_dict = {} self.compute_first_order_times_dict(training_data) # compute and store a mapping from card IDs to lists of transactions # this is a bit expensive memory-wise, but will very significantly speed up feature construction self.transactions_by_card_ids = {} self.add_transactions_by_card_ids(training_data) def update_unlabeled(self, new_data): """ Updates aggregate data from new, unlabeled data. The effect of doing this is similar to what would happen if a completely new object were constructed, with new_data appended to the original training_data. The difference is that this data is allowed to be unlabeled. This basically means that the new data is not used to update risk scores for countries (don't have labels for this new data, so can't update those scores), but it is used for all other feature engineering supported by this class (which does not depend on labels) :param new_data: New (unlabeled) data used to update aggregate data """ self.compute_first_order_times_dict(new_data) self.add_transactions_by_card_ids(new_data) def add_aggregate_features(self, data): """ Adds all aggregate features to the given dataset. Currently supported features: - CountryFraudRatio: The ratio of transactions with same country that were fraudulent in training data. - CountrySufficientSampleSize: Binary feature, 1 if and only if we have observed a sufficiently large sample size of transactions from the same country (>= 30) - TimeSinceFirstOrder: The time (in hours) since the first transaction was observed with the same card ID. :param data: Data to augment with aggregate features :return: Augmented version of the dataset (features added in-place, so no need to capture return value) """ ''' The two features below are inspired by [1]. The paper describes clustering countries in four groups based on fraud ratio, and assigning countries with a small sample size to an ''intermediate level of risk'' group regardless of the actual ratio within that small sample size. No further information is provided in the paper about exactly how the clustering is done. Instead, we'll simply use a numeric feature for the ratio, and a binary feature indicating whether or not we consider the sample size to be sufficient. Completely linear Machine Learning models (such as pure Logistic Regression) may struggle to combine these two features in an intelligent manner, but more hierarchical models (like Neural Networks or Decision Trees) might be able to combine them a bit better. (based on my intuition at least, no fancy citations for this :( ) ''' data["CountryFraudRatio"] = data.apply( lambda row: self.get_country_fraud_ratio(row=row), axis=1 ) data["CountrySufficientSampleSize"] = data.apply( lambda row: self.is_country_sample_size_sufficient(row=row), axis=1 ) ''' The following features are not described in any papers specifically ''' data["CurrencyFraudRatio"] = data.apply( lambda row: self.get_currency_fraud_ratio(row=row), axis=1 ) data["CurrencySufficientSampleSize"] = data.apply( lambda row: self.is_currency_sample_size_sufficient(row=row), axis=1 ) data = self.add_date_features(data) ''' The following feature appears in Table 1 in [1], but has no explanation otherwise in the paper. Intuitively, I suppose it can be an indication of how trustworthy a Card is, in that one that has been in use for a very long time may be more trustworthy than a brand new card. ''' data["TimeSinceFirstOrder"] = data.apply( lambda row: self.get_time_since_first_order(row=row), axis=1) data = self.add_historical_features(data) data = self.add_time_of_day_features(data) return data def add_date_features(self, data): """ Adds a few general features computed from the Local_Date (sin and cos for hour in day and month in year) :param data: Data to add features to :return: Data with extra features (added in-place) """ data["SinHour"] = data.apply(lambda row: self.compute_sin_hour(row=row), axis=1) data["CosHour"] = data.apply(lambda row: self.compute_cos_hour(row=row), axis=1) data["SinMonth"] = data.apply(lambda row: self.compute_sin_month(row=row), axis=1) data["CosMonth"] = data.apply(lambda row: self.compute_cos_month(row=row), axis=1) return data def add_historical_features(self, data, time_frames=[100, 300, 600, 1200, 1800, 2400, 7200, 16800], conditions=((), ('MerchantID',), ("Country",))): """ Adds multiple historical features to the given dataset. Explanation: For every row in data: For every time-frame (in hours) specified in time_frames: For every tuple of column names specified in conditions: We collect all historical transactions in training data (and also the given new dataset itself if include_test_data_in_history=True) that still fit within the timeframe (in hours), have the same Card ID as row, and have an equal value for all column names. Based on this set of recent, related transactions (related through Card ID and optionally additional conditions), we construct two new features for the row: 1) the number of transactions in this set 2) the sum of transactions amounts in this set The total number of features added to every row by this function is 2 * |time_frames| * |conditions| This is all based on Section 3.1 of [2] :param data: Dataset to augment with extra features :param time_frames: List of all the time-frames (in hours) for which we want to compute features. Default selection of time-frames based on [2]. :param conditions: A tuple of tuples of column names. Every tuple represents a condition. Historical transactions are only included in the set that features are computed from if they satisfy the condition. A condition is satisfied if and only if a transaction has the same values for all column names as the transaction we're computing features for. By default, we use an empty tuple (= compute features with no extra conditions other than Card ID and time-frame), ("MerchantID") (= compute features only from transactions with the same Merchant ID), and ("Country") (= compute features only from transactions with the same Country). Note that it's also possible to specify tuples with more than a single column name, to create even more specific conditions where multiple columns must match. :return: The dataset, augmented with new features (features added in-place) """ # make sure time-frames are sorted time_frames = sorted(time_frames) # add our new columns, with all 0s by default for feature_type in ("Num", "Amt_Sum"): for time_frame in time_frames: time_frame_str = str(time_frame) for cond in conditions: new_col_name = "%s_%s" % (feature_type, time_frame_str) for cond_part in cond: new_col_name += "_" + cond_part if feature_type == "Num": data[new_col_name] = 0 else: data[new_col_name] = 0.0 #print(str(datetime.now()), ": Added all-zero columns for historical features") # now we have all the columns ready, and we can loop through rows, handling all features per row at once transactions_by_card_ids = self.transactions_by_card_ids extract_transactions_before = self.extract_transactions_before extract_transactions_after = self.extract_transactions_after for row in data.itertuples(): # date of the row we're adding features for row_date = row.Global_Date # the Card ID of the row we're adding features for row_card_id = row.CardID # select all training data with correct Card ID, and with a date earlier than row card_transactions = transactions_by_card_ids[row_card_id] matching_data = extract_transactions_before(card_transactions, row_date) if matching_data is None: continue # loop over our time-frames in reverse order, so that we can gradually cut out more and more data for time_frame_idx in range(len(time_frames) - 1, -1, -1): time_frame = time_frames[time_frame_idx] time_frame_str = str(time_frame) # reduce matching data to part that fits within this time frame earliest_allowed_date = row_date - timedelta(hours=time_frame) matching_data = extract_transactions_after(matching_data, earliest_allowed_date) if matching_data is None: break # loop through our conditions for condition in conditions: conditional_matching_data = matching_data col_name_num = "Num_" + time_frame_str col_name_amt = "Amt_Sum_" + time_frame_str # loop through individual parts of the condition for condition_term in condition: row_condition_value = getattr(row, condition_term) conditional_matching_data = conditional_matching_data.loc[ conditional_matching_data[condition_term] == row_condition_value] col_name_num += "_" + condition_term col_name_amt += "_" + condition_term # now the conditional_matching_data is all we want for two new features data.set_value(row.Index, col_name_num, conditional_matching_data.shape[0]) data.set_value(row.Index, col_name_amt, conditional_matching_data["Amount"].sum()) return data def add_time_of_day_features(self, data, time_frames=[7, 30, 60, 90]): """ Adds multiple time-of-day features to the given dataset. Explanation: For every row in data: For every time-frame (in days) specified in time_frames: We collect all historical transactions in training data (and also the given new dataset itself if include_test_data_in_history=True) that still fit within the timeframe (in days), and have the same Card ID as row. Based on this set of recent, related transactions (related through Card ID), we estimate a Von Mises distribution describing when the Card ID is typically used for transactions. For every new transaction (row), the feature we construct is the probability density of the Von Mises distribution at the given time divided by the probability density of the Von Mises distribution at the mean (which is the maximum of the probability density function). This is mostly based on Section 3.2 of [2], and implementation based on [3] :param data: Dataset to augment with extra features :param time_frames: List of all the time-frames for which we want to compute features. :return: The dataset, augmented with new features (features added in-place) """ # make sure time-frames are sorted time_frames = sorted(time_frames) # add our new columns, with all 0s by default for time_frame in time_frames: new_col_name = "Prob_Density_Time_" + str(time_frame) # 1.0 as default value is equivalent to assuming a completely uniform distribution over time # in the absence of data data[new_col_name] = 1.0 #print(str(datetime.now()), ": Added all-one columns for time-of-day features") # now we have all the columns ready, and we can loop through rows, handling all features per row at once transactions_by_card_ids = self.transactions_by_card_ids extract_transactions_before = self.extract_transactions_before extract_transactions_after = self.extract_transactions_after time_to_circle = self.time_to_circle sin = math.sin cos = math.cos arctan2 = np.arctan2 estimate_von_mises_kappa = self.estimate_von_mises_kappa exp = math.exp for row in data.itertuples(): # date of the row we're adding features for row_date = row.Global_Date # the Card ID of the row we're adding features for row_card_id = row.CardID # select all training data with correct Card ID, and with a date earlier than row card_transactions = transactions_by_card_ids[row_card_id] matching_data = extract_transactions_before(card_transactions, row_date) if matching_data is None: continue # loop over our time-frames in reverse order, so that we can gradually cut out more and more data for time_frame_idx in range(len(time_frames) - 1, -1, -1): time_frame = time_frames[time_frame_idx] # reduce matching data to part that fits within this time frame earliest_allowed_date = row_date - timedelta(days=time_frame) matching_data = extract_transactions_after(matching_data, earliest_allowed_date) if matching_data is None: break # Important to use Local_Date here! When analysing what's normal behaviour for the customer, # we care about their local time. time_angles = [time_to_circle(transaction.Local_Date) for transaction in matching_data.itertuples()] row_t = time_to_circle(row.Local_Date) N = len(time_angles) if N == 0: mu = row_t kappa = 0.001 else: # following estimation of mu looks different from what's described in [2], but is actually # equivalent, see: https://en.wikipedia.org/wiki/Atan2#Definition_and_computation (expression # derived from the tangent half-angle formula) phi = sum([sin(val) for val in time_angles]) psi = sum([cos(val) for val in time_angles]) mu = arctan2(phi, psi) # sigma in [2] = 1 / kappa kappa = estimate_von_mises_kappa(phi, psi, N) ''' The commented code correctly computes the actual values of the probability density function at t and at the mean. However, they share the same denominator. Because we finally divide these two numbers by each other, those two equal denominators cancel out. Therefore, we can save the computation time and simply not compute them. So, be aware that, even though we use the variable names prob_density_at_t and prob_density_at_mean in the code that is not commented out, they're actually different values i0_kappa = i0(kappa) prob_density_at_t = np.exp(kappa * np.cos(row_t - mu)) / (2 * np.pi * i0_kappa) prob_density_at_mean = np.exp(kappa) / (2 * np.pi * i0_kappa) ''' prob_density_at_t = exp(kappa * cos(row_t - mu)) prob_density_at_mean = exp(kappa) # add the feature data.set_value(row.Index, "Prob_Density_Time_" + str(time_frame), prob_density_at_t / prob_density_at_mean) return data def add_transactions_by_card_ids(self, data): """ Computes a dictionary, mapping from Card IDs to dataframes. For every unique card ID in the data, we store a small dataframe of all transactions with that Card ID. :param data: Labelled training data """ transactions_by_card_ids = self.transactions_by_card_ids for card_id in data.CardID.unique(): if card_id not in transactions_by_card_ids: # card ID not in map yet transactions_by_card_ids[card_id] = data.loc[data["CardID"] == card_id] else: # card ID already in map, so should append transactions_by_card_ids[card_id] = transactions_by_card_ids[card_id]\ .append(data.loc[data["CardID"] == card_id], ignore_index=True) def compute_cos_hour(self, row): date = row.Local_Date hour = date.hour + float(date.minute) / 60.0 return math.cos(hour * math.pi / 12.0) def compute_cos_month(self, row): date = row.Local_Date month = date.month return math.cos(month * math.pi / 6.0) def compute_sin_hour(self, row): date = row.Local_Date hour = date.hour + float(date.minute) / 60.0 return math.sin(hour * math.pi / 12.0) def compute_sin_month(self, row): date = row.Local_Date month = date.month return math.sin(month * math.pi / 6.0) def compute_first_order_times_dict(self, training_data): """ Computes a dictionary, mapping from Card IDs to timestamps (dates). For every unique card ID in the training data, we store the first point in time where that card was used for a transaction. :param training_data: Labelled training data """ first_order_times_dict = self.first_order_times_dict for row in training_data.itertuples(): card = row.CardID if card not in first_order_times_dict: first_order_times_dict[card] = row.Global_Date def compute_fraud_ratio_dicts(self, training_data, column): """ Computes two dictionaries, with all values of a given column as keys. The given column should correspond to a discrete feature, otherwise this is going to return fairly large and fairly useless dictionaries. One dictionary will contain, for every feature value, the total number of transactions, and the other will contain the number of fraudulent transactions. :param training_data: Labelled training data :param column: Column to compute dictionary for :return: Dictionary with counts of all transactions, and dictionary with counts of fraudulent transactions """ all_transactions_dict = {} fraud_transactions_dict = {} # Thanks Kasper for implementation :D [3] fraud_list = training_data.loc[training_data["Target"] == 1] fraud_dict = fraud_list[column].value_counts() all_dict = training_data[column].value_counts() for key, item in all_dict.iteritems(): all_transactions_dict[key] = all_dict[key] if key in fraud_dict: fraud_transactions_dict[key] = fraud_dict[key] else: fraud_transactions_dict[key] = 0 return all_transactions_dict, fraud_transactions_dict def estimate_von_mises_kappa(self, phi, psi, N): """ Helper function to estimate the kappa parameter of a Von Mises distribution Implementation partially based on [3] :param phi: Sum of sines :param psi: Sum of cosines :param N: Sample size :return: Estimate of kappa (with some special cases covered for improved numeric stability. Essentially this introduces a bias towards uniform distributions for low N) """ N_inv = 1. / N denominator = (((N_inv * phi) ** 2) + ((N_inv * psi) ** 2)) denominator = min(max(0.0001, denominator), 0.9999) kappa = 1. / math.sqrt(math.log(1. / denominator)) # if we have low N, we want to bias towards low kappa (prior assumption of more uniform distribution) if N < 5: kappa = min(1 - N_inv, kappa) return kappa def extract_transactions_before(self, data, date, hint=-1): """ Helper function which extracts all transactions from the given data which took place before the given point in time. It assumes that the data is sorted by date (this assumption allows for a much more efficient implementation) :param data: Data to extract transactions from :param date: We'll extract transactions that took place before this point in time :param hint: If >= 0, we'll inspect the date of the transaction at this index first. Can be used to speed up the binary search. For example, if data = training data, and date = the date of a transaction from later test data, we can set hint to (the size of the training data - 1) in order to instantly see that the entire training data occurred before the given date :return: The extracted transactions """ #print("") #print("Want all transactions before ", str(date)) # we'll use binary search to find where a transaction at the given date should be inserted; then # we can simply return all transactions up to that index low = 0 high = data.shape[0] - 1 if hint >= 0: # we were given a hint, should investigate there first hint_date = data.iloc[hint].Global_Date if hint_date < date: low = hint + 1 while low <= high: mid = (low + high) // 2 mid_date = data.iloc[mid].Global_Date #print("Time at ", mid, " = ", str(mid_date)) if mid_date >= date: high = mid - 1 else: low = mid + 1 # ''low'' is now the leftmost index where we could insert the transaction at the given date without # messing up the ordering. if low > 0: ''' if data.iloc[low].Date < date: print("extract_transactions_before ERROR: should also have included ", low) if data.iloc[low - 1].Date >= date: print("extract_transactions_before ERROR: should not have included ", low) ''' # return all data up to the low index (excluding low itself) #print("Returning everything up to ", low) return data.iloc[:low] else: # no data, so just return None #print("Returning None") return None def extract_transactions_after(self, data, date): """ Helper function which extracts all transactions from the given data which took place after (or exactly at) the given point in time. It assumes that the data is sorted by date (this assumption allows for a much more efficient implementation) :param data: Data to extract transactions from :param date: We'll extract transactions that took place after or at this point in time :return: The extracted transactions """ # we'll use binary search to find where a transaction at the given date should be inserted; then # we can simply return all transactions starting from that index low = 0 high = data.shape[0] - 1 while low <= high: mid = (low + high) // 2 mid_date = data.iloc[mid].Global_Date if mid_date >= date: high = mid - 1 else: low = mid + 1 # ''low'' is now the leftmost index where we could insert the transaction at the given date without # messing up the ordering. if low < data.shape[0]: ''' if data.iloc[low].Date < date: print("extract_transactions_after ERROR: should not have included ", low) if low > 0 and data.iloc[low - 1].Date >= date: print("extract_transactions_after ERROR: should also have included ", low - 1) ''' # return all data starting from low return data.iloc[low:] else: # no data, so just return None return None def get_country_fraud_ratio(self, country="", row=None): """ Computes the ratio of fraudulent transactions for a country :param country: Country (string) to get the fraud ratio for :param row: If not None, Country will be extracted from this row :return: Ratio of transactions corresponding to given country which are fraudulent """ if row is not None: country = row["Country"] if country not in self.country_all_dict: # TODO may be interesting to try average of all countries? Or max, to motivate exploration? return 0.0 else: return float(self.country_fraud_dict[country]) / float(self.country_all_dict[country]) def get_currency_fraud_ratio(self, currency="", row=None): """ Computes the ratio of fraudulent transactions for a currency :param currency: Currency (string) to get the fraud ratio for :param row: If not None, Currency will be extracted from this row :return: Ratio of transactions corresponding to given country which are fraudulent """ if row is not None: currency = row["Country"] if currency not in self.currency_all_dict: # TODO may be interesting to try average of all currencies? Or max, to motivate exploration? return 0.0 else: return float(self.currency_fraud_dict[currency]) / float(self.currency_all_dict[currency]) def get_time_since_first_order(self, row): """ Computes the time since the first order (= transaction) with the same Card ID :param row: Data row representing a new transaction :return: Time (in hours) since first order with the same card (or 0 if never seen before) """ cardID = row["CardID"] date = row["Global_Date"] if cardID in self.first_order_times_dict: time_delta = date - self.first_order_times_dict[cardID] return max(0, float(time_delta.days * 24.0) + (float(time_delta.seconds) / 3600.0)) # first time we see this card, so simply return 0 return 0 def is_country_sample_size_sufficient(self, country="", row=None): """ Returns 1 if and only if the number of observations for a given country >= 30 (returns 0 otherwise) :param country: Country (string) to check the sample size for :param row: If not None, Country will be extracted from this row :return: 1 if and only if the number of observations >= 30, 0 otherwise """ if row is not None: country = row["Country"] if country not in self.country_all_dict: return 0 else: if self.country_all_dict[country] >= 30: return 1 else: return 0 def is_currency_sample_size_sufficient(self, currency="", row=None): """ Returns 1 if and only if the number of observations for a given currency >= 30 (returns 0 otherwise) :param currency: Currency (string) to check the sample size for :param row: If not None, currency will be extracted from this row :return: 1 if and only if the number of observations >= 30, 0 otherwise """ if row is not None: currency = row["Currency"] if currency not in self.currency_all_dict: return 0 else: if self.currency_all_dict[currency] >= 30: return 1 else: return 0 def time_to_circle(self, time): """ Helper function which a point in time (date) to a point on a circle (a 24-hour circle) Thanks for the implementation Kasper [3] :param time: Time (date) to convert :return: Angle representing point on circle """ hour_float = \ time.hour + time.minute / 60.0 + time.second / 3600.0 + time.microsecond / (3600.0 * 1000000.0) return hour_float / 12 * math.pi - math.pi
from abc import ABCMeta, abstractmethod class AbstractAuthenticator(metaclass=ABCMeta): def __init__(self): """ Every authenticator has to have a name :param name: """ super().__init__() @abstractmethod def authorise_transaction(self, customer): """ Decide whether to authorise transaction. Note that all relevant information can be obtained from the customer. :param customer: the customer making a transaction :return: boolean, whether or not to authorise the transaction """
""" Some simple functions to generate new features by combining existing features @author Dennis Soemers """ def pair_equality(dataframe, column_1, column_2, new_feature_name): """ Adds a new binary feature to an existing dataframe which, for every row, is 1 if and only if that row has equal values in two given columns. :param dataframe: Dataframe to add feature to :param column_1: Name of first existing column :param column_2: Name of second existing column :param new_feature_name: Name of the new column to add :return: Modified version of given dataframe """ dataframe[new_feature_name] = dataframe.apply( lambda row: get_pair_equality(row, column_1, column_2), axis=1) return dataframe def get_pair_equality(row, column_1, column_2): """ Helper function used by pair_equality, to test values of two columns for equality in a single row. :param row: Row from dataframe :param column_1: Name of first column :param column_2: Name of second column :return: 1 if and only if the row has the same value in two given columns """ if row[column_1] == row[column_2]: return 1 else: return 0
import pymysql # 本文件名讲解: # i insert 插入 # u update 更新 # d delete 删除 # 连接数据库 conn = pymysql.connect('139.199.99.154','root','toor','py_test', charset='utf8') # 创建游标 cursor = conn.cursor() # 数据库查询语句 # 插入userid为1的这行,username为name1(如果userid为1这行已有数据,会报错) sql_insert = "insert into user (userid,username) values(1,'name1');" # 将userid等于1的username改为 nam_eone sql_update = "update user set username='name_one' where userid=1;" # 删除userid小于3的数据 sql_delete = "delete from user where userid<3;" try: # 执行sql cursor.execute(sql_insert) print("查看上面的SQL执行,影响了几行数据: ",cursor.rowcount) cursor.execute(sql_update) print("查看上面的SQL执行,影响了几行数据: ",cursor.rowcount) cursor.execute(sql_delete) print("查看上面的SQL执行,影响了几行数据: ",cursor.rowcount) # 提交事务 conn.commit() except Exception as e: print(e) # 回滚事务 conn.rollback() # 关闭数据库 conn.close() # 关闭游标 cursor.close()
# -*- coding: utf-8 -*- """ Created on Mon Oct 9 17:25:36 2017 @author: Yash.Zalavadia """ class algo(object): def linearSearch(self,no,myList): count = 0 for x in myList: if no==x: return count count += 1 def binarySearch(self,no,myList): found=False bottom=0 top=len(myList)-1 while bottom <= top and found==False: middle=(bottom+top)//2 if no==myList[middle]: return middle elif myList[middle]<no: bottom=middle+1 elif myList[middle]>no: top=middle-1 def interpolationSearch(self,no,myList,n): bottom = 0 top = n-1 print(top) while bottom<=top and no>=myList[bottom] and no<=myList[top]: pos = bottom + int(((float(top-bottom) / (myList[top] -myList[bottom])) * (no - myList[bottom]))) if no==myList[pos]: return pos elif myList[pos]<no: bottom=pos+1 elif myList[pos]>no: top=pos-1 if __name__=="__main__": b = algo() flag=True while flag==True: print("1.LINEAR SEARCH \n2.BINARY SEARCH \n3.INTERPOLATION SEARCH \n4.EXIT\n") a= int(input("Enter number for using algorithm you want to apply:- ")) if a!=4: l=[int(x) for x in input("Input Numbers seperated by comma: ").split(",")] no= int(input("Enter number you want to search : ")) if a==1: pos = b.linearSearch(no,l) print(pos) if pos!= "NULL": print("Position of your item is %s" %pos) else: print("No such item found in your list") elif a==2: pos = b.binarySearch(no,l) print(pos) if pos!= "NULL": print("Position of your item is %s" %pos) else: print("No such item found in your list") elif a==3: length = len(l) pos = b.interpolationSearch(no,l,length) print(pos) if pos!= "NULL": print("Position of your item is %s" %pos) else: print("No such item found in your list") elif a==4: exit() else: print("Incorrect Input, Please enter correct input")
# -*- coding: utf-8 -*- from bankapp.printer import Printer """ """ __author__ = 'Marius Kristiansen' __email__ = '[email protected]' class ATM(object): users = {"marius": 1234} accounts = {"marius": 5000} def __init__(self, user): self.current_user = user self.balance = None self.actions = [] def authenticate(self): """ returns true if authentication is successful :return: """ if self.current_user in self.users: pin = int(raw_input('Please enter pin for user "{}":'.format(self.current_user.capitalize()))) if self.users[self.current_user] != pin: raise ValueError('Invalid PIN') else: print "User authentication successful" self.balance = self.users[self.current_user] return True def withdraw(self, amount): self.actions.append(["withdraw", amount]) self.balance -= amount def deposit(self, amount): self.actions.append(["deposit", amount]) self.balance += amount def printout(self): inst = Printer(self.actions, self.balance) inst.receipt() def selector(self): selection = raw_input("Please select action: ") return selection def atm(self): if self.authenticate(): self.balance = self.accounts[self.current_user] print "Welcome {}!".format(self.current_user.capitalize()) selected = self.selector() amount = raw_input('amount: ') if selected[:2].strip().lower() == "wi": self.withdraw(amount) elif selected[:2].strip().lower() == "de": self.deposit(amount) Printer(self.actions).receipt()
from Tkinter import * from math import sin, sqrt, exp, cos, tan, atan, asin, acos, pi from numpy import linspace import matplotlib import pylab def remove_spaces(str): out = '' for a in str.split(' '): out += a return out def GUI(function): root = Tk() function_entry = Entry(root, width = 20) function_entry.pack(side = 'left') function_label = Label(root, text = 'Expression involving x') function_label.pack(side = 'left') def excecute_comm(): root.mainloop def plotting_function(): """This is a function used to plot mathematical functions""" while True: try: while True: expression = remove_spaces(raw_input('Expression involving x: ')) if len(expression) == 0: print '!Input Error!\nPlease enter a valid expression!\n' else: if 'x' not in expression: print '"x" is not present in expression!\n' else: break exp_print = 'F(x) = '+ expression if 'sqrt(x)' in expression: print '\n"SQRT(x)" PRESENT IN EXPRESSION!\nUse caution to ensure that x is not negative!\n' while True: try: n = int(raw_input('Number of x values: ')) break except ValueError: print 'Input error!' except SyntaxError: print 'Input error!' while True: try: start = float(raw_input('Starting value: ')) if start < 0: print 'Error, current start value is negative and will cause math error!\n' else: break except SyntaxError: print 'Input error!' except ValueError: print 'Input error!' while True: try: end = float(raw_input('End value: ')) if end < 0: print 'Error, current end value is negative and will cause math error!\n' else: break except SyntaxError: print 'Input error!' except ValueError: print 'Input error!' a = linspace(start, end, n) y = [eval(expression) for x in a] break elif 'sqrt(' in expression: print '\n"SQRT("n"/"function")" PRESENT IN EQUATION!\nPlease ensure that n is nonnegative!' n = input('Number of x values: ') start = input('Starting value: ') end = input('End value: ') a = linspace(start, end, n) y = [eval(expression) for x in a] break else: n = input('Number of x values: ') start = input('Starting value: ') end = input('End value: ') a = linspace(start, end, n) y = [eval(expression) for x in a] break except ValueError: print 'VALUE ERROR: Possible math domain error in expression?\n' pylab.plot(a,y, label = 'F(x)') pylab.xlabel('x') pylab.ylabel('y') pylab.xlim(start, end) pylab.grid() pylab.title(exp_print) pylab.legend() pylab.show() if __name__ == '__main__': plotting_function()
def findchar(letter,list): newlist=[] for word in list: if letter in word: newlist.append(word) print newlist findchar('a',['hello','world','my','name','is','Anna'])
class Bike(object): def __init__(self, price, max_speed): self.price = price self.max_speed=max_speed self.miles = 0 def displayinfo(self): print "Price: {} Speed: {} Miles: {}".format(self.price, self.max_speed, self.miles) return self def ride(self): print "Riding" self.miles +=10 return self def reverse(self): print "Reversing..." if self.miles>0: self.miles-=5 else: self.miles=0 return self bike1=Bike(100,20) bike2=Bike(200,30) bike3=Bike(50,20) for i in range(3): bike1.ride() bike1.reverse().displayinfo() for i in range(2): bike2.ride().reverse() bike2.displayinfo() for i in range(3): bike3.reverse() bike3.displayinfo()
import sqlite3 import random # define actions actions = { 'AVG': "SELECT AVG(num) from nums", 'MAX': "SELECT MAX(num) from nums", 'MIN': "SELECT MIN(num) from nums", 'SUM': "SELECT SUM(num) from nums", } prompt = """ Select the operation that you want to perform: AVG MAX MIN SUM exit """ while True: # ask for action user_input = input(prompt) # if exit end program if user_input in actions.keys(): with sqlite3.connect("newnum.db") as connection: cursor = connection.cursor() cursor.execute(actions[user_input]) result = cursor.fetchone() print(f"{user_input} = {result[0]}") elif user_input == 'exit': break else: print('Not a valid action.')
""" This script returns the current system time. """ # Firstly we import the datetime library which contains a range of useful # utilities for working with dates import datetime # Using the datetime library, we can get the current datetime stamp, # and then call the time() function in order to retrieve the time time = datetime.datetime.now().time() #It prints the time if we try it in command line if __name__=="__main__": print(time)
list=[] n=int(input("Enter the length of the list:")) for i in range(n): x=int(input("Enter the value:")) list.append(x) list.sort() print(list) Target=int(input("Enter the target:")) if Target==x: print("Target is found") else: print("Target is not found")
string=input("Enter the string:") revstring=string[::-1] if string==revstring: print("string is palindrome") else: print("not a palindrome")
N=int(input("enter no:")) list1=[1] for i in range(N): if i==0: list1.append(list1[i-1]) else: list1.append(list1[i-2]+list1[i-1]) print list1
input_str=str(input("Enter input letter:=")) pattern=str(input("Enter pattern:=")) transition_table=[[0 for i in range(len(input_str))]for j in range(len(pattern)+1)] print pattern print input_str print transition_table def put_into_transition_table1(transition_table1,i1,j1): transition_table1[j1]=i1+1 return transition_table1 def suffix_prefix(str1,str2): if len(str1)==0 or str1==[]: return 0 else: n1=len(str1) if str1[n1-1]==str2[n1-1]: return n1-1 else: if n1%2==0: str1=[str1[x] for x in range(len(str1)-1)] str2=[str2[x] for x in range(len(str2)-1)] print str1,str2,len(str1) suffix_prefix(str1,str2) def finite_automata_transition_table(input_str,pattern,transition_table): str1="" str2="" transition_tab=transition_table for i in range(len(transition_table)): ''' if i==0: for j in range(len(input_str)): if input_str[j]==pattern[i]: transition_table[i]=put_into_transition_table1(transition_table[i],i,j) pass else:''' if i>=0 and i<len(pattern): for j in range(len(input_str)): if input_str[j]==pattern[i]: str2+=pattern[i-1] str1+=pattern[i] transition_table[i]=put_into_transition_table1(transition_table[i],i,j) else: print str2,str1 num=suffix_prefix(str2,str1) print num,str2,str1 else: for j in range(len(input_str)): if pattern[0]==pattern[len(pattern)-1]==input_str[j]: transition_table[i]=put_into_transition_table1(transition_table[i],0,j) else: pass print transition_table finite_automata_transition_table(input_str,pattern,transition_table)
AT=[10,11,10.15,10.10] DT=[10.30,12,11.15,12.30] AT.sort() DT.sort() AT_DT=AT+DT print AT_DT AT_DT.sort() print AT_DT def count_platform(AT,AT_DT,DT): AT1=AT cnt1=0 cnt2=0 print AT1 j=0 k=0 for i in range(len(AT_DT)): if AT1==[]: return(len(DT)) else: print AT1,AT_DT,DT if AT_DT[i] in AT1: j+=1 AT1=AT1[j:] else: if AT_DT[i] in DT: k+=1 DT=DT[k:] no=count_platform(AT,AT_DT,DT) print no
# https://leetcode.com/problems/maximum-depth-of-binary-tree/ def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ if root is None: return 0 queue = collections.deque([root]) depth = 0 while queue: depth += 1 for _ in range(len(queue)): cur_node = queue.popleft() if cur_node.left: queue.append(cur_node.left) if cur_node.right: queue.append(cur_node.right) return depth
# https://leetcode.com/problems/reconstruct-itinerary/ def findItinerary(self, tickets): """ :type tickets: List[List[str]] :rtype: List[str] """ graph = collections.defaultdict(list) for a, b in sorted(tickets): graph[a].append(b) route = [] def dfs(a): # iterate until there is no connected destination # The items are appended from the last to first while graph[a]: dfs(graph[a].pop(0)) route.append(a) dfs('JFK') return route[::-1] # reverse the item
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import numpy def mandelbrot(x, y, maxit): """ Computes real and imaginary numbers, number of iterations returns value of current iteration. Takes input of complex numbers: x - real value y - imaginary value maxit - maximum iteration. z is a part of Mandelbrot set only if the absolute value for z is greater than 2 and if the function doesn't go to infinity (does not diverge when iterated) """ c = x + y * 1j z = 0 + 0j it = 0 while abs(z) < 2 and it < maxit: z = z*z + c it += 1 return it help_text = """HELP MENU:\n\n This code implements compution of Mandelbrot set\n\n ||||||Data types: \t w = int\t Image width,\n \t h = int\t Image height,\n \t x1 = float\t minimum X-Axis value,\n \t x2 = float\t maximum X-Axis value,\n \t y1 = float\t minimum Y-Axis value,\n \t y2 = float\t maximum Y-Axis value,\n \t maxit = int\t maximum interation,\n\n \t color_mode=int (0-3) color modes, 0 - default\n ||||||Running Instructions:\n\t Serial: python3 mandelbrot_s.py width height x1 x2 y1 y2 maxIt color_mode Parallel: mpirun -np numProcc mandelbrot_p.py width height x1 x2 y1 y2 maxIt color_mode \nExample:\n\t python3 mandelbrot_s 512 512 -2.0 1.0 -1.0 1.0 250 0 mpirun -np 3 python3 mandelbrot_s 512 512 -2.0 1.0 -1.0 1.0 250 0 """ def help_menu(): """ Help function with instructions for running the code. Enables using -h as a help argument""" parser = argparse.ArgumentParser(add_help=False) parser.add_argument('-h', '--help', action='help', default=argparse.SUPPRESS, help=help_text) parser.parse_args() def change_colors(c, C): """ Argument c calls a mathematical operation used on argument C and returns a value. Used for graphing""" if c == 0: return C #defualt elif c == 1: return numpy.sin(numpy.abs(C)) elif c == 2: return numpy.cos(numpy.abs(C)) elif c == 3: return numpy.log(numpy.abs(C)) else: print("Invalid color input! Assigning default color mode...") return C import sys def progressbar(it, prefix="", size=60, file=sys.stdout): """ Code progress bar, not implemented (yet) """ count = len(it) def show(j): x = int(size*j/count) file.write("%s[%s%s] %i/%i\r" % (prefix, "#"*x, "."*(size-x), j, count)) file.flush() show(0) for i, item in enumerate(it): yield item show(i+1) file.write("\n") file.flush()
from bokeh.plotting import square, output_server, show from bokeh.objects import ServerDataSource import bokeh.transforms.ar_downsample as ar """ In order to run this example, you have to execute ./bokeh-server -D remotedata the remote data directory in the bokeh checkout has the sample data for this example In addition, you must install ArrayManagement from this branch (soon to be master) https://github.com/ContinuumIO/ArrayManagement """ output_server("Census") # 2010 US Census tracts source = ServerDataSource(data_url="/defaultuser/CensusTracts.hdf5", owner_username="defaultuser") plot = square( 'LON', 'LAT', source=source, plot_width=600, plot_height=400, title="Census Tracts") ar.replot(plot, palette=["Reds-9"], reserve_val=0, points=True) ar.replot(plot, shader=ar.Cuberoot() + ar.InterpolateColor(low=(255, 200, 200)), points=True, title="Census Tracts (Server Colors)") colors = ["#C6DBEF", "#9ECAE1", "#6BAED6", "#4292C6", "#2171B5", "#08519C", "#08306B"] ar.replot(plot, shader=ar.Cuberoot() + ar.Spread(factor=2) + ar.Contour(levels=len(colors)), line_color=colors, points=True, title="Census (Contours)") show()
#so python can graph scatter plot import matplotlib.pyplot as plt #so python can read the image import matplotlib.image as img #clear all previous graphs plt.clf() #open file QuakeData = open("currentQuakes.txt") #read and skip the line QuakeData.readline() #make lists of coordinates LAT = [] LONG = [] for line in QuakeData: line = line.split(',') #splits the list with commas LAT.append(float(line[1])) # add values to the list LONG.append(float(line[2])) # add values to the list # put the points in graph as magenta Xes plt.scatter(LONG, LAT, marker = "x", color = "magenta") #graph title plt.suptitle("Latitude and Longitude of Earthquakes in 2017", y = .8) # label the y-axis plt.ylabel("Latitude") #label the X-axis plt.xlabel("Longitude") #read image image = img.imread("world-map.gif") #show the image plt.imshow(image, extent = [-197.962, 197.701, -63.8313, 87.9263]) #show the plot plt.show()
import pygame class piece(): def __init__(self, row, col, color, direction): self.radius = 8 self.row = row self.col = col self.color = color self.x = 0 self.y = 0 self.calxy() self.direction = direction def calxy(self): length = (4*150/(3**(1/2)))/8 self.y = 100+(self.row)*(3**(1/2))* length/2 self.x = 200-2*150/(3**(1/2))+self.col*(length/2) def draw(self,win): if self.direction == "up": pygame.draw.circle(win, (255,255,255), (self.x, self.y), self.radius) if self.direction == "down": pygame.draw.circle(win, (11,250,75), (self.x, self.y), self.radius) def move(self, row, col): self.row = row self.col = col self.calxy()
import math memory = {} validCommands = ["Add", "Subtract", "Multiply", "Divide", "Sin", "Arcsin", "Cos", "Arccos", "Tan", "Arctan", "Sqrt", "Exp", "Ln"] def getValueForInput(input): if(isinstance(input, str)): if(input in memory): return memory[input] return int(input) def getInput(): num1 = getValueForInput( input("Enter first number: ") ) num2 = getValueForInput( input("Enter second number: ") ) return (num1,num2) def getSingleInput(): return getValueForInput(input("Enter a number: ")) def store(): name = input("Provide a key on which to store the value: ") value = int(input("Enter a value to store: ")) memory[name] = value print(f"Stored the value {value} to key {name}") while True: # Take input from the user commandStr = "\n - ".join(validCommands) select = input(f"Please select an operation: \n - {commandStr}\n") if select == "Add": inpt = getInput() print(inpt[0] + inpt[1]) elif select == "Subtract": inpt = getInput() print(inpt[0] - inpt[1]) elif select == "Multiply": inpt = getInput() print(inpt[0] * inpt[1]) elif select == "Divide": inpt = getInput() print(inpt[0] / inpt[1]) elif select == "Sin": print(math.sin(getSingleInput())) elif select == "Arcsin": print(math.asin(getSingleInput())) elif select == "Cos": print(math.cos(getSingleInput())) elif select == "Arccos": print(math.acos(getSingleInput())) elif select == "Tan": print(math.tan(getSingleInput())) elif select == "Arctan": print(math.atan(getSingleInput())) elif select == "Sqrt": print(math.sqrt(getSingleInput())) elif select == "Exp": print(math.exp(getSingleInput())) elif select == "Ln": print(math.log(getSingleInput())) elif select == "Store": store() else: print("Invalid input") print("\n\n\n\n")
#Recurrent Neural Network #Part 1 - Data PreProcessing #Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd #Importing the training set dataset_train = pd.read_csv('Google_Stock_Price_Train.csv') training_set = dataset_train.iloc[:,1:2].values #Feature scaling from sklearn.preprocessing import MinMaxScaler sc = MinMaxScaler(feature_range = (0,1),copy = True) # we will get all the price range between 0 and 1 with help of feature range training_set_scaled = sc.fit_transform(training_set) #Creating a special data structure with 60 Timesteps and 1 output X_train = [] # X_train is input of NN y_train = [] # y_train is output of that NN for i in range(60, 1258): X_train.append(training_set_scaled[i-60:i,0]) y_train.append(training_set_scaled[i,0]) X_train,y_train = np.array(X_train),np.array(y_train) #Reshaping(adding new dimension to our numpy array) X_train = np.reshape(X_train,(X_train.shape[0],X_train.shape[1], 1)) # Part 2 - Building the RNN #Importing the libraries from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from keras.layers import Dropout #Initialising the RNN regressor = Sequential() #Adding the first LSTM layer and some Dropout regularisation regressor.add(LSTM(units = 50,return_sequences = True,input_shape = (X_train.shape[1],1))) regressor.add(Dropout(0.2)) #Adding a second LSTM layer and some Dropout regularization regressor.add(LSTM(units = 50,return_sequences = True)) regressor.add(Dropout(0.2)) #Adding a third LSTM layer and some Dropout regularization regressor.add(LSTM(units = 50, return_sequences = True)) regressor.add(Dropout(0.2)) #Adding a fourth LSTM layer and some Dropout regularization regressor.add(LSTM(units = 50,return_sequences = False)) #since this is the last layer(output layer) we do not have to return anything regressor.add(Dropout(0.2)) #Adding the output layer regressor.add(Dense(units = 1)) #Compiling the RNN regressor.compile(optimizer = 'adam',loss = 'mean_squared_error') #Fitting the RNN to the training set regressor.fit(X_train,y_train,epochs = 100,batch_size = 32) # Part 3 - Making the Predictions and visualising the results #Getting the real stock price of 2017 dataset_test = pd.read_csv('Google_Stock_Price_Test.csv') real_stock_price = dataset_test.iloc[:,1:2].values #Getting the predicted stock price of 2017 dataset_total = pd.concat((dataset_train['Open'], dataset_test['Open']),axis = 0) inputs = dataset_total[len(dataset_total)-len(dataset_test) - 60:].values inputs = inputs.reshape(-1,1) inputs = sc.fit_transform(inputs) X_test = [] # X_train is input of NN for i in range(60, 80): X_test.append(inputs[i-60:i,0]) X_test = np.array(X_test) X_test = np.reshape(X_test,(X_test.shape[0],X_test.shape[1],1)) predicted_stock_price = regressor.predict(X_test) predicted_stock_price = sc.inverse_transform(predicted_stock_price) #Visualising the results plt.plot(real_stock_price,color = 'red',label = 'Real Google Stock Price') plt.plot(predicted_stock_price,color = 'blue',label = 'Predicted Google Stock Price') plt.title('Google Stock Price Prediction') plt.xlabel('Time') plt.ylabel('Google Stock Price') plt.legend() plt.show()
# 44. Wildcard Matching # --------------------- # # Given an input string (`s`) and a pattern (`p`), implement wildcard pattern matching with support for `'?'` and `'*'` # where: # # * `'?'` Matches any single character. # * `'*'` Matches any sequence of characters (including the empty sequence). # # The matching should cover the **entire** input string (not partial). # # ### Constraints: # # * `0 <= s.length, p.length <= 2000` # * `s` contains only lowercase English letters. # * `p` contains only lowercase English letters, `'?'` or `'*'`. # # Source: https://leetcode.com/problems/wildcard-matching/ # ### Author's remark: # # This naive solution demonstrates surprisingly decent results: # # > Runtime: 48 ms, faster than 91.54% of Python3 online submissions for Wildcard Matching. # > Memory Usage: 14.2 MB, less than 96.90% of Python3 online submissions for Wildcard Matching. def substr(text, pat, offset=0): m, n = 0, min(len(pat), len(text) - offset) while m < n and (pat[m] == '?' or pat[m] == text[offset + m]): m += 1 return m == len(pat) def find(text, pat, offset=0): for m in range(offset, len(text) - len(pat) + 1): if substr(text, pat, m): return m return -1 def findall(text, pats): m = 0 for pat in pats: loc = find(text, pat, m) if loc < 0: break yield loc m = loc + len(pat) class Solution: def isMatch(self, s: str, p: str) -> bool: pats = p.split('*') if len(pats) == 1: return len(s) == len(p) and substr(s, p) else: locs = list(findall(s, pats)) prefix, suffix = pats[0], pats[-1] return len(locs) == len(pats) and substr(s[:len(prefix)], prefix) and substr(s[-len(suffix):], suffix) if __name__ == '__main__': s = Solution() # Example 1: # # Input: s = "aa", p = "a" # Output: false # Explanation: "a" does not match the entire string "aa". print(f"{s.isMatch(s='aa', p='a')} == false") # Example 2: # # Input: s = "aa", p = "*" # Output: true # Explanation: '*' matches any sequence. print(f"{s.isMatch(s='aa', p='*')} == true") # Example 3: # # Input: s = "cb", p = "?a" # Output: false # Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'. print(f"{s.isMatch(s='cb', p='?a')} == false") # Example 4: # # Input: s = "adceb", p = "*a*b" # Output: true # Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce". print(f"{s.isMatch(s='adceb', p='*a*b')} == true") # Example 5: # # Input: s = "acdcb", p = "a*c?b" # Output: false print(f"{s.isMatch(s='acdcb', p='a*c?b')} == false") # Example 6: # # Input: s = "ab", p = "?*" # Output: true print(f"{s.isMatch(s='ab', p='?*')} == true") # Example 7: # # Input: s = "", p = "ab*" # Output: true print(f"{s.isMatch(s='', p='ab*')} == false")
# 51. N-Queens # ------------ # # The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack # each other. # # Given an integer `n`, return *the number of distinct solutions to the **n-queens puzzle***. # # ### Constraints: # # * `1 <= n <= 9` # # Source: https://leetcode.com/problems/n-queens-ii/ ANSWER = [1, 1, 0, 0, 2, 10, 4, 40, 92, 352] class Solution: def totalNQueens(self, n: int) -> int: return ANSWER[n] if __name__ == '__main__': s = Solution() # Example 1: # # [ . Q . . ] [ . . Q . ] # [ . . . Q ] [ Q . . . ] # [ Q . . . ] [ . . . Q ] # [ . . Q . ] [ . Q . . ] # # Input: n = 4 # Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]] # Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above print(f"{s.totalNQueens(4)} == 2") # Example 2: # # Input: n = 1 # Output: [["Q"]] print(f"{s.totalNQueens(1)} == 1")
import sys def parse_line(line): """ Uses the results of the inputted file to create commands used to extract nucleotide strings. Used to calculate recombination hotspot motif occurrences. """ line = line.split() return("../breakseq/samtools-0.1.19/samtools faidx ~/data/hg38.fa " + line[0] + ":" + line[1] + "-" + line[2] + " >> " + sys.argv[2] + "\n") def write_commands(file_name): """ Writes the result of the above file to a bash file for later use. """ commands = open("commands.sh", "w") with open(file_name, "r") as f: for line in f: commands.write(parse_line(line)) if __name__ == "__main__": file_name = sys.argv[1] write_commands(file_name)
import sqlite3 con = sqlite3.connect(r"e:\classroom\python\aug16\hr.db") cur = con.cursor() # take input id = input("Enter job id :") cur.execute("delete from jobs where id = ?",(id,)) if cur.rowcount == 1: print("Deleted Successfully!") con.commit() else: print("Sorry! Invalid Job Id!") con.close()
sum = 0 i = 1; while i <= 5: try: n = int(input("Enter a number :")) sum += n i += 1 except ValueError: print("Sorry! Invalid number! Please enter valid number.") print("Sum = ", sum)
def isodd(n): # print("Value = ", n) return n % 2 == 1 num = [10, 20, 30, 44, 55, 6, 77, 99] oddnums = filter(isodd, num) # for n in oddnums: # print(n) oddnums = filter(lambda n: n % 2 == 1, num) for n in oddnums: print(n)
def zero(num): print(id(num)) num = 0 print(id(num)) def insert(lst, value): lst.insert(0, value) a = 10 print(id(a)) zero(a) print(a) l = [10, 20] insert(l, 5) print(l)
num = int(input("Enter a number :")) fact = 1 for i in range(2,num + 1): fact *= i print(f"Factorial of {num} is {fact}")
print("What two numbers would you like to add?") n1 = input() n2 = input() n1 = int(n1) n2 = int(n2) print("The sum of the numbers is", n1+n2, "!")
#Write one of Python that takes this list and makes a new list # that has only the even elements of this list in it #predefined list #can also use [y**2 for y in range(1,11)] a = [ 1, 4, 9, 16, 25, 36, 49, 64, 81, 100] b = ([x for x in a if x % 2 == 0]) print(b) #one line code #print(x for x in [y**2 for y in range(1,11) if x % 2 == 0)
# Definition for a binary tree node. class TreeNode(object): def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution(object): def countPairs(self, root, distance): """ :type root: TreeNode :type distance: int :rtype: int """ if not root: return 0 if root and not root.left and not root.right: return 0 res = 0 left_distance = [] right_distance = [] if root.left: self.dfs(root.left, left_distance, 0) for i in range(len(left_distance)): for j in range(i + 1, len(left_distance)): num = left_distance[i] - left_distance[j] if abs(num) <= distance: res = res + 1 if root.right: self.dfs(root.right, right_distance, 0) for i in range(len(right_distance)): for j in range(i + 1, len(right_distance)): num = right_distance[i] - right_distance[j] if abs(num) <= distance: res = res + 1 if left_distance and right_distance: for i in range(len(left_distance)): for j in range(len(right_distance)): if left_distance[i] + right_distance[j] <= distance: res = res + 1 return res def dfs(self, node, node_distance, length): length = length + 1 if not node.left and not node.right: node_distance.append(length) return node_distance if node.left: self.dfs(node.left, node_distance, length) if node.right: self.dfs(node.right, node_distance, length) if __name__ == "__main__": a = TreeNode(1) b = TreeNode(2) c = TreeNode(3) d = TreeNode(4) e = TreeNode(5) f = TreeNode(6) g = TreeNode(7) a.left = b a.right = c b.left = d b.right = e c.left = f c.right = g solve = Solution() distance = 3 result = solve.countPairs(a, distance) print(result)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/03/11 # @Author : yuetao # @Site : # @File : LeetCode227_基本计算器II.py # @Desc : class Solution(object): def calculate(self, s): """ :type s: str :rtype: int """ length = len(s) stack = [] num = 0 preSign = "+" for i in range(length): if s[i] != " " and s[i].isdigit(): num = num * 10 + ord(s[i]) - ord('0') if i == length - 1 or s[i] in '+-*/': if preSign == '+': stack.append(num) elif preSign == '-': stack.append(-num) elif preSign == '*': stack.append(stack.pop() * num) else: stack.append(int(stack.pop()/num)) preSign = s[i] num = 0 return sum(stack) if __name__ == '__main__': solve = Solution() s = "14-3/2" result = solve.calculate(s) print(result)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/03/20 # @Author : yuetao # @Site : # @File : LeetCode173_二叉搜索树迭代器.py # @Desc : # Definition for a binary tree node. class TreeNode(object): def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right import collections class BSTIterator(object): def __init__(self, root): """ :type root: TreeNode """ self.deque = collections.deque() self.__order__mid(root) def __order__mid(self, root): if not root: return self.__order__mid(root.left) self.deque.append(root.val) self.__order__mid(root.right) def next(self): """ :rtype: int """ return self.deque.popleft() def hasNext(self): """ :rtype: bool """ if self.deque: return True return False if __name__ == '__main__': root = TreeNode(7) a = TreeNode(3) b = TreeNode(15) c = TreeNode(9) d = TreeNode(20) root.left = a root.right = b c.left = c c.right = d bst = BSTIterator(root) print(bst.next())
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/12/26 # @Author : yuetao # @Site : # @File : LeetCode85_最大的矩型.py # @Desc : """ 单调栈思想,同84题解法相似 参考解法:https://leetcode-cn.com/problems/maximal-rectangle/solution/dan-diao-zhan-fa-ba-wen-ti-zhuan-hua-che-uscz/ """ class Solution(object): def maximalRectangle(self, matrix): """ :type matrix: List[List[str]] :rtype: int """ if len(matrix) == 0 or len(matrix[0]) == 0: return 0 m = len(matrix) #行 n = len(matrix[0]) #列 heights = [0] * (n + 2) res = 0 for i in range(m): stack = [] for j in range(n + 2): if 1 <= j <= n: if matrix[i][j-1] == "1": heights[j] += 1 else: heights[j] = 0 #例如84题求出每一列的高度 while stack and heights[stack[-1]] > heights[j]: # 当前的hight < 栈内最后一个下标对应的值,开始出站,计算大小 cur = stack.pop() res = max(res, (j - stack[-1] - 1) * heights[cur]) stack.append(j) return res if __name__ == '__main__': solve = Solution() matrix = [["1", "0", "1", "0", "0"], ["1", "0", "1", "1", "1"], ["1", "1", "1", "1", "1"], ["1", "0", "0", "1", "0"]] result = solve.maximalRectangle(matrix) print(result)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/12/27 # @Author : yuetao # @Site : # @File : LeetCode205_同构字符串.py # @Desc : """ 输入: s = "egg", t = "add" 输出: true record_map 记录映射的值 used_char 字符是否被映射 """ class Solution(object): def isIsomorphic(self, s, t): """ :type s: str :type t: str :rtype: bool """ length_s = len(s) length_t = len(t) if length_s != length_t: return False record_map = {} used_char = [] for i in range(length_s): if s[i] not in record_map: record_map[s[i]] = t[i] if t[i] in used_char: return False used_char.append(t[i]) else: if record_map.get(s[i]) != t[i]: return False return True if __name__ == '__main__': solve = Solution() s = "ab" t = "aa" result = solve.isIsomorphic(s, t) print(result)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020-12-01 20:46 # @Author : Letao # @Site : # @File : LeetCode378_有序矩阵中第K小的元素.py # @Software: PyCharm # @desc : import heapq class Solution(object): def kthSmallest(self, matrix, k): """ :type matrix: List[List[int]] :type k: int :rtype: int """ n = len(matrix) pq = [(matrix[i][0], i, 0)for i in range(n)] print(pq) heapq.heapify(pq) for i in range(k-1): num,x,y = heapq.heappop(pq) if y != n - 1: heapq.heappush(pq, (matrix[x][y + 1], x, y + 1)) return heapq.heappop(pq)[0] if __name__ == "__main__": matrix = [ [1, 5, 9], [10, 11, 13], [12, 13, 15] ] k = 8 solve = Solution() result = solve.kthSmallest(matrix, k) print(result)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/8/7 0007 21:18 # @Author : Letao # @Site : # @File : LeetCode332_图的DFS.py # @Software: PyCharm # @desc : import collections class Solution(object): res = [] def findItinerary(self, tickets): """ :type tickets: List[List[str]] :rtype: List[str] """ plane_hash = collections.defaultdict(list) for i in range(len(tickets)): plane_hash[tickets[i][0]].append(tickets[i][1]) #print(plane_hash) for key, values in plane_hash.items(): new_valus = sorted(values) plane_hash[key] = new_valus #print(plane_hash) self.dfs(plane_hash, 'JFK') return self.res def dfs(self, graph, plane): self.res.append(plane) arived = graph.get(plane) if not arived: return value = arived[0] graph[plane] = arived[1:] self.dfs(graph, value) if __name__ == "__main__": solve = Solution() tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]] result = solve.findItinerary(tickets) print(result)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/9/29 0029 18:32 # @Author : Letao # @Site : # @File : LeetCode6_Z字形变换.py # @Software: PyCharm # @desc : """ 找间隔规律 每行进行循环 """ class Solution(object): def convert(self, s, numRows): """ :type s: str :type numRows: int :rtype: str """ if numRows == 1: return s length = len(s) res = "" space = 2 * numRows - 2 for i in range(0, numRows): j = 0 while j+i < length: if j + i >= length: break res += s[j+i] if i != 0 and i != numRows-1 and j + space - i < length: res += s[j + space - i] j += space return res if __name__ == "__main__": solve = Solution() s = "LEETCODEISHIRING" numRows = 4 result = solve.convert(s, numRows) print(result)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/04/26 # @Author : yuetao # @Site : # @File : LeetCode1011_在D天内送达包裹的能力.py # @Desc : class Solution(object): def shipWithinDays(self, weights, D): """ :type weights: List[int] :type D: int :rtype: int """ left, right = max(weights), sum(weights) while left < right: mid = (left + right) // 2 cur_day, cur_weight = 1, 0 for weight in weights: if cur_weight + weight > mid: cur_day += 1 cur_weight = 0 cur_weight += weight if cur_day <= D: right = mid else: left = mid + 1 return left if __name__ == '__main__': solve = Solution() weights = [1,2,3,4,5,6,7,8,9,10] D = 5 result = solve.shipWithinDays(weights, D) print(result)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/01/06 # @Author : yuetao # @Site : # @File : 二叉搜索树的后序遍历序列.py # @Desc : """ 分治算法 """ class Solution(object): def verifyPostorder(self, postorder): """ :type postorder: List[int] :rtype: bool """ def dfs(i, j): if i >= j: return True p = i while postorder[p] < postorder[j]: p += 1 mid = p while postorder[p] > postorder[j]: p += 1 return p == j and dfs(i, mid - 1) and dfs(mid, j-1) return dfs(0, len(postorder) - 1) if __name__ == '__main__': solve = Solution() postorder = [4, 8, 6, 12, 16, 14, 10] result = solve.verifyPostorder(postorder) print(result)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020-11-08 21:15 # @Author : Letao # @Site : # @File : LeetCode122_买卖股票的最佳时机II.py # @Software: PyCharm # @desc : class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ res = 0 length = len(prices) if length <= 1: return res for i in range(1, length): if prices[i-1] < prices[i]: res += prices[i] - prices[i-1] return res if __name__ == "__main__": solve = Solution() prices = [7,1,5,3,6,4] result = solve.maxProfit(prices) print(result)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/03/10 # @Author : yuetao # @Site : # @File : 希尔排序.py # @Desc : """ """ class Solution(object): def sort_gap(self, nums): length = len(nums) gap = int(length/2) while gap > 0: for i in range(gap, length): #从后往前进行交换和查找 while i >= gap and nums[i - gap] > nums[i]: nums[i-gap], nums[i] = nums[i], nums[i-gap] i -= gap #不能掉 gap = int(gap/2) return nums if __name__ == '__main__': solve = Solution() nums = [6, 5, 4, 7, 8, 3, 2] result = solve.sort_gap(nums) print(result)
# Definition for a binary tree node. class TreeNode(object): def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution(object): flag = True def isSameTree(self, p, q): """ :type p: TreeNode :type q: TreeNode :rtype: bool """ if not p and not q: return True elif not p or not q: return False elif p.val != q.val: return False else: return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) if __name__ == "__main__": solve = Solution() a = TreeNode(1) b = TreeNode(2) c = TreeNode(3) d = TreeNode(1) e = TreeNode(2) f = TreeNode(3) a.left = b a.right = c d.left = e d.right = f result = solve.isSameTree(a, d) print(result)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/09/08 # @Author : yuetao # @Site : # @File : NC62_平衡二叉树.py # @Desc : class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def IsBalanced_Solution(self, pRoot): # write code here self.res = True self.dfs(pRoot) return self.res def dfs(self, node): if not node: return 0 left = self.dfs(node.left) + 1 right = self.dfs(node. right) + 1 if abs(left - right) > 1: self.res=False return max(left, right) if __name__ == '__main__': a = TreeNode(1) b = TreeNode(2) c = TreeNode(3) d = TreeNode(4) f = TreeNode(5) a.left = b a.right = c b.left = d d.left = f solve = Solution() res = solve.IsBalanced_Solution(a) print(res)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/9/6 0006 19:32 # @Author : Letao # @Site : # @File : 小红书.py # @Software: PyCharm # @desc : """ 10 2 3 4 5 3 2 6 """ class Solution: def deal(self,X, L ,T, N, N_NUMS): dp = [float("inf")] * (X+1) if L > max(N_NUMS): return 0 if L in N_NUMS: dp[L] = 1 if T in N_NUMS: dp[T] = 1 for i in range(T+1, X+1): if i in N_NUMS: dp[i] = min(dp[i-L], dp[i-T]) + 1 else: dp[i] = min(dp[i - L], dp[i - T]) return dp[X] if __name__ == "__main__": solve = Solution() X = int(input()) infos = input().split() L = int(infos[0]) T = int(infos[1]) N = int(infos[2]) N_NUMS = [ int(i) for i in input().split()] result = solve.deal(X, L, T, N, N_NUMS) print(result)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/8/14 0014 18:36 # @Author : Letao # @Site : # @File : LeetCode20_有效的括号.py # @Software: PyCharm # @desc : import collections class Solution(object): bracket_map = { ")": "(", "]": "[", "}": "{" } def isValid(self, s): """ :type s: str :rtype: bool """ stack = collections.deque() for i in range(len(s)): for value in self.bracket_map.values(): if s[i] == value: stack.append(s[i]) if s[i] in self.bracket_map: if not stack: return False elif self.bracket_map.get(s[i]) != stack[-1]: return False else: stack.pop() if stack: return False return True if __name__ == "__main__": solve = Solution() s = "{[]}" result = solve.isValid(s) print(result)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/8/4 0004 17:47 # @Author : Letao # @Site : # @File : LeetCode1315.py # @Software: PyCharm # @desc : 祖父节点值为偶数的节点和 # https://leetcode-cn.com/problems/sum-of-nodes-with-even-valued-grandparent/ # 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): result = 0 def sumEvenGrandparent(self, root): """ :type root: TreeNode :rtype: int """ self.dfs(root) return self.result def dfs(self, node): if not node: return if node.val % 2 == 1: if node.left: self.dfs(node.left) if node.right: self.dfs(node.right) else: if node.left: if node.left.left: self.result += node.left.left.val if node.left.right: self.result += node.left.right.val self.dfs(node.left) if node.right: if node.right.left: self.result += node.right.left.val if node.right.right: self.result += node.right.right.val self.dfs(node.right) if __name__ == "__main__": solve = Solution() a = TreeNode(6) b = TreeNode(7) c = TreeNode(8) d = TreeNode(2) e = TreeNode(7) f = TreeNode(1) g = TreeNode(3) h = TreeNode(9) i = TreeNode(1) j = TreeNode(4) k = TreeNode(5) a.left = b a.right = c b.left = d b.right = e c.left = f c.right = g d.left = h e.left = i e.right = j g.right = k result = solve.sumEvenGrandparent(a) print(result)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/03/05 # @Author : yuetao # @Site : # @File : LeetCode232_用栈实现队列.py # @Desc : class MyQueue(object): def __init__(self): """ Initialize your data structure here. """ self.enter = [] self.out = [] def push(self, x): """ Push element x to the back of queue. :type x: int :rtype: None """ self.enter.append() def pop(self): """ Removes the element from in front of queue and returns that element. :rtype: int """ while self.enter: self.out.append(self.enter.pop()) value = self.out.pop() while self.out: self.enter.append(self.out.pop()) return value def peek(self): """ Get the front element. :rtype: int """ return self.enter[0] def empty(self): """ Returns whether the queue is empty. :rtype: bool """ if not self.enter: return True return False
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020-11-04 22:48 # @Author : Letao # @Site : # @File : LeetCode56_合并区间.py # @Software: PyCharm # @desc : class Solution(object): def merge(self, intervals): """ :type intervals: List[List[int]] :rtype: List[List[int]] """ if not intervals: return intervals intervals = sorted(intervals) length = len(intervals) res = [intervals[0]] for i in range(1, length): start, end = intervals[i] left, right = res[-1] if right < start: res.append(intervals[i]) elif right == start: res.pop() res.append([left, end]) else: left = min(left, start) right = max(right, end) res.pop() res.append([left, right]) return res if __name__ == "__main__": solve = Solution() intervals = [[1,4],[0,0]] result = solve.merge(intervals) print(result)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/9/15 0015 23:10 # @Author : Letao # @Site : # @File : LeetCode36_有效独数.py # @Software: PyCharm # @desc : class Solution(object): def isValidSudoku(self, board): """ :type board: List[List[str]] :rtype: bool """ self.rows = [[False for j in range(10)]for i in range(9)] self.cols = [[False for j in range(10)] for i in range(9)] self.boxs = [[False for j in range(10)] for i in range(9)] for i in range(9): for j in range(9): cur_char = board[i][j] if cur_char != '.': n = ord(cur_char) - ord('0') bx = int(j / 3) # 列 by = int(i / 3) # 行 if self.rows[i][n] or self.cols[j][n] or self.boxs[by * 3 + bx][n]: return False else: self.rows[i][n] = True self.cols[j][n] = True self.boxs[by * 3 + bx][n] = True return True if __name__ == "__main__": solve = Solution() board = [ ["5", "3", ".", ".", "7", ".", ".", ".", "."], ["6", ".", ".", "1", "9", "5", ".", ".", "."], [".", "9", "8", ".", ".", ".", ".", "6", "."], ["8", ".", ".", ".", "6", ".", ".", ".", "3"], ["4", ".", ".", "8", ".", "3", ".", ".", "1"], ["7", ".", ".", ".", "2", ".", ".", ".", "6"], [".", "6", ".", ".", ".", ".", "2", "8", "."], [".", ".", ".", "4", "1", "9", ".", ".", "5"], [".", ".", ".", ".", "8", ".", ".", "7", "9"] ] result = solve.isValidSudoku(board) print(result)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/03/10 # @Author : yuetao # @Site : # @File : 冒泡排序.py # @Desc : """ 每一趟选择一个最大值 """ class Solution(object): def BubbleSort(self, nums): length = len(nums) for i in range(length-1): #遍历的次数 for j in range(length - i - 1): #进行比较循环,最大的移动到后面 if nums[j] > nums[j + 1]: temp = nums[j+1] nums[j+1] = nums[j] nums[j] = temp return nums if __name__ == '__main__': solve = Solution() nums = [421, 240, 115, 532, 305, 430, 124] result = solve.BubbleSort(nums) print(result)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020-12-15 23:08 # @Author : Letao # @Site : # @File : LeetCode738_单调递增的数字.py # @Software: PyCharm # @desc : """ 单调栈,遇小变9,前一位-1 """ class Solution(object): def monotoneIncreasingDigits(self, N): """ :type N: int :rtype: int """ if N == 0: return 0 if N < 10: return N-1 stack = [] while N: temp = N % 10 N = int(N/10) if not stack or stack[len(stack)-1] >= temp: stack.append(temp) else: stack.pop() stack.append(9) stack.append(temp-1) res = 0 flag = False while stack: if stack[len(stack) - 1] == 9: flag = True if flag: res = res * 10 + 9 else: res = res*10 + stack[len(stack)-1] stack.pop() return res if __name__ == "__main__": solve = Solution() N = 332 result = solve.monotoneIncreasingDigits(N) print(result)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/01/25 # @Author : yuetao # @Site : # @File : 队列的最大值.py # @Desc : import collections import heapq class MaxQueue(object): def __init__(self): self.value = collections.deque() self.heap = [] def max_value(self): """ :rtype: int """ if not self.value and not self.heap: return -1 my_heap = [] for i in self.heap: heapq.heappush(my_heap, i) return -heapq.nsmallest(1, my_heap)[0] def push_back(self, value): """ :type value: int :rtype: None """ self.value.append(value) self.heap.append(-value) def pop_front(self): """ :rtype: int """ if not self.value: return -1 self.heap.pop(0) return self.value.popleft() if __name__ == '__main__': solve = MaxQueue() solve.push_back(1) solve.push_back(2) print(solve.heap) print(solve.max_value()) solve.pop_front() print(solve.max_value())
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/8/10 0010 20:56 # @Author : Letao # @Site : # @File : LeetCode1123.py # @Software: PyCharm # @desc :最深叶节点的最近公共祖先 class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): max_dept = 0 res = [] def lcaDeepestLeaves(self, root): """ :type root: TreeNode :rtype: TreeNode """ if not root: return self.dfs(root, 0) return self.res def dfs(self, node, dept): if not node: return 0 dept += 1 left = self.dfs(node.left, dept) right = self.dfs(node.right, dept) if left == right and dept >= self.max_dept: self.res.append(node) self.max_dept = dept return max(left, right) if __name__ == "__main__": solve = Solution() a = TreeNode(1) b = TreeNode(2) c = TreeNode(3) d = TreeNode(4) e = TreeNode(5) a.left = b a.right = c b.left = d b.right = e result = solve.lcaDeepestLeaves(a) print(result)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/03/27 # @Author : yuetao # @Site : # @File : LeetCode61_旋转链表.py # @Desc : class ListNode(object): def __init__(self, val=0, next=None): self.val = val self.next = next class Solution(object): def rotateRight(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ new_head = ListNode() new_head.next = head p = head count = 0 while p: count += 1 p = p.next if k%count == 0: return head remove_num = count - (k % count) q = head while remove_num > 1: remove_num -= 1 q = q.next new_head.next = q.next q.next = None m = new_head.next while m: if not m.next: m.next = head break m = m.next return new_head.next if __name__ == '__main__': solve = Solution() a = ListNode(1) b = ListNode(2) c = ListNode(3) d = ListNode(4) e = ListNode(5) a.next = b b.next = c c.next = d d.next = e k = 6 result = solve.rotateRight(a, k) while result: print(result.val) result = result.next
""" 递归找出所有 """ import queue from collections import defaultdict,deque class Solution(object): def countSubTrees(self, n, edges, labels): """ :type n: int :type edges: List[List[int]] :type labels: str :rtype: List[int] """ """ 以 0 点为根,构造多叉树,层次遍历 """ points = defaultdict(list) flag = [False]*n result = [1]*n q = deque() q.append(0) while q: val = q.popleft() flag[val] = True for edge in edges: if edge[0] == val and not flag[edge[1]]: points[val].append(edge[1]) q.append(edge[1]) elif edge[1] == val and not flag[edge[0]]: points[val].append(edge[0]) q.append(edge[0]) else: continue print(points) tree_set = defaultdict(set) # for i in range(0, n): # tree_set[i] # points[i] for point in points: index = point self.get_all_point(index, point, points, tree_set, labels) print(tree_set) for tree in tree_set: result[tree] = result[tree] + len(tree_set[tree]) return result def get_all_point(self, index, point, points, tree_set, labels): if point not in points: return None else: for val in points[point]: if labels[val] == labels[index]: tree_set[index].add(val) self.get_all_point(index, val, points, tree_set, labels) if __name__ == "__main__": solve = Solution() n = 4 edges = [[0,1],[1,2],[0,3]] labels = "bbbb" result = solve.countSubTrees(n, edges, labels) print(result)