{"doc_id": "001adc3959f7ae40e782e44f9ef8dbc4", "text": "\"\"\"\r\nGiven an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.\r\n\r\n\r\n\r\nExample 1:\r\n\r\nInput: nums = [1,2,3,1]\r\nOutput: true\r\nExample 2:\r\n\r\nInput: nums = [1,2,3,4]\r\nOutput: false\r\nExample 3:\r\n\r\nInput: nums = [1,1,1,3,3,4,3,2,4,2]\r\nOutput: true\r\n\"\"\"\r\n\r\nfrom collections import defaultdict\r\nfrom typing import List\r\n\r\n\r\nclass Solution:\r\n def contains_duplicate1(self, nums: List[int]) -> bool:\r\n \"\"\"\r\n n(log(n))\r\n Using sort with one loop\r\n :param nums:\r\n :return:\r\n \"\"\"\r\n nums.sort() # n(log(n))\r\n for i in range(1, len(nums)):\r\n if nums[i] == nums[i - 1]:\r\n return True\r\n return False\r\n\r\n def contains_duplicate2(self, nums: List[int]) -> bool:\r\n \"\"\"\r\n O(n), space = O(n)\r\n Using sort with one loop\r\n :param nums:\r\n :return:\r\n \"\"\"\r\n o = set(nums) # n(log(n))\r\n if len(nums) != len(s):\r\n return True\r\n return False\r\n\r\n def containsDuplicate(self, nums: List[int]) -> bool:\r\n \"\"\"\r\n O(n), space = O(n)\r\n Optomize solutions with hash map\r\n :param nums:\r\n :return:\r\n \"\"\"\r\n m = defaultdict(int)\r\n\r\n for num in nums:\r\n if m[num]:\r\n return True\r\n m[num] += 1\r\n return False\r\n\r\n\r\nnum1 = [2, 11, 11, 7, 15]\r\n# num1 = [2, 11, 7, 15]\r\ns = Solution()\r\nanswer = s.contains_duplicate1(num1)\r\nprint(answer)\r\nanswer1 = s.contains_duplicate1(num1)\r\nprint(\"With using set--------------\")\r\nprint(answer1)\r\nanswer2 = s.containsDuplicate(num1)\r\nprint(\"WITH Optimize solutions----------------\")\r\nprint(answer2)\r\n"}
{"doc_id": "009eddacb8eb6389dcfae7efee12823a", "text": "\n# (1)Vers\u00e3o com o for:\n\nlista = [100, 50, 20, 10, 5, 2, 1]\nvalor = int(input('Insira o valor que desaja sacar R$ '))\nfor n in range(len(lista)):\n if valor >= lista[n]:\n nota = valor // lista[n]\n print(f'\\033[31mTotal de {nota} notas de R$ {lista[n]}')\n valor = valor % lista[n]\nprint('\\n\\033[34mVolte sempre ao Banco do Cev! Tenha um bom dia!')\n\n# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n\n# (2) Vers\u00e3o com o while:\n\nlista = [100, 50, 20, 10, 5, 2, 1]\nvalor = int(input('Insira o valor que desaja sacar R$ '))\ncont = 0\nwhile True:\n if valor >= lista[cont]:\n nota = valor // lista[cont]\n print(f'Total de {nota} notas de R$ {lista[cont]}')\n valor = valor % lista[cont]\n cont += 1\n if valor == 0:\n break\nprint('\\nVolte sempre ao Banco do Cev! Tenha um bom dia!')"}
{"doc_id": "00a47bede9474f1487aad668a829dfb1", "text": "\"\"\"\nFile: sierpinski.py\nName: Allen Lee\n---------------------------\nThis file recursively prints the Sierpinski triangle on GWindow.\nThe Sierpinski triangle is a fractal described in 1915 by Waclaw Sierpinski.\nIt is a self similar structure that occurs at different levels of iterations.\n\"\"\"\n\nfrom campy.graphics.gwindow import GWindow\nfrom campy.graphics.gobjects import GLine\nfrom campy.gui.events.timer import pause\n\n# Constants\nORDER = 6 # Controls the order of Sierpinski Triangle\nLENGTH = 600 # The length of order 1 Sierpinski Triangle\nUPPER_LEFT_X = 150\t\t # The upper left x coordinate of order 1 Sierpinski Triangle\nUPPER_LEFT_Y = 100 # The upper left y coordinate of order 1 Sierpinski Triangle\nWINDOW_WIDTH = 950 # The width of the GWindow\nWINDOW_HEIGHT = 700 # The height of the GWindow\n\n# Global Variable\nwindow = GWindow(width=WINDOW_WIDTH, height=WINDOW_HEIGHT) # The canvas to draw Sierpinski Triangle\n\n\ndef main():\n\t\"\"\"\n\tThis program use a recursive function to draw the Sierpinski triangle with any order.\n\t\"\"\"\n\tsierpinski_triangle(ORDER, LENGTH, UPPER_LEFT_X, UPPER_LEFT_Y)\n\n\ndef sierpinski_triangle(order, length, upper_left_x, upper_left_y):\n\t\"\"\"\n\t:param order: (int) the order of Sierpinski Triangle\n\t:param length: (int) The length of Sierpinski Triangle with the order\n\t:param upper_left_x: (int) The upper left x coordinate of Sierpinski Triangle with the order\n\t:param upper_left_y: (int) The upper left y coordinate of Sierpinski Triangle with the order\n\t:return: The function does not return any value.\n\t\"\"\"\n\tif order == 0:\n\t\tpass\n\telse:\n\t\t# Draw order 1 Sierpinski triangle\n\t\ttop_side = GLine(upper_left_x, upper_left_y, upper_left_x + length, upper_left_y)\n\t\tleft_leg = GLine(upper_left_x, upper_left_y, upper_left_x + length/2, upper_left_y+length*0.866)\n\t\tright_leg = GLine(upper_left_x + length/2, upper_left_y + length*0.866, upper_left_x + length, upper_left_y)\n\t\twindow.add(top_side)\n\t\twindow.add(left_leg)\n\t\twindow.add(right_leg)\n\n\t\t# Upper left\n\t\tsierpinski_triangle(order-1, length/2, upper_left_x, upper_left_y)\n\t\t# Upper right\n\t\tsierpinski_triangle(order-1, length/2, upper_left_x+length/2, upper_left_y)\n\t\t# bottom\n\t\tsierpinski_triangle(order-1, length/2, upper_left_x+length/4, upper_left_y+(length*0.866)/2)\n\n\nif __name__ == '__main__':\n\tmain()\n"}
{"doc_id": "00aa5ab49281abb85591c4ac97db5fc1", "text": "\n# ### Problem 1:\n# Create two variables. One should equal \u201cMy name is: \u201c and the other should equal your actual name.\n# Print the two variables in one print message.\n\nstringVar1 = (\"My name is:\")\nstringVar2 = (\"Hamida\")\nprint(stringVar1 + stringVar2)\n\n\n# ### Problem 2:\n# Ask the user to enter the extra credit they earned. If they entered less than 5 print \u201cThat\u2019s not enough extra credit.\u201d\n# If they entered more than 20 print \u201cThat\u2019s too much extra credit\u201d.\n#\n\nextraCredit= int(input(\"Enter the extra credit:\"))\nif(extraCredit <5):\n print(\"That\u2019s not enough extra credit.\")\nelif(extraCredit>20):\n print(\"That\u2019s too much extra credit.\")\n\n# ### Problem 3:\n# Ask a user to enter a password. Enter a password. Ask user to reenter password. Check to see if they are correct.\n#\nusrPassWord= input(\"Enter a password here: \")\ncheckPassword=input(\"What is the password:\")\nif (usrPassWord == checkPassword):\n print(\"You got it\")\nelse :\n print(\"Wrong Password\")\n\n\n# ### Problem 4:\n# Ask for two card numbers. If it equals 21 print BLACKJACK!, if it\u2019s greater than 21 print BUST!,\n# if it\u2019s less than 21 print \u201cThe total is [THE TOTAL]\u201d\ncard1=int(input(\"Enter your first card number:\"))\ncard2=int(input(\"Enter your second card number\"))\nsum= card1 +card2\nif (sum==21):\n print(\"BLACKJACK!\")\nelif (sum>21):\n print(\"BUST!\")\nelse :\n print (\"The total is \" + str(sum))"}
{"doc_id": "00ccbcc1d7f71457d1ea919db324a98a", "text": "#!/usr/bin/python3\n\nwhile True :\n password = input(\"Make up a secure password: \")\n print(\"You entered: \", password)\n\n # initialize\n has_capital = False\n has_digit = False\n\n # check length\n gt_6 = len(password) >= 6\n if gt_6 is True :\n print(\"Password length check passed\")\n\n # check alphanum exist\n for ch in password :\n if ch in \"0123456789\" :\n has_digit = True\n if ch in \"ABCDEFGHIJKLMNOPQRSTUVWYZ\" :\n has_capital = True\n if has_digit is True :\n print(\"Password number check passed\")\n if has_capital is True :\n print(\"Password capital check passed\")\n\n # tell the user they failed to meet requirements\n if not gt_6 :\n print(\"Password length should be greater than or equal to 6 characters\")\n\n if not has_capital :\n print(\"Password must have at least one capital letter\")\n\n if not has_digit :\n print(\"Password must have at least one number\")\n\n # conditions to ask for a new password\n if not gt_6 or not has_capital or not has_digit:\n continue\n break\nprint(\"Great password!\")\n"}
{"doc_id": "010e7a4cde877aea97fc583534355fc6", "text": "\"\"\"\nNow write a program that calculates the minimum fixed monthly payment needed in order pay off a credit card balance\nwithin 12 months. By a fixed monthly payment, we mean a single number which does not change each month,\nbut instead is a constant amount that will be paid each month.\n\nIn this problem, we will not be dealing with a minimum monthly payment rate.\nThe following variables contain values as described below:\n balance - the outstanding balance on the credit card\n annualInterestRate - annual interest rate as a decimal\n\nThe program should print out one line: the lowest monthly payment that will pay off all debt in under 1 year,\nfor example:\nLowest Payment: 180\n\nAssume that the interest is compounded monthly according to the balance at the end of the month\n(after the payment for that month is made).\n\n> The monthly payment must be a multiple of $10 and is the same for all months.\n\nTest Case 1:\n balance = 3329\n annualInterestRate = 0.2\n\n Result Your Code Should Generate:\n -------------------\n Lowest Payment: 310\n\nTest Case 2:\n balance = 4773\n annualInterestRate = 0.2\n\n Result Your Code Should Generate:\n -------------------\n Lowest Payment: 440\n\"\"\"\n\nbalance = 4773\nannualInterestRate = 0.2\n\n\n# NB: this asks for a brute force approach since using multiple of 10 (next problem is with bisection)\n# so no need to b\n\ndef final_balance(balance, lowest_payment, annualInterestRate):\n for i in range(1, 13):\n outstanding = balance - lowest_payment\n balance = outstanding * (1. + annualInterestRate / 12.) # outstanding balance + interest due\n return balance\n\n\nlowest_payment = max(10, int((balance / 12 - 5) // 10) * 10) # lowest multiple of 10 closer to balance/12 (round down)\nwhile final_balance(balance, lowest_payment, annualInterestRate) > 0:\n lowest_payment += 10\n\nprint(\"Lowest Payment: {}\".format(lowest_payment))\n"}
{"doc_id": "01aba0c9620023521c82de294a49227a", "text": "\"\"\"\nAuthor Samuel Souik\n\nLicense MIT.\n\nremove_all_at.py\n\"\"\"\n\n\ndef remove_all_at(seq, remove_indices):\n \"\"\"\n Description\n ----------\n Remove values at specified indices from the sequence.\n\n Parameters\n ----------\n seq : (list or tuple) - sequence to remove values from\\n\n remove_indices : (list or tuple or set) - sequence of indices to remove\n\n Returns\n ----------\n generator - a generator containing all values not removed from the sequence\n\n Example\n ----------\n >>> tup = ('a', 'b', 'c', 'd', 'e', 'f', 'g')\n >>> remove_all_at(tup, [0, 3, 1, 5])\n >>> ['c', 'e', 'g'] Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).” Given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4] Example 1: Example 2: Note: \u7ed9\u5b9a\u4e00\u4e2a\u4e8c\u53c9\u6811, \u627e\u5230\u8be5\u6811\u4e2d\u4e24\u4e2a\u6307\u5b9a\u8282\u70b9\u7684\u6700\u8fd1\u516c\u5171\u7956\u5148\u3002 \u767e\u5ea6\u767e\u79d1\u4e2d\u6700\u8fd1\u516c\u5171\u7956\u5148\u7684\u5b9a\u4e49\u4e3a\uff1a“\u5bf9\u4e8e\u6709\u6839\u6811 T \u7684\u4e24\u4e2a\u7ed3\u70b9 p\u3001q\uff0c\u6700\u8fd1\u516c\u5171\u7956\u5148\u8868\u793a\u4e3a\u4e00\u4e2a\u7ed3\u70b9 x\uff0c\u6ee1\u8db3 x \u662f p\u3001q \u7684\u7956\u5148\u4e14 x \u7684\u6df1\u5ea6\u5c3d\u53ef\u80fd\u5927\uff08\u4e00\u4e2a\u8282\u70b9\u4e5f\u53ef\u4ee5\u662f\u5b83\u81ea\u5df1\u7684\u7956\u5148\uff09\u3002” \u4f8b\u5982\uff0c\u7ed9\u5b9a\u5982\u4e0b\u4e8c\u53c9\u6811: root = [3,5,1,6,2,0,8,null,null,7,4] \u793a\u4f8b 1: \u793a\u4f8b 2: \u8bf4\u660e: \u7ed9\u5b9a\u4e00\u4e2a\u4e8c\u53c9\u6811, \u627e\u5230\u8be5\u6811\u4e2d\u4e24\u4e2a\u6307\u5b9a\u8282\u70b9\u7684\u6700\u8fd1\u516c\u5171\u7956\u5148\u3002 \u767e\u5ea6\u767e\u79d1\u4e2d\u6700\u8fd1\u516c\u5171\u7956\u5148\u7684\u5b9a\u4e49\u4e3a\uff1a“\u5bf9\u4e8e\u6709\u6839\u6811 T \u7684\u4e24\u4e2a\u7ed3\u70b9 p\u3001q\uff0c\u6700\u8fd1\u516c\u5171\u7956\u5148\u8868\u793a\u4e3a\u4e00\u4e2a\u7ed3\u70b9 x\uff0c\u6ee1\u8db3 x \u662f p\u3001q \u7684\u7956\u5148\u4e14 x \u7684\u6df1\u5ea6\u5c3d\u53ef\u80fd\u5927\uff08\u4e00\u4e2a\u8282\u70b9\u4e5f\u53ef\u4ee5\u662f\u5b83\u81ea\u5df1\u7684\u7956\u5148\uff09\u3002” \u4f8b\u5982\uff0c\u7ed9\u5b9a\u5982\u4e0b\u4e8c\u53c9\u6811: root = [3,5,1,6,2,0,8,null,null,7,4] \u793a\u4f8b 1: \u793a\u4f8b 2: \u8bf4\u660e: \nInitially on a notepad only one character 'A' is present. You can perform two operations on this notepad for each step: \n\n _______3______\n / \\\n ___5__ ___1__\n / \\ / \\\n 6 _2 0 8\n / \\\n 7 4\n
\n\n\nInput: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1\nOutput: 3\nExplanation: The LCA of of nodes
\n\n5 and 1 is 3.\n\nInput: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4\nOutput: 5\nExplanation: The LCA of nodes
\n\n5 and 4 is 5, since a node can be a descendant of itself\n according to the LCA definition.\n\t
\n _______3______\n / \\\n ___5__ ___1__\n / \\ / \\\n 6 _2 0 8\n / \\\n 7 4\n
\n\n\u8f93\u5165: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1\n\u8f93\u51fa: 3\n\u89e3\u91ca: \u8282\u70b9
\n\n5 \u548c\u8282\u70b9 1 \u7684\u6700\u8fd1\u516c\u5171\u7956\u5148\u662f\u8282\u70b9 3\u3002\n\u8f93\u5165: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4\n\u8f93\u51fa: 5\n\u89e3\u91ca: \u8282\u70b9
\n\n5 \u548c\u8282\u70b9 4 \u7684\u6700\u8fd1\u516c\u5171\u7956\u5148\u662f\u8282\u70b9 5\u3002\u56e0\u4e3a\u6839\u636e\u5b9a\u4e49\u6700\u8fd1\u516c\u5171\u7956\u5148\u8282\u70b9\u53ef\u4ee5\u4e3a\u8282\u70b9\u672c\u8eab\u3002\n\n\t
\n _______3______\n / \\\n ___5__ ___1__\n / \\ / \\\n 6 _2 0 8\n / \\\n 7 4\n
\n\n\u8f93\u5165: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1\n\u8f93\u51fa: 3\n\u89e3\u91ca: \u8282\u70b9
\n\n5 \u548c\u8282\u70b9 1 \u7684\u6700\u8fd1\u516c\u5171\u7956\u5148\u662f\u8282\u70b9 3\u3002\n\u8f93\u5165: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4\n\u8f93\u51fa: 5\n\u89e3\u91ca: \u8282\u70b9
\n\n5 \u548c\u8282\u70b9 4 \u7684\u6700\u8fd1\u516c\u5171\u7956\u5148\u662f\u8282\u70b9 5\u3002\u56e0\u4e3a\u6839\u636e\u5b9a\u4e49\u6700\u8fd1\u516c\u5171\u7956\u5148\u8282\u70b9\u53ef\u4ee5\u4e3a\u8282\u70b9\u672c\u8eab\u3002\n\n\t
\n\"\"\"\n\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def lowestCommonAncestor(self, root, p, q):\n \"\"\"\n :type root: TreeNode\n :type p: TreeNode\n :type q: TreeNode\n :rtype: TreeNode\n \"\"\"\n "}
{"doc_id": "049c5555c97f370ccc41f73e5b7759fd", "text": "import string\nimport random\n\n\nalphabets = list(string.ascii_letters)\ndigits = list(string.digits)\nspecial_characters = list(\"!@#$%^&*()\")\ncharacters = list(string.ascii_letters + string.digits + \"!@#$%^&*()\")\n\ndef generate_random_password():\n\tlength = int(input(\"Enter The Length Of Password: \"))\n\n\talphabets_count = int(input(\"How Many Alphabets You Want : \"))\n\tdigits_count = int(input(\"How Many Digits You Want : \"))\n\tspecial_characters_count = int(input(\"How Many Special Character You Want: \"))\n\n\tcharacters_count = alphabets_count + digits_count + special_characters_count\n\n\t\n\tif characters_count > length:\n\t\tprint(\"Characters total count is greater than the password length\")\n\t\treturn\n\n\n\tpassword = []\n\t\n\tfor i in range(alphabets_count):\n\t\tpassword.append(random.choice(alphabets))\n\n\n\tfor i in range(digits_count):\n\t\tpassword.append(random.choice(digits))\n\n\n\tfor i in range(special_characters_count):\n\t\tpassword.append(random.choice(special_characters))\n\n\n\t\n\tif characters_count < length:\n\t\trandom.shuffle(characters)\n\t\tfor i in range(length - characters_count):\n\t\t\tpassword.append(random.choice(characters))\n\n\n\t\n\trandom.shuffle(password)\n\n\t\n\tprint(\"\".join(password))\n\n\n\ngenerate_random_password()"}
{"doc_id": "04b19312123175470c2600ab1d33d4dc", "text": "# palindrome\n\"\"\"\nwrite a function that check if a string is a plindrome\nif it is then return true and if it is not return false\n\nclarifying question\n------------------\nshould we deal with case difference?\n- no normalise the case of the input\n\n\n\"\"\"\n\n# function is_palindrome\ndef is_palindrome(s):\n \"\"\"\n is_palindrome\n -------------\n Takes in a string as an input\n Outputs a boolean of True or False\n Depending on the outcome of the question\n - is this strong a plaindrome\n \"\"\"\n\n # normalise our string to have all lower case letters\n lower_s = s.lower()\n # make lower_s in to a list\n list_lower_s = list(lower_s)\n # reveres the lower_s using reversed() as rev_lower_s\n rev_lower_s = list(reversed(list_lower_s))\n\n # compare rev_lower_s with lower_s\n if rev_lower_s == list_lower_s:\n # return True\n return True\n # otherwise\n else:\n # return False\n return False\n\n\n\n# is_palindrome with input of \"Mom\"\nprint(is_palindrome(\"Mom\")) # True\n\nprint(is_palindrome(\"dAd\")) # True\n\n# is_palindrome with input of \"Add\"\nprint(is_palindrome(\"Add\")) # False\n\nprint(is_palindrome(\"Mom is A non Palindrome!\")) # False"}
{"doc_id": "04e3e4cc416ae53262f792a8db383a56", "text": "\"\"\"\n\n
\nCopy All: You can copy all the characters present on the notepad (partial copy is not allowed).Paste: You can paste the characters which are copied last time.
\nGiven a number n. You have to get exactly n 'A' on the notepad by performing the minimum number of steps permitted. Output the minimum number of steps to get n 'A'. \n
Example 1:
\n
\nInput: 3\nOutput: 3\nExplanation:\nIntitally, we have one character 'A'.\nIn step 1, we use Copy All operation.\nIn step 2, we use Paste operation to get 'AA'.\nIn step 3, we use Paste operation to get 'AAA'.\n\n\n\n\n
Note:
\n
n will be in the range [1, 1000].\u6700\u521d\u5728\u4e00\u4e2a\u8bb0\u4e8b\u672c\u4e0a\u53ea\u6709\u4e00\u4e2a\u5b57\u7b26 'A'\u3002\u4f60\u6bcf\u6b21\u53ef\u4ee5\u5bf9\u8fd9\u4e2a\u8bb0\u4e8b\u672c\u8fdb\u884c\u4e24\u79cd\u64cd\u4f5c\uff1a
\n\nCopy All (\u590d\u5236\u5168\u90e8) : \u4f60\u53ef\u4ee5\u590d\u5236\u8fd9\u4e2a\u8bb0\u4e8b\u672c\u4e2d\u7684\u6240\u6709\u5b57\u7b26(\u90e8\u5206\u7684\u590d\u5236\u662f\u4e0d\u5141\u8bb8\u7684)\u3002Paste (\u7c98\u8d34) : \u4f60\u53ef\u4ee5\u7c98\u8d34\u4f60\u4e0a\u4e00\u6b21\u590d\u5236\u7684\u5b57\u7b26\u3002\u7ed9\u5b9a\u4e00\u4e2a\u6570\u5b57 n \u3002\u4f60\u9700\u8981\u4f7f\u7528\u6700\u5c11\u7684\u64cd\u4f5c\u6b21\u6570\uff0c\u5728\u8bb0\u4e8b\u672c\u4e2d\u6253\u5370\u51fa\u6070\u597d n \u4e2a 'A'\u3002\u8f93\u51fa\u80fd\u591f\u6253\u5370\u51fa n \u4e2a 'A' \u7684\u6700\u5c11\u64cd\u4f5c\u6b21\u6570\u3002
\u793a\u4f8b 1:
\n\n\n\u8f93\u5165: 3\n\u8f93\u51fa: 3\n\u89e3\u91ca:\n\u6700\u521d, \u6211\u4eec\u53ea\u6709\u4e00\u4e2a\u5b57\u7b26 'A'\u3002\n\u7b2c 1 \u6b65, \u6211\u4eec\u4f7f\u7528 Copy All \u64cd\u4f5c\u3002\n\u7b2c 2 \u6b65, \u6211\u4eec\u4f7f\u7528 Paste \u64cd\u4f5c\u6765\u83b7\u5f97 'AA'\u3002\n\u7b2c 3 \u6b65, \u6211\u4eec\u4f7f\u7528 Paste \u64cd\u4f5c\u6765\u83b7\u5f97 'AAA'\u3002\n\n\n
\u8bf4\u660e:
\n\nn \u7684\u53d6\u503c\u8303\u56f4\u662f [1, 1000] \u3002\u6700\u521d\u5728\u4e00\u4e2a\u8bb0\u4e8b\u672c\u4e0a\u53ea\u6709\u4e00\u4e2a\u5b57\u7b26 'A'\u3002\u4f60\u6bcf\u6b21\u53ef\u4ee5\u5bf9\u8fd9\u4e2a\u8bb0\u4e8b\u672c\u8fdb\u884c\u4e24\u79cd\u64cd\u4f5c\uff1a
\n\nCopy All (\u590d\u5236\u5168\u90e8) : \u4f60\u53ef\u4ee5\u590d\u5236\u8fd9\u4e2a\u8bb0\u4e8b\u672c\u4e2d\u7684\u6240\u6709\u5b57\u7b26(\u90e8\u5206\u7684\u590d\u5236\u662f\u4e0d\u5141\u8bb8\u7684)\u3002Paste (\u7c98\u8d34) : \u4f60\u53ef\u4ee5\u7c98\u8d34\u4f60\u4e0a\u4e00\u6b21\u590d\u5236\u7684\u5b57\u7b26\u3002\u7ed9\u5b9a\u4e00\u4e2a\u6570\u5b57 n \u3002\u4f60\u9700\u8981\u4f7f\u7528\u6700\u5c11\u7684\u64cd\u4f5c\u6b21\u6570\uff0c\u5728\u8bb0\u4e8b\u672c\u4e2d\u6253\u5370\u51fa\u6070\u597d n \u4e2a 'A'\u3002\u8f93\u51fa\u80fd\u591f\u6253\u5370\u51fa n \u4e2a 'A' \u7684\u6700\u5c11\u64cd\u4f5c\u6b21\u6570\u3002
\u793a\u4f8b 1:
\n\n\n\u8f93\u5165: 3\n\u8f93\u51fa: 3\n\u89e3\u91ca:\n\u6700\u521d, \u6211\u4eec\u53ea\u6709\u4e00\u4e2a\u5b57\u7b26 'A'\u3002\n\u7b2c 1 \u6b65, \u6211\u4eec\u4f7f\u7528 Copy All \u64cd\u4f5c\u3002\n\u7b2c 2 \u6b65, \u6211\u4eec\u4f7f\u7528 Paste \u64cd\u4f5c\u6765\u83b7\u5f97 'AA'\u3002\n\u7b2c 3 \u6b65, \u6211\u4eec\u4f7f\u7528 Paste \u64cd\u4f5c\u6765\u83b7\u5f97 'AAA'\u3002\n\n\n
\u8bf4\u660e:
\n\nn \u7684\u53d6\u503c\u8303\u56f4\u662f [1, 1000] \u3002\nThere is a room with n lights which are turned on initially and 4 buttons on the wall. After performing exactly m unknown operations towards buttons, you need to return how many different kinds of status of the n lights could be.\n
\nSuppose n lights are labeled as number [1, 2, 3 ..., n], function of these 4 buttons are given below:\n\n
Example 1:
\n
\nInput: n = 1, m = 1.\nOutput: 2\nExplanation: Status can be: [on], [off]\n\n\n\n\n
Example 2:
\n
\nInput: n = 2, m = 1.\nOutput: 3\nExplanation: Status can be: [on, off], [off, on], [off, off]\n\n\n\n\n
Example 3:
\n
\nInput: n = 3, m = 1.\nOutput: 4\nExplanation: Status can be: [off, on, off], [on, off, on], [off, off, off], [off, on, on].\n\n\n\n
Note:\nn and m both fit in range [0, 1000].\n
\u73b0\u6709\u4e00\u4e2a\u623f\u95f4\uff0c\u5899\u4e0a\u6302\u6709 n \u53ea\u5df2\u7ecf\u6253\u5f00\u7684\u706f\u6ce1\u548c 4 \u4e2a\u6309\u94ae\u3002\u5728\u8fdb\u884c\u4e86 m \u6b21\u672a\u77e5\u64cd\u4f5c\u540e\uff0c\u4f60\u9700\u8981\u8fd4\u56de\u8fd9 n \u53ea\u706f\u6ce1\u53ef\u80fd\u6709\u591a\u5c11\u79cd\u4e0d\u540c\u7684\u72b6\u6001\u3002
\u5047\u8bbe\u8fd9 n \u53ea\u706f\u6ce1\u88ab\u7f16\u53f7\u4e3a [1, 2, 3 ..., n]\uff0c\u8fd9 4 \u4e2a\u6309\u94ae\u7684\u529f\u80fd\u5982\u4e0b\uff1a
3k+1 \u7684\u706f\u6ce1\u7684\u72b6\u6001\u53cd\u8f6c\uff08k = 0, 1, 2, ...)\u793a\u4f8b 1:
\n\n\u8f93\u5165: n = 1, m = 1.\n\u8f93\u51fa: 2\n\u8bf4\u660e: \u72b6\u6001\u4e3a: [\u5f00], [\u5173]\n\n\n
\u793a\u4f8b 2:
\n\n\u8f93\u5165: n = 2, m = 1.\n\u8f93\u51fa: 3\n\u8bf4\u660e: \u72b6\u6001\u4e3a: [\u5f00, \u5173], [\u5173, \u5f00], [\u5173, \u5173]\n\n\n
\u793a\u4f8b 3:
\n\n\u8f93\u5165: n = 3, m = 1.\n\u8f93\u51fa: 4\n\u8bf4\u660e: \u72b6\u6001\u4e3a: [\u5173, \u5f00, \u5173], [\u5f00, \u5173, \u5f00], [\u5173, \u5173, \u5173], [\u5173, \u5f00, \u5f00].\n\n\n
\u6ce8\u610f\uff1a n \u548c m \u90fd\u5c5e\u4e8e [0, 1000].
\u73b0\u6709\u4e00\u4e2a\u623f\u95f4\uff0c\u5899\u4e0a\u6302\u6709 n \u53ea\u5df2\u7ecf\u6253\u5f00\u7684\u706f\u6ce1\u548c 4 \u4e2a\u6309\u94ae\u3002\u5728\u8fdb\u884c\u4e86 m \u6b21\u672a\u77e5\u64cd\u4f5c\u540e\uff0c\u4f60\u9700\u8981\u8fd4\u56de\u8fd9 n \u53ea\u706f\u6ce1\u53ef\u80fd\u6709\u591a\u5c11\u79cd\u4e0d\u540c\u7684\u72b6\u6001\u3002
\u5047\u8bbe\u8fd9 n \u53ea\u706f\u6ce1\u88ab\u7f16\u53f7\u4e3a [1, 2, 3 ..., n]\uff0c\u8fd9 4 \u4e2a\u6309\u94ae\u7684\u529f\u80fd\u5982\u4e0b\uff1a
3k+1 \u7684\u706f\u6ce1\u7684\u72b6\u6001\u53cd\u8f6c\uff08k = 0, 1, 2, ...)\u793a\u4f8b 1:
\n\n\u8f93\u5165: n = 1, m = 1.\n\u8f93\u51fa: 2\n\u8bf4\u660e: \u72b6\u6001\u4e3a: [\u5f00], [\u5173]\n\n\n
\u793a\u4f8b 2:
\n\n\u8f93\u5165: n = 2, m = 1.\n\u8f93\u51fa: 3\n\u8bf4\u660e: \u72b6\u6001\u4e3a: [\u5f00, \u5173], [\u5173, \u5f00], [\u5173, \u5173]\n\n\n
\u793a\u4f8b 3:
\n\n\u8f93\u5165: n = 3, m = 1.\n\u8f93\u51fa: 4\n\u8bf4\u660e: \u72b6\u6001\u4e3a: [\u5173, \u5f00, \u5173], [\u5f00, \u5173, \u5f00], [\u5173, \u5173, \u5173], [\u5173, \u5f00, \u5f00].\n\n\n
\u6ce8\u610f\uff1a n \u548c m \u90fd\u5c5e\u4e8e [0, 1000].
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.
\n\nNote:
\n\nExample 1:
\n\n\nInput:\ns = "\n\ncatsanddog"\nwordDict =["cat", "cats", "and", "sand", "dog"]\nOutput:\n[\n "cats and dog",\n "cat sand dog"\n]\n
Example 2:
\n\n\nInput:\ns = "pineapplepenapple"\nwordDict = ["apple", "pen", "applepen", "pine", "pineapple"]\nOutput:\n[\n "pine apple pen apple",\n "pineapple pen apple",\n "pine applepen apple"\n]\nExplanation: Note that you are allowed to reuse a dictionary word.\n\n\n
Example 3:
\n\n\nInput:\ns = "catsandog"\nwordDict = ["cats", "dog", "sand", "and", "cat"]\nOutput:\n[]\n
\u7ed9\u5b9a\u4e00\u4e2a\u975e\u7a7a\u5b57\u7b26\u4e32 s \u548c\u4e00\u4e2a\u5305\u542b\u975e\u7a7a\u5355\u8bcd\u5217\u8868\u7684\u5b57\u5178 wordDict\uff0c\u5728\u5b57\u7b26\u4e32\u4e2d\u589e\u52a0\u7a7a\u683c\u6765\u6784\u5efa\u4e00\u4e2a\u53e5\u5b50\uff0c\u4f7f\u5f97\u53e5\u5b50\u4e2d\u6240\u6709\u7684\u5355\u8bcd\u90fd\u5728\u8bcd\u5178\u4e2d\u3002\u8fd4\u56de\u6240\u6709\u8fd9\u4e9b\u53ef\u80fd\u7684\u53e5\u5b50\u3002
\n\n\u8bf4\u660e\uff1a
\n\n\u793a\u4f8b 1\uff1a
\n\n\u8f93\u5165:\ns = "\n\ncatsanddog"\nwordDict =["cat", "cats", "and", "sand", "dog"]\n\u8f93\u51fa:\n[\n "cats and dog",\n "cat sand dog"\n]\n
\u793a\u4f8b 2\uff1a
\n\n\u8f93\u5165:\ns = "pineapplepenapple"\nwordDict = ["apple", "pen", "applepen", "pine", "pineapple"]\n\u8f93\u51fa:\n[\n "pine apple pen apple",\n "pineapple pen apple",\n "pine applepen apple"\n]\n\u89e3\u91ca: \u6ce8\u610f\u4f60\u53ef\u4ee5\u91cd\u590d\u4f7f\u7528\u5b57\u5178\u4e2d\u7684\u5355\u8bcd\u3002\n\n\n
\u793a\u4f8b 3\uff1a
\n\n\u8f93\u5165:\ns = "catsandog"\nwordDict = ["cats", "dog", "sand", "and", "cat"]\n\u8f93\u51fa:\n[]\n\n
\u7ed9\u5b9a\u4e00\u4e2a\u975e\u7a7a\u5b57\u7b26\u4e32 s \u548c\u4e00\u4e2a\u5305\u542b\u975e\u7a7a\u5355\u8bcd\u5217\u8868\u7684\u5b57\u5178 wordDict\uff0c\u5728\u5b57\u7b26\u4e32\u4e2d\u589e\u52a0\u7a7a\u683c\u6765\u6784\u5efa\u4e00\u4e2a\u53e5\u5b50\uff0c\u4f7f\u5f97\u53e5\u5b50\u4e2d\u6240\u6709\u7684\u5355\u8bcd\u90fd\u5728\u8bcd\u5178\u4e2d\u3002\u8fd4\u56de\u6240\u6709\u8fd9\u4e9b\u53ef\u80fd\u7684\u53e5\u5b50\u3002
\n\n\u8bf4\u660e\uff1a
\n\n\u793a\u4f8b 1\uff1a
\n\n\u8f93\u5165:\ns = "\n\ncatsanddog"\nwordDict =["cat", "cats", "and", "sand", "dog"]\n\u8f93\u51fa:\n[\n "cats and dog",\n "cat sand dog"\n]\n
\u793a\u4f8b 2\uff1a
\n\n\u8f93\u5165:\ns = "pineapplepenapple"\nwordDict = ["apple", "pen", "applepen", "pine", "pineapple"]\n\u8f93\u51fa:\n[\n "pine apple pen apple",\n "pineapple pen apple",\n "pine applepen apple"\n]\n\u89e3\u91ca: \u6ce8\u610f\u4f60\u53ef\u4ee5\u91cd\u590d\u4f7f\u7528\u5b57\u5178\u4e2d\u7684\u5355\u8bcd\u3002\n\n\n
\u793a\u4f8b 3\uff1a
\n\n\u8f93\u5165:\ns = "catsandog"\nwordDict = ["cats", "dog", "sand", "and", "cat"]\n\u8f93\u51fa:\n[]\n\n\"\"\"\n\n\nclass Solution:\n def wordBreak(self, s, wordDict):\n \"\"\"\n :type s: str\n :type wordDict: List[str]\n :rtype: List[str]\n \"\"\"\n "} {"doc_id": "073253e9faba7a054e939ed6d3bc007a", "text": "\"\"\"\n@author: MatteoRaso\n\"\"\"\nfrom numpy import pi, sqrt\nfrom random import uniform\nfrom statistics import mean\n\n\ndef pi_estimator(iterations: int):\n \"\"\"\n An implementation of the Monte Carlo method used to find pi.\n 1. Draw a 2x2 square centred at (0,0).\n 2. Inscribe a circle within the square.\n 3. For each iteration, place a dot anywhere in the square.\n a. Record the number of dots within the circle.\n 4. After all the dots are placed, divide the dots in the circle by the total.\n 5. Multiply this value by 4 to get your estimate of pi.\n 6. Print the estimated and numpy value of pi\n \"\"\"\n # A local function to see if a dot lands in the circle.\n def in_circle(x: float, y: float) -> bool:\n distance_from_centre = sqrt((x ** 2) + (y ** 2))\n # Our circle has a radius of 1, so a distance\n # greater than 1 would land outside the circle.\n return distance_from_centre <= 1\n\n # The proportion of guesses that landed in the circle\n proportion = mean(\n int(in_circle(uniform(-1.0, 1.0), uniform(-1.0, 1.0)))\n for _ in range(iterations)\n )\n # The ratio of the area for circle to square is pi/4.\n pi_estimate = proportion * 4\n print(\"The estimated value of pi is \", pi_estimate)\n print(\"The numpy value of pi is \", pi)\n print(\"The total error is \", abs(pi - pi_estimate))\n\n\ndef area_under_line_estimator(\n iterations: int, min_value: float = 0.0, max_value: float = 1.0\n) -> float:\n \"\"\"\n An implementation of the Monte Carlo method to find area under\n y = x where x lies between min_value to max_value\n 1. Let x be a uniformly distributed random variable between min_value to max_value\n 2. Expected value of x = (integration of x from min_value to max_value) / (max_value - min_value)\n 3. Finding expected value of x:\n a. Repeatedly draw x from uniform distribution\n b. Expected value = average of those values\n 4. Actual value = (max_value^2 - min_value^2) / 2\n 5. Returns estimated value\n \"\"\"\n return mean(uniform(min_value, max_value) for _ in range(iterations)) * (\n max_value - min_value\n )\n\n\ndef area_under_line_estimator_check(\n iterations: int, min_value: float = 0.0, max_value: float = 1.0\n) -> None:\n \"\"\"\n Checks estimation error for area_under_line_estimator func\n 1. Calls \"area_under_line_estimator\" function\n 2. Compares with the expected value\n 3. Prints estimated, expected and error value\n \"\"\"\n\n estimated_value = area_under_line_estimator(iterations, min_value, max_value)\n expected_value = (max_value * max_value - min_value * min_value) / 2\n\n print(\"******************\")\n print(\n \"Estimating area under y=x where x varies from \", min_value, \" to \", max_value\n )\n print(\"Estimated value is \", estimated_value)\n print(\"Expected value is \", expected_value)\n print(\"Total error is \", abs(estimated_value - expected_value))\n print(\"******************\")\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n"} {"doc_id": "074c8fc1780b3ea2a2a5c043899ea721", "text": "import random\n\ndef smallLetter(num):\n char = \"\"\n for i in range(num):\n char += chr(random.choice(range(97, 123)))\n\n return char\n\ndef capitalLetter(num):\n char = \"\"\n for i in range(num):\n char += chr(random.choice(range(65, 91)))\n\n return char\n\ndef numbers(num):\n char = \"\"\n for i in range(num):\n char += str(random.choice(range(0, 10)))\n\n return char\n\ndef specialChar(num):\n char = \"\"\n for i in range(num):\n char += chr(random.choice(range(33, 44)))\n\n return char\n\n\nif __name__ == \"__main__\":\n small_letters = int(input(\"Enter the number of Small letters in your password: \"))\n capital_letters = int(input(\"Enter the number of Capital letters in your password: \"))\n nums = int(input(\"Enter the number of Number in your password: \"))\n special_characters = int(input(\"Enter the number of Special characters in your password: \"))\n \n password = f\"{smallLetter(small_letters)}{capitalLetter(capital_letters)}{numbers(nums)}{specialChar(special_characters)}\"\n \n updatedPass = ''.join(random.sample(password, len(password)))\n # print(password)\n print('\\n')\n print(f\"Your new secured password is: {updatedPass}\")"} {"doc_id": "07b7f5f5680ccc04d2a33923ab225e0e", "text": "# Entradas, salidas de datos, y casting\nprint(\"Hola me llamo xd dame tu nombre y tu dinero xd\")\nnombre = input()\nprint(f\"Me alegro de conocerte {nombre}\")\nprint(f\"Ahora por favor {nombre}, dame tu dinero\")\ndinero = int(input())\nprint(f\"Genial {nombre} que andas {dinero}$\")\nprint(f\"Pero te regalare mejor unos 40$ para que andes {(dinero + 40)}$ pinche pobre\")\nprint(\"============================================\")\n\nprint(\"Soy una calculadora\")\nprint(\"Dame 2 numeros \")\nnum1 = float(input())\nnum2 = float(input())\n# Operador de Suma\nresultado_suma = num1 + num2\n# Operador de Resta\nresultado_resta = num1 - num2\n# Operador de multiplicacion\nresultado_multiplicacion = num1 * num2\n# Operador de division\nresultado_division = num1 / num2\n# Operador\nresultado_exponente = num1 ** num2\n# Modulo\nresultado_modulo = num1 % num2\n# Division entera\nresultado_division_entera = num1 // num2\n# Raiz cuadrada\nresultado_raiz_cuadrada = num1 ** (1/2)\n\nprint(f\"Es resultado de la suma de 4 + 8 = {resultado_suma}\" )\nprint(f\"El resultado de la resta de 4 - 8 = {resultado_resta}\")\nprint(f\"El resultado de la multiplicacion de 4 * 8 = {resultado_multiplicacion}\")\nprint(f\"El resultado de la division de 4 / 8 = {resultado_division}\")\nprint(f\"El resultado de elevar 4 a la 8 es = {resultado_exponente}\")\nprint(f\"El resultado de el modulo es = {resultado_modulo}\")\nprint(f\"El resultado de la division entera es = {resultado_division_entera}\")\nprint(f\"El resultado de la raiz cuadrada es = {resultado_raiz_cuadrada}\")"} {"doc_id": "080fdc7c0314b635c6c41dfdbc4d0102", "text": "# Bank that manages a dictionary of Account objects\n\nfrom Account import *\n\nclass Bank():\n\n def __init__(self):\n self.accountsDict = {}\n self.nextAccountNumber = 0\n\n def createAccount(self, theName, theStartingAmount, thePassword):\n oAccount = Account(theName, theStartingAmount, thePassword)\n newAccountNumber = self.nextAccountNumber\n self.accountsDict[newAccountNumber] = oAccount\n # Increment to prepare for next account to be created\n self.nextAccountNumber = self.nextAccountNumber + 1\n return newAccountNumber\n\n def openAccount(self):\n print('*** Open Account ***')\n userName = input('What is the name for the new user account? ')\n userStartingAmount = input('What is the starting balance for this account? ')\n userStartingAmount = int(userStartingAmount)\n userPassword = input('What password would you want to use for this account? ')\n\n userAccountNumber = self.createAccount(userName, userStartingAmount, userPassword)\n print('Your new account number is:', userAccountNumber)\n print()\n\n def closeAccount(self):\n print('*** Close Account ***')\n userAccountNumber = input('What is your account number? ')\n userAccountNumber = int(userAccountNumber)\n userPassword = input('What is your password? ')\n oAccount = self.accountsDict[userAccountNumber]\n theBalance = oAccount.getBalance(userPassword)\n\n if theBalance is not None:\n print('You had', theBalance, 'in your account, which is being returned to you.')\n # Remove user's account from the dictioary of accounts\n del self.accountsDict[userAccountNumber]\n print('Your account is now closed.')\n\n def balance(self):\n print('*** Get Balance ***')\n userAccountNumber = input('Please enter your account number: ')\n userAccountNumber = int(userAccountNumber)\n userAccountPassword = input('Please enter the password: ')\n oAccount = self.accountsDict[userAccountNumber]\n theBalance = oAccount.getBalance(userAccountPassword)\n if theBalance is not None:\n print('Your balance is:', theBalance)\n\n def deposit(self):\n print('*** Deposit ***')\n accountNum = input('Please enter the account number: ')\n accountNum = int(accountNum)\n depositAmount = input('Please enter amount to deposit: ')\n depositAmount = int(depositAmount)\n userAccountPassword = input('Please enter the password: ')\n oAccount = self.accountsDict[accountNum] \n theBalance = oAccount.deposit(depositAmount, userAccountPassword)\n if theBalance is not None:\n print('Your new balance is:', theBalance)\n\n def show(self):\n print('*** Show ***')\n for userAccountNumber in self.accountsDict:\n oAccount = self.accountsDict[userAccountNumber]\n print(' Account number:', userAccountNumber)\n oAccount.show()\n\n def withdraw(self):\n print('*** Withdraw ***')\n userAccountNumber = input('Please enter your account number: ')\n userAccountNumber = int(userAccountNumber)\n userAmount = input('Please enter the amount to withdraw: ')\n userAmount = int(userAmount)\n userAccountPassword = input('Please enter the password: ')\n oAccount = self.accountsDict[userAccountNumber]\n theBalance = oAccount.withdraw(userAmount, userAccountPassword)\n if theBalance is not None:\n print('Withdrew:', userAmount)\n print('Your new balance is:', theBalance)\n\n def bankInfo(self):\n print('Hours: 9 to 5')\n print('Address: 123 Main Street, Anytown, USA')\n print('Phone: (650) 555-1212')\n print('We currently have', len(self.accountsDict), 'account(s) open.')\n"} {"doc_id": "0883cc30693ba433afb9710faa190864", "text": "#1. Start, get user's name\nuser_name = input(\"Please provide your name: \")\n\n#2. check if the name is Rowen (if true, ask for password else print \"Access denied\")\nif user_name == 'Rowen':\n #3. if the password is correct write 'welcome' else print 'incorrect'\n #lets assume the password is 123456\n password = input(\"Please provide your password: \")\n if password == 123456:\n print \"Welcome\"\n else:\n print \"Incorrect\"\nelse:\n print \"Access denied\""} {"doc_id": "0927395baaa6d444aa3bf8454214a2b2", "text": "from typing import List, Dict, Callable\n\n\nclass TreeNode:\n \"\"\" \u4e8c\u53c9\u6811\u8282\u70b9 \"\"\"\n\n def __init__(self, data: any):\n self.__data = data\n self.__left = None # \u5de6\u5b50\u6811\n self.__right = None # \u53f3\u5b50\u6811\n\n @property\n def data(self):\n return self.__data\n\n @data.setter\n def data(self, data: any):\n self.__data = data\n\n @property\n def left(self):\n return self.__left\n\n @left.setter\n def left(self, left):\n self.__left = left\n\n @property\n def right(self):\n return self.__right\n\n @right.setter\n def right(self, right):\n self.__right = right\n\n def __str__(self):\n return \"data = \" + str(self.__data)\n\n\nclass HuffmanTree(TreeNode):\n \"\"\"\n \u54c8\u592b\u66fc\u6811\uff08Huffman Tree\uff09\uff1a\u53c8\u53eb\u6700\u4f18\u4e8c\u53c9\u6811\uff0c\u6307\u4e00\u7ec4\u5177\u6709\u786e\u5b9a\u6743\u503c\u7684\u53f6\u5b50\u8282\u70b9\u7684\u5177\u6709\u6700\u5c0f\u5e2f\u6743\u8def\u5f84\u957f\u5ea6\uff08WPL\uff09\u7684\u4e8c\u53c9\u6811\u3002\n \u6811\u7684\u5e2f\u6743\u8def\u5f84\u957f\u5ea6\uff1a\u6811\u4e2d\u6240\u6709\u53f6\u5b50\u8282\u70b9\u7684\u5e2f\u6743\u8def\u5f84\u957f\u5ea6\u4e4b\u548c\u5c31\u662f\u6811\u7684\u5e2f\u6743\u8def\u5f84\u957f\u5ea6WPL(weighted path length)\n \"\"\"\n\n \"\"\"\n \u6784\u9020\u6b65\u9aa4\uff1a\n 1. \u9996\u5148\u6839\u636en\u4e2a\u6709\u6743\u503c\u7684\u8282\u70b9\u6784\u9020n\u68f5\u5355\u8282\u70b9\u4e8c\u53c9\u6811\uff0c\u5c06\u6743\u503c\u4fdd\u5b58\u5728\u6839\u8282\u70b9\u4e2d\uff0c\u5176\u5de6\u53f3\u5b50\u6811\u5747\u4e3a\u7a7a\n 2. \u5728\u8fd9n\u68f5\u5355\u8282\u70b9\u4e8c\u53c9\u6811\u4e2d\u627e\u51fa\u4e24\u68f5\u6839\u8282\u70b9\u6743\u503c\u6700\u5c0f\u7684\u6811\uff0c\u7528\u8fd9\u4e24\u68f5\u6811\u4f5c\u4e3a\u5de6\u53f3\u5b50\u6811\u6784\u9020\u4e00\u9897\u65b0\u7684\n \u4e8c\u53c9\u6811\uff0c\u5c06\u5de6\u53f3\u5b50\u6811\u7684\u6839\u8282\u70b9\u7684\u6743\u503c\u76f8\u52a0\u4f5c\u4e3a\u65b0\u4e8c\u53c9\u6811\u6839\u8282\u70b9\u7684\u6743\u503c\u3002\n 3. \u5c06\u4e0a\u4e00\u6b65\u627e\u5230\u7684\u4e24\u68f5\u6743\u503c\u6700\u5c0f\u7684\u4e8c\u53c9\u6811\u6392\u67e5\u5728\u4e0b\u6b21\u67e5\u627e\u7684\u8303\u56f4\u4e4b\u5916\uff0c\u5c06\u65b0\u521b\u5efa\u7684\u4e8c\u53c9\u6811\u6dfb\u52a0\u5230\u67e5\u627e\u8303\u56f4\u4e4b\u5185\u3002\n 4. \u91cd\u590d\u6b65\u9aa42\u548c\u6b65\u9aa43\uff0c\u76f4\u5230\u67e5\u627e\u8303\u56f4\u53ea\u5269\u4e0b\u4e00\u9897\u6811\u4e3a\u6b62\n \"\"\"\n\n @staticmethod\n def createHuffmanTree(weighteds: List[int]):\n lenght = len(weighteds)\n if lenght == 0:\n raise AttributeError(\"\u6784\u9020\u54c8\u592b\u66fc\u6811\u65f6\u6743\u91cd\u5217\u8868\u4e0d\u80fd\u4e3a\u7a7a\uff01\")\n if lenght == 1:\n return HuffmanTree(weighteds[0])\n weighteds.sort(reverse=True) # \u5c06\u6743\u91cd\u4ece\u5927\u5230\u5c0f\u6392\u5e8f\n huffNodes = list(map(lambda weight: HuffmanTree(weight), weighteds)) # \u751f\u6210\u5355\u8282\u70b9\u4e8c\u53c9\u6811\n huff_root = None\n while len(huffNodes) >= 2:\n # \u5f39\u51fa\u4e24\u4e2a\u6700\u5c0f\u6743\u91cd\u7684\u5355\u8282\u70b9\u4e8c\u53c9\u6811\u7ec4\u6210\u6210\u4e00\u9897\u65b0\u7684\u4e8c\u53c9\u6811\n huff_left = huffNodes.pop()\n huff_right = huffNodes.pop()\n huff_root_weight = huff_left.data + huff_right.data\n huff_root = HuffmanTree(huff_root_weight)\n huff_root.left = huff_left\n huff_root.right = huff_right\n # \u5c06\u65b0\u521b\u5efa\u7684\u4e8c\u53c9\u6811\u8282\u70b9\u6dfb\u52a0\u5230\u67e5\u627e\u8303\u56f4\u5185\uff0c\u540c\u65f6\u786e\u4fdd\u8282\u70b9\u5217\u8868\u6709\u5e8f\n for index, node in enumerate(huffNodes):\n if node.data <= huff_root.data:\n huffNodes.insert(index, huff_root)\n break\n elif index == len(huffNodes) - 1: # \u5982\u679c\u6ca1\u6709\u6bd4\u6b64root\u8282\u70b9\u5c0f\u7684\u6570\u636e\uff0c\u76f4\u63a5\u5c06\u6b64\u8282\u70b9\u6dfb\u52a0\u5230\u6700\u540e\n huffNodes.append(huff_root)\n break # \u6ce8\u610fbreak\uff0c\u4e0d\u7136\u8fd8\u4f1a\u5faa\u73af\u4e00\u6b21\u800c\u4e24\u6b21\u63d2\u5165\u8282\u70b9\n return huff_root\n\n @staticmethod\n def createHuffmanCode(weight_str: Dict) -> Dict:\n \"\"\"\n \u751f\u6210\u4e00\u9897Huffman\u6811\uff0c\u7531\u4e8e\u6240\u6709\u5e26\u6743\u91cd\u7684\u8282\u70b9\u90fd\u662f\u53f6\u5b50\u8282\u70b9\uff0c\n \u6240\u4ee5\u4ece\u6839\u8282\u70b9\u9012\u5f52\u904d\u5386\u6b64\u54c8\u592b\u66fc\u6811\uff0c\u9047\u5230\u5de6\u5b50\u6811\u7f16\u7801+'0'\uff0c\n \u9047\u5230\u53f3\u5b50\u6811\u7f16\u7801+'1'\uff0c\u5f97\u5230\u6bcf\u4e2a\u53f6\u5b50\u8282\u70b9\u7684\u7f16\u7801\n :param weight_str: (int -> str) \u6bd4\u91cd\u548c\u5bf9\u5e94\u5b57\u7b26\u7684\u5b57\u5178\n :return str_code: (str -> str) \u5b57\u7b26\u548c\u5bf9\u5e94\u7f16\u7801\u7684\u5b57\u5178\n \"\"\"\n weights = list(weight_str.keys()) # \u83b7\u53d6\u6240\u6709\u6bd4\u91cd\u503c\n root_huffman = HuffmanTree.createHuffmanTree(weights) # \u6784\u5efahuffman\u6811\n\n # \u904d\u5386\u6bcf\u4e2a\u53f6\u5b50\u8282\u70b9\uff0c\u751f\u6210\u5bf9\u5e94\u7f16\u7801\n str_code = {}\n\n # \u5148\u5e8f\u904d\u5386\u54c8\u592b\u66fc\u6811\u751f\u6210\u54c8\u592b\u66fc\u7f16\u7801\uff0c\u5de6\u5b50\u6811\u7f16\u7801+'0'\uff0c\u53f3\u5b50\u6811\u7f16\u7801+'1'\n def code_generater(tree: HuffmanTree, code: str = \"\"):\n if tree.left is None: # \u54c8\u592b\u66fc\u6811\u4e2d\u7684\u975e\u53f6\u5b50\u8282\u70b9\u5de6\u53f3\u5b50\u6811\u90fd\u4e0d\u4e3aNone\n weight = tree.data\n str_code[weight_str.get(weight)] = code\n return\n code_generater(tree.left, code + \"0\")\n code_generater(tree.right, code + \"1\")\n\n code_generater(root_huffman)\n return str_code\n\n\nclass BinarySearchTree:\n \"\"\"\n \u4e8c\u53c9\u641c\u7d22\u6811\uff08Binary Search Tree\uff09\uff1a\u53c8\u79f0\u4e8c\u53c9\u6392\u5e8f\u6811\uff0c\u6709\u5982\u4e0b\u6027\u8d28\uff1a\n \u82e5\u5b83\u7684\u5de6\u5b50\u6811\u4e0d\u7a7a\uff0c\u5219\u5de6\u5b50\u6811\u4e0a\u6240\u6709\u7684\u8282\u70b9\u7684\u503c\u5747\u5c0f\u4e8e\u5b83\u7684\u6839\u8282\u70b9\uff0c\n \u82e5\u5b83\u7684\u53f3\u5b50\u6811\u4e0d\u7a7a\uff0c\u5219\u53f3\u5b50\u6811\u4e0a\u6240\u6709\u7684\u8282\u70b9\u7684\u503c\u5747\u5927\u4e8e\u5b83\u7684\u6839\u8282\u70b9\uff1b\n \u5b83\u7684\u5de6\u3001\u53f3\u5b50\u6811\u4e5f\u5206\u522b\u4e3a\u4e8c\u53c9\u641c\u7d22\u6811\u3002\n \u6bcf\u6b21\u64cd\u4f5c\u7684\u65f6\u95f4\u590d\u6742\u5ea6\u4e3aO(logn)\uff0c\u548c\u6811\u7684\u9ad8\u5ea6\u6210\u6b63\u6bd4\n \"\"\"\n\n def __init__(self):\n self._root = TreeNode(None)\n\n def search(self, data: any) -> bool:\n \"\"\"\n \u67e5\u627e\u6570\u636e\u662f\u5426\u5b58\u5728\n :param data: \u6570\u636e\n :return: True - \u6570\u636e\u5b58\u5728\uff0cFalse - \u6570\u636e\u4e0d\u5b58\u5728\n \"\"\"\n node = self._root\n while node:\n node_data = node.data\n if node_data == data:\n return True\n elif node_data < data:\n node = node.right\n else:\n node = node.left\n return False\n\n def insert(self, data: any) -> any:\n \"\"\"\n \u63d2\u5165\u6570\u636e\uff0c\u5982\u679c\u6709\u91cd\u590d\u6570\u636e\u5219\u5ffd\u7565\n :param data: \u6570\u636e\n :return: \u6210\u529f\u63d2\u5165\u5219\u8fd4\u56dedata\uff0c\u6709\u91cd\u590d\u6570\u636e\u8fd4\u56de None\n \"\"\"\n node = self._root\n if node.data is None: # \u6574\u9897\u6811\u4e3a\u7a7a\n node.data = data\n return data\n while node:\n node_data = node.data\n if node_data == data:\n return None\n elif node_data < data:\n if node.right:\n node = node.right\n else: # \u76f4\u5230\u53f3\u5b50\u6811\u4e3a\u7a7a\u65f6\uff0c\u6784\u9020\u8282\u70b9\u63d2\u5165\u5230\u6b64\u8282\u70b9\u7684\u53f3\u5b50\u6811\n node.right = TreeNode(data)\n return data\n else:\n if node.left:\n node = node.left\n else:\n node.left = TreeNode(data)\n return data\n return None\n\n def delete(self, data: any) -> any:\n \"\"\"\n \u5220\u9664\u6570\u636e\n :param data: \u6570\u636e\n :return: \u5982\u679c\u5220\u9664\u6210\u529f\uff0c\u8fd4\u56de\u6b64\u6570\u636e\uff0c\u5982\u679c\u65e0\u6b64\u6570\u636e\uff0c\u8fd4\u56deNone\n \"\"\"\n ######## \u975e\u9012\u5f52\u5b9e\u73b0 #######\n pre_node = None # \u524d\u9a71\u8282\u70b9\n node = self._root\n left_side = None # \u5f53\u524d\u8282\u70b9\u4e3a\u7236\u8282\u70b9\u7684\u5de6\u8282\u70b9\uff1f\n while node:\n node_data = node.data\n if node_data == data: # \u627e\u5230\u8282\u70b9\u4f4d\u7f6e\n data_node = node\n if data_node.left and data_node.right:\n # \u8282\u70b9\u7684\u5ea6\u4e3a2\uff0c\u4ece\u6b64\u8282\u70b9\u7684\u5de6\u5b50\u6811\u4e2d\u9009\u51fa\u4e00\u4e2a\u6700\u5927\u503c\u7684\u8282\u70b9\u66ff\u6362\u6b64\u8282\u70b9\n left_max_node: TreeNode = data_node.left\n pre_left_max_node: TreeNode = data_node # \u524d\u9a71\u8282\u70b9\n while left_max_node.right:\n pre_left_max_node, left_max_node = left_max_node, left_max_node.right\n left_max_node_left = left_max_node.left # \u6700\u5927\u8282\u70b9\u7684\u5de6\u8282\u70b9\n # \u5c06data_node\u66ff\u6362\u6210left_max_node\n data_node.data = left_max_node.data\n # \u5220\u9664left_max_node, \u6b64\u8282\u70b9\u65e0\u53f3\u5b50\u6811\uff0c\u4e14\u6709\u524d\u9a71\u8282\u70b9\n if left_max_node == data_node.left: # \u5de6\u8282\u70b9\n pre_left_max_node.left = left_max_node_left\n left_max_node.left = None\n else:\n # \u5de6\u8282\u70b9\u7684\u53f3\u5b50\u6811\n pre_left_max_node.right = left_max_node_left\n left_max_node.left = None\n #\n elif data_node.left or data_node.right:\n # \u8282\u70b9\u7684\u5ea6\u4e3a1\uff0c\u76f4\u63a5\u5c06\u5b50\u8282\u70b9\u79fb\u5230\u672c\u8282\u70b9\n node_child = data_node.left if data_node.left else data_node.right\n if pre_node:\n # \u5b50\u8282\u70b9\u66ff\u6362\u672c\u8282\u70b9\n if left_side:\n pre_node.left = node_child\n else:\n pre_node.right = node_child\n else: # \u6839\u8282\u70b9\u4e3a\u8981\u5220\u9664\u7684\u8282\u70b9\n self._root = node_child # \u65e0\u524d\u9a71\u8282\u70b9\u65f6\u4e0d\u80fd\u4f7f\u7528left_side\u6807\u8bb0\u5224\u65ad\n data_node.left, data_node.right, data_node.data = None, None, None # \u91ca\u653e\u8282\u70b9\u8d44\u6e90\n else:\n # \u8282\u70b9\u7684\u5ea6\u4e3a0\uff0c\u76f4\u63a5\u5220\u9664\u672c\u8282\u70b9\n data_node.data = None\n if pre_node: # \u6709\u524d\u9a71\u8282\u70b9\uff0c\u5373\u672c\u8282\u70b9\u4e0d\u662f\u6839\u8282\u70b9\n if left_side: # \u5224\u65ad\u662f\u524d\u9a71\u8282\u70b9\u7684\u5de6\u8282\u70b9\u8fd8\u662f\u53f3\u8282\u70b9\n pre_node.left = None\n else:\n pre_node.right = None\n break\n elif node_data < data: # \u5411\u53f3\u904d\u5386\n pre_node = node\n node = node.right\n left_side = False\n else: # \u5411\u5de6\u904d\u5386\n pre_node = node\n node = node.left\n left_side = True\n \"\"\" \u9012\u5f52\u5b9e\u73b0\u53c2\u8003\n def delete(root, value):\n if not root:\n return None\n if value < root.value:\n root.lchild = delete(root.lchild, value)\n elif value > root.value:\n root.rchild = delete(root.rchild, value)\n else:\n if root.lchild and root.rchild: # degree of the node is 2\n target = root.lchild # find the maximum node of the left subtree\n while target.rchild:\n target = target.rchild\n root = delete(root, target.value)\n root.value = target.value\n else: # degree of the node is [0|1]\n root = root.lchild if root.lchild else root.rchild\n return root\n \"\"\"\n return None\n\n def traversal(self):\n self.__traversal(self._root)\n print()\n\n def __traversal(self, node: TreeNode):\n if not node:\n return\n self.__traversal(node.left)\n print(node.data, end=' ')\n self.__traversal(node.right)\n\n\nclass AVLTreeNode(TreeNode):\n\n def __init__(self, data: any):\n super().__init__(data)\n self.__height = 0\n\n @property\n def height(self):\n \"\"\"\n \u8282\u70b9\u7684\u9ad8\u5ea6\uff0c\u7528\u4e8e\u8ba1\u7b97\u7236\u8282\u70b9\u7684\u5e73\u8861\u56e0\u5b50\n :return:\n \"\"\"\n return self.__height\n\n @height.setter\n def height(self, height: int):\n self.__height = height\n\n\nclass AVLTree:\n \"\"\"\n AVL\u6811\u662f\u6700\u5148\u53d1\u660e\u7684\u81ea\u5e73\u8861\u4e8c\u53c9\u67e5\u627e\u6811\uff08Self-Balancing Binary Search Tree\uff09\u3002\n \u5e73\u8861\u56e0\u5b50\uff08BF\uff09\uff1a\u5de6\u5b50\u6811\u7684\u9ad8\u5ea6\u51cf\u53bb\u53f3\u5b50\u6811\u7684\u9ad8\u5ea6\n \u94fe\u63a5\uff1ahttps://cloud.tencent.com/developer/article/1155143\n \u4e00\u9897AVL\u6811\u6709\u5982\u4e0b\u5fc5\u8981\u6761\u4ef6\uff1a\n 1. \u5b83\u5fc5\u987b\u662f\u4e8c\u53c9\u67e5\u627e\u6811\n 2. \u6bcf\u4e2a\u8282\u70b9\u7684\u5de6\u5b50\u6811\u548c\u53f3\u5b50\u6811\u7684\u9ad8\u5ea6\u5dee\u81f3\u591a\u4e3a1\n \"\"\"\n\n def __init__(self):\n self._root = None\n\n def insert(self, data):\n self._root = AVLTree._insertNode(self._root, data)\n\n def delete(self, data):\n self._root = AVLTree._deleteNode(self._root, data)\n\n def search(self, data) -> bool:\n data_node = AVLTree._searchNode(self._root, data)\n return True if data_node else False\n\n def traversal(self):\n AVLTree._LDR_traversal(self._root, lambda d: print(str(d), end=\"\\t\"))\n print()\n\n ########################### static method #############################\n @staticmethod\n def _LDR_traversal(root: AVLTreeNode, fn: Callable):\n if root:\n AVLTree._LDR_traversal(root.left, fn)\n fn(root.data)\n AVLTree._LDR_traversal(root.right, fn)\n\n @staticmethod\n def _height(node: AVLTreeNode) -> int:\n \"\"\" AVL\u7684\u9ad8\u5ea6 \"\"\"\n return node.height if node else 0\n\n @staticmethod\n def _leftRotation(root: AVLTreeNode) -> AVLTreeNode:\n \"\"\"\n \u5355\u5de6\u65cb\u8f6c\uff1a\u5728\u53f3\u5b50\u6811\u63d2\u5165\u53f3\u5b69\u5b50\u5bfc\u81f4AVL\u5931\u8861\uff0c\u4f7f\u7528\u5355\u5de6\u65cb\u8f6c\uff1a\n 4 BF=-1 \u63d2\u51656 (4) \u5de6\u65cb 5\n \\ =====> \\ ========> / \\\n 5 5 4 6\n \\ BF=0\n 6\n \u5206\u6790\uff1a\n 1. \u6839\u8282\u70b9\u4e3a\u8282\u70b94\n 2. \u82e5\u8282\u70b95\u6709\u5de6\u5b50\u6811\uff0c\u5219\u8be5\u5de6\u5b50\u6811\u6210\u4e3a\u8282\u70b94\u7684\u53f3\u5b50\u6811\n 3. \u8282\u70b94\u6210\u4e3a\u8282\u70b95\u7684\u5de6\u5b50\u6811\n 4. \u66f4\u65b0\u8282\u70b9\u7684\u9ad8\u5ea6\n :param root: \u6700\u5c0f\u5931\u8861\u5b50\u6811\u7684\u6839\u8282\u70b9\n :return: \u5355\u5de6\u65cb\u540e\u7684root\u8282\u70b9\n \"\"\"\n rchild: AVLTreeNode = root.right\n root.right = rchild.left\n rchild.left = root\n\n root.height = max(AVLTree._height(root.left), AVLTree._height(root.right)) + 1\n rchild.height = max(AVLTree._height(rchild.left), AVLTree._height(rchild.right)) + 1\n\n return rchild\n\n @staticmethod\n def _rightRotation(root: AVLTreeNode) -> AVLTreeNode:\n \"\"\"\n \u5355\u53f3\u65cb\u8f6c\uff1a\u5728\u5de6\u5b50\u6811\u4e0a\u63d2\u5165\u5de6\u5b69\u5b50\u5bfc\u81f4AVL\u6811\u5931\u8861\uff0c\u4f7f\u7528\u5355\u53f3\u65cb\u8f6c\uff1a\n 5 5 5\n / \\ \u63d2\u51652\u30013 / \\ \u53f3\u65cb / \\\n 4 6 ====> (4) 6 =====> 3 6\n BF=0 / BF=2 / \\\n 3 2 4 BF=0\n /\n 2\n 1. \u6700\u5c0f\u5931\u8861\u5b50\u6811\u7684\u6839\u8282\u70b9\u4e3a\u8282\u70b94\n 2. \u82e5\u8282\u70b93\u6709\u53f3\u5b50\u6811\uff0c\u5219\u8be5\u53f3\u5b50\u6811\u79f0\u4e3a\u8282\u70b94\u7684\u5de6\u5b50\u6811\n 3. \u8282\u70b94\u79f0\u4e3a\u8282\u70b93\u7684\u53f3\u5b50\u6811\n 4. \u8c03\u6574\u8282\u70b9\u9ad8\u5ea6\n :param root: \u5355\u53f3\u65cb\u540e\u7684root\u8282\u70b9\n :return:\n \"\"\"\n lchild: AVLTreeNode = root.left\n root.left = lchild.right\n lchild.right = root\n\n root.height = max(AVLTree._height(root.left), AVLTree._height(root.right)) + 1\n lchild.height = max(AVLTree._height(lchild.left), AVLTree._height(lchild.right)) + 1\n\n return lchild\n\n @staticmethod\n def _rightLeftRotation(root: AVLTreeNode) -> AVLTreeNode:\n \"\"\"\n \u5148\u53f3\u65cb\u540e\u5de6\u65cb\uff1a\u5728\u53f3\u5b50\u6811\u4e0a\u63d2\u5165\u5de6\u5b69\u5b50\u5bfc\u81f4AVL\u6811\u5931\u8861\u65f6\u4f7f\u7528\uff1a\n 6 6 7\n \\ \u53f3\u65cb \\ \u5de6\u65cb / \\\n 8 ====> 7 ====> 6 8\n / \\\n 7 8\n 1. \u5bf9\u6700\u5c0f\u4e0d\u5e73\u8861\u6811\u6839\u8282\u70b9\u7684\u53f3\u5b69\u5b50\u8282\u70b98\u8fdb\u884c\u53f3\u65cb\u64cd\u4f5c\n 2. \u518d\u5bf9\u6839\u8282\u70b96\u8fdb\u884c\u5de6\u65cb\u8f6c\n :param root:\n :return:\n \"\"\"\n root.right = AVLTree._rightRotation(root.right)\n return AVLTree._leftRotation(root)\n\n @staticmethod\n def _leftRightRotation(root: AVLTreeNode) -> AVLTreeNode:\n \"\"\"\n \u5148\u5de6\u65cb\u540e\u53f3\u65cb\uff1a\u5728\u5de6\u5b50\u6811\u4e0a\u63d2\u5165\u53f3\u5b69\u5b50\u5bfc\u81f4AVL\u6811\u5931\u8861\u65f6\u4f7f\u7528\uff1a\n 2 2 1\n / \u53f3\u65cb / \u5de6\u65cb / \\\n 0 ====> 1 ====> 0 2\n \\ /\n 1 0\n 1. \u5bf9\u6700\u5c0f\u4e0d\u5e73\u8861\u6811\u6839\u8282\u70b9\u7684\u5de6\u5b69\u5b50\u8282\u70b90\u8fdb\u884c\u5de6\u65cb\u8f6c\n 2. \u5bf9\u6839\u8282\u70b92\u8fdb\u884c\u53f3\u65cb\u8f6c\n :param root:\n :return:\n \"\"\"\n root.left = AVLTree._rightRotation(root.left)\n return AVLTree._leftRotation(root)\n\n @staticmethod\n def _searchNode(root: AVLTreeNode, data) -> AVLTreeNode:\n \"\"\"\n AVL\u6811\u9012\u5f52\u67e5\u8be2\u6570\u636e\n :return \u6570\u636e\u5b58\u5728\u6570\u636e\u6240\u5728\u8282\u70b9\uff0c\u6570\u636e\u4e0d\u5b58\u5728\u8fd4\u56deNone\n \"\"\"\n if root:\n if data == root.data:\n return root\n if data > root.data:\n return AVLTree._searchNode(root.right, data)\n if data < root.data:\n return AVLTree._searchNode(root.left, data)\n\n @staticmethod\n def _insertNode(root: AVLTreeNode, data: any) -> AVLTreeNode:\n if root is None:\n root = AVLTreeNode(data)\n elif data > root.data:\n root.right = AVLTree._insertNode(root.right, data)\n # AVL\u6811\u5e73\u8861\u56e0\u5b50\u68c0\u67e5\u548c\u518d\u5747\u8861\n # \u63d2\u5165\u53f3\u5b50\u8282\u70b9\uff0c\u5219\u6b64\u65f6\u53f3\u5b50\u6811\u9ad8\u5ea6+1\uff0c\u4e0d\u53ef\u80fd\u51fa\u73b0\u5de6\u5b50\u6811\u9ad8\u5ea6-\u53f3\u5b50\u6811\u9ad8\u5ea6\u5927\u4e8e2\u7684\u60c5\u51b5\n if AVLTree._height(root.right) - AVLTree._height(root.left) == 2:\n if data > root.right.data:\n # \u63d2\u5165\u53f3\u5b50\u8282\u70b9\u7684\u53f3\u8282\u70b9\uff0c\u8fdb\u884c\u5de6\u65cb\n root = AVLTree._leftRotation(root)\n elif data < root.right.data:\n # \u63d2\u5165\u53f3\u5b50\u8282\u70b9\u7684\u5de6\u8282\u70b9\uff0c\u5148\u53f3\u65cb\u518d\u5de6\u65cb\n root = AVLTree._rightLeftRotation(root)\n elif data < root.data:\n root.left = AVLTree._insertNode(root.left, data)\n if AVLTree._height(root.left) - AVLTree._height(root.right) == 2:\n if data < root.left.data:\n root = AVLTree._rightRotation(root)\n elif data > root.left.data:\n root = AVLTree._leftRightRotation(root)\n root.height = max(AVLTree._height(root.left), AVLTree._height(root.right)) + 1\n return root\n\n @staticmethod\n def _deleteNode(root: AVLTreeNode, data: any) -> AVLTreeNode:\n \"\"\"\n \u5220\u9664\u8282\u70b9\u4e5f\u53ef\u80fd\u5bfc\u81f4AVL\u6811\u7684\u5931\u8861\uff0c\u5b83\u548c\u63d2\u5165\u662f\u4e00\u79cd\u4e92\u9006\u7684\u64cd\u4f5c\uff1a\n 1. \u5220\u9664\u53f3\u5b50\u6811\u7684\u8282\u70b9\u5bfc\u81f4AVL\u6811\u5931\u8861\u65f6\uff0c\u76f8\u5f53\u4e8e\u5728\u5de6\u5b50\u6811\u63d2\u5165\u8282\u70b9\u5bfc\u81f4AVL\u6811\u5931\u8861\n 2. \u5220\u9664\u5de6\u5b50\u6811\u7684\u8282\u70b9\u5bfc\u81f4AVL\u6811\u5931\u8861\u65f6\uff0c\u76f8\u5f53\u4e8e\u5728\u53f3\u5b50\u6811\u63d2\u5165\u8282\u70b9\u5bfc\u81f4AVL\u6811\u5931\u8861\n \u53e6\u5916\uff0c\u5728\u5220\u9664\u8282\u70b9\u65f6\u4e5f\u8981\u7ef4\u62a4\u4e8c\u53c9\u6392\u5e8f\u6811\u7684\u9ad8\u5ea6\u5c5e\u6027\n \u5728\u5220\u9664\u8282\u70b9\u65f6\uff0c\u5982\u679c\u8282\u70b9\u540c\u65f6\u62e5\u6709\u5de6\u53f3\u5b50\u6811\uff0c\u5219\u5728\u9ad8\u5ea6\u8f83\u9ad8\u7684\u5b50\u6811\u4e0a\u9009\u62e9\u6700\u5927\uff08\u6216\u6700\u5c0f\uff09\n \u5143\u7d20\u8fdb\u884c\u66ff\u6362\uff0c\u8fd9\u6837\u80fd\u4fdd\u8bc1\u66ff\u6362\u540e\u4e0d\u4f1a\u518d\u51fa\u73b0\u5931\u8861\u7684\u73b0\u8c61\u3002\n \"\"\"\n if root:\n if data == root.data: # \u9501\u5b9a\u9700\u8981\u5220\u9664\u7684\u8282\u70b9\n if root.left and root.right:\n # \u5220\u9664\u8282\u70b9\u540c\u65f6\u6709\u5de6\u53f3\u5b50\u6811\uff0c\u9009\u62e9\u9ad8\u5ea6\u8f83\u9ad8\u7684\u5b50\u6811\u4e0a\u9009\u62e9\u6700\u5927\u6216\u6700\u5c0f\u5143\u7d20\u8fdb\u884c\u66ff\u6362\uff0c\u8fd9\u6837\n # \u5c31\u65e0\u9700\u8c03\u6574AVL\u6811\u7684\u5e73\u8861\u6027\n if AVLTree._height(root.left) > AVLTree._height(root.right):\n # \u5de6\u8282\u70b9\u9ad8\u5ea6\u5927\u4e8e\u53f3\u8282\u70b9\uff0c\u9009\u62e9\u5de6\u8282\u70b9\u4e2d\u6700\u5927\u8282\u70b9\u66ff\u6362root\u8282\u70b9\uff0c\u6b64\u65f6\u65e0\u9700\u8c03\u6574\u5e73\u8861\u6027\n left_maxNode = AVLTree.__maxNode(root.left)\n root.data = left_maxNode.data\n # \u2605\u2605\u2605\u8bbe\u7f6eroot\u5de6\u8282\u70b9\u4e3a\u5220\u9664\u4ee5root\u8282\u70b9\u5de6\u8282\u70b9\u4e3aroot\u8282\u70b9\u7684\u6811\u7684\u6700\u5927\u8282\u70b9\u540e\u7684\u6839\u8282\u70b9\n root.left = AVLTree._deleteNode(root.left, left_maxNode.data)\n else:\n # \u5de6\u8282\u70b9\u9ad8\u5ea6\u5c0f\u4e8e\u7b49\u4e8e\u53f3\u8282\u70b9\uff0c\u9009\u62e9\u53f3\u8282\u70b9\u4e2d\u6700\u5c0f\u8282\u70b9\u66ff\u6362root\u8282\u70b9\n right_minNode = AVLTree.__minNode(root.right)\n root.data = right_minNode.data\n root.right = AVLTree._deleteNode(root.right, right_minNode.data)\n else:\n # \u8282\u70b9\u7684\u5b50\u6811\u4e3a1\u62160\u68f5\uff0c\u76f4\u63a5\u4f7f\u7528\u5b50\u6811\u8282\u70b9\u66ff\u6362\u672c\u8282\u70b9\n root = root.left if root.left else root.right\n\n elif data > root.data:\n # \u6570\u636e\u5728\u53f3\u5b50\u6811\u4e0a\n root.right = AVLTree._deleteNode(root.right, data)\n if AVLTree._height(root.left) - AVLTree._height(root.right) == 2:\n # \u2605\u2605\u2605\u5bf9root\u8fdb\u884c\u518d\u5e73\u8861\u5904\u7406\n if AVLTree._height(root.left.right) > AVLTree._height(root.left.left):\n root = AVLTree._leftRightRotation(root)\n else:\n root = AVLTree._rightRotation(root)\n else:\n # \u6570\u636e\u5728\u5de6\u5b50\u6811\u4e0a\n root.left = AVLTree._deleteNode(root.left, data)\n if AVLTree._height(root.right) - AVLTree._height(root.left) == 2:\n if AVLTree._height(root.right.left) > AVLTree._height(root.right.right):\n root = AVLTree._rightLeftRotation(root)\n else:\n root = AVLTree._leftRotation(root)\n return root\n\n ########################### private method #############################\n @staticmethod\n def __maxNode(root: AVLTreeNode) -> AVLTreeNode:\n \"\"\"\n \u9009\u51faAVL\u6811\u4e2d\u5143\u7d20\u6700\u5927\u7684\u8282\u70b9\u5e76\u8fd4\u56de\n \"\"\"\n if root:\n return AVLTree.__maxNode(root.right) if root.right else root\n\n @staticmethod\n def __minNode(root: AVLTreeNode) -> AVLTreeNode:\n \"\"\"\n \u9009\u51faAVL\u6811\u4e2d\u5143\u7d20\u6700\u5c0f\u7684\u8282\u70b9\u5e76\u8fd4\u56de\n \"\"\"\n if root:\n return AVLTree.__minNode(root.left) if root.left else root\n\n\ndef createBinarySearchTree(datas: []) -> BinarySearchTree:\n tree = BinarySearchTree()\n for data in datas:\n tree.insert(data)\n return tree\n\n\nif __name__ == '__main__':\n def LDR_traversal(root: TreeNode, fn):\n \"\"\"\n \u4e2d\u5e8f\u904d\u5386\u4e8c\u53c9\u6811\n :param fn:\n :param root: \u4e8c\u53c9\u6811\u6839\u8282\u70b9\n \"\"\"\n if root:\n LDR_traversal(root.left, fn)\n fn(root.data)\n LDR_traversal(root.right, fn)\n\n\n huffman_weight = [[5, 7, 2, 13], [7, 5, 2, 4], [7, 19, 2, 6, 32, 3, 21, 10], [13, 7, 8, 3, 29, 6, 1],\n [3, 12, 7, 4, 2, 8, 11]]\n for weighted in huffman_weight:\n huffmane_tree = HuffmanTree.createHuffmanTree(weighted)\n LDR_traversal(huffmane_tree, lambda node: print(node, end=\"\\t\"))\n print(\"\\r\\n===================== next>>>>>>\")\n weight_char = {6: \"A\", 3: \"B\", 8: \"C\", 2: \"D\", 10: \"E\", 4: \"F\"}\n print(HuffmanTree.createHuffmanCode(weight_char))\n print(\"================== \u4e8c\u53c9\u641c\u7d22\u6811 >>>>>>>\")\n arr = [5, 3, 4, 0, 2, 1, 8, 6, 9, 7]\n bst = createBinarySearchTree(arr)\n for x in arr[::-1]:\n print(\"after delete\", x, end=\",BST in-order is = \")\n bst.delete(x)\n bst.traversal()\n print()\n arr1 = [20, 9, 8, 15, 12, 13, 11, 23]\n bst1 = createBinarySearchTree(arr1)\n bst1.delete(20)\n bst1.traversal()\n bst1.delete(9)\n bst1.traversal()\n bst1.delete(8)\n bst1.traversal()\n bst1.delete(11)\n bst1.traversal()\n bst1.delete(15)\n bst1.traversal()\n print(\"================== AVL\u6811 >>>>>>>\")\n avl = AVLTree()\n for i in range(20):\n avl.insert(i)\n avl.traversal()\n avl.delete(8)\n avl.delete(15)\n avl.delete(3)\n avl.delete(9)\n avl.traversal()\n"} {"doc_id": "09293131c18e2b6476eddcbf05754bfa", "text": "# Code to print all values from 1 to 100\n# Skip the numbers which are divisible by 3 or 5\n\nfor i in range(1, 100):\n if i % 3 != 0 or i % 5 != 0:\n print(i)\n else:\n pass\n\n# While loop\n\ni = 1\nwhile (i < 101):\n if (i % 3 != 0) and (i % 5 != 0):\n print(i)\n i = i + 1\n\n# Print pattern\n\n####\n####\n####\n####\n\ni = 1\nwhile i <= 5:\n print(5 * '#')\n i = i + 1\n print()\n"} {"doc_id": "093bba7387e0ae9772466be84cf2c0da", "text": "#\u067e\u0631\u0648\u0698\u0647 \u0628\u0627\u0646\u06a9\n#\u0646\u0648\u0634\u062a\u0647 \u0634\u062f\u0647 \u062a\u0648\u0633\u0637 \u0627\u0645\u06cc\u0631 \u062d\u0633\u06cc\u0646 \u063a\u0631\u0642\u06cc\n\nclass Bank:\n \n def Create(self):\n\n self.first_name = input( 'Enter first name : ')\n self.last_name = input(\"Enter your last name : \")\n self.phone_number = input(\"Enter your phone number, sample : 0912*****54 :\")\n self.value = float(input(\"Enter your start value : \"))\n \n while self.value < 0 :\n print(\"First value can not be negative !\")\n self.value = float(input(\"Enter your start value : \"))\n\n def Add(self):\n self.to_add = float(input(\"How much do you want to add? \"))\n\n while self.to_add < 0 :\n print(\"Can't be negative! try again \")\n self.to_add = float(input(\"How much do you want to add? \")) \n\n self.value += self.to_add\n print (\"your balance is :\", self.value)\n\n def Sub(self):\n self.sub_from = float(input(\"how much do you want to take? \"))\n \n while self.sub_from < 0 and self.sub_from > self.value:\n print(\"Cant be negative! try again \")\n self.sub_from = float(input(\"how much do you want to take? \"))\n\n self.value -= self.sub_from\n print (\"your balance is :\", self.value)\n\n def Show(self):\n print(self.first_name, self.last_name,\"phone number\", self.phone_number,\"account balance\", self.value)\n\n#------main---------------------------------\n\nprint(\"\"\" \nWellcome \nhere are your choices:)\npress 1 to create an account;\npress 2 to deposit to your account;\npress 3 to withdraw from the account\npress 4 to show your info;\npress 0 to exit;\n\"\"\")\n\n\ncustomer = Bank()\n\nwhile True :\n print(\"\"\" \n Wellcome \n here are your choices:)\n press 1 to create an account;\n press 2 to deposit to your account;\n press 3 to withdraw from the account\n press 4 to show your info;\n press 0 to exit;\n \"\"\")\n menu = int(input(\"\"))\n\n if menu == 1:\n \n customer.Create()\n \n\n elif menu == 2 :\n \n customer.Add()\n \n\n elif menu == 3 :\n \n customer.Sub()\n \n\n elif menu == 4 :\n \n customer.Show()\n \n\n elif menu == 0 :\n break\n"} {"doc_id": "0947c980aac7351b403861d58a023e23", "text": "# This script contains a program for a simple guessing game!\n\n# Define a function `print_hot_or_cold()` that takes in two arguments (the `target`\n# and the `guess`), and prints out an appropriate message based on how close\n# the guess is to the target:\n#\n# Distance Message\n# -------------------\n# The same \"got it!\"\n# Within 1\t \"scalding hot\"\n# Within 3\t \"very warm\"\n# Within 5\t \"warm\"\n# Within 8\t \"cold\"\n# Within 13\t \"very cold\"\n# > 13 away\t \"icy freezing miserably cold\"\n#\n# Be sure to consider both positive AND negative distances!\n# BONUS: Also print out whether the guess is high or low\n\n\n\n# Define a function `guess_number()` that takes a single argument (a target number)\n# and prompts the user for a guess using the `input()` method. Your function should\n# then print how close the user's guess is (use your previous function!). Note that\n# you will need to convert the input into a number.\n#\n# Once you have a single guess working, modify your function so that the user can\n# make MULTIPLE guesses. You can either do this using a loop (see the next module)\n# or by simply calling your `guess_number() method again IF the user didn't get\n# the answer right. This is an example of **recursion**.\n\n\n\n# If the file is run as a top-level script, your script should pick a random number\n# between 1 and 50 as the target and then start the game. You should inform the\n# use of the range of numbers before asking them for a guess.\n"} {"doc_id": "0955212f3a235570dd6b1872c71a5677", "text": "#!/usr/bin/env python3\n\n\"\"\"\nCounting Subsets\n================\n\nGiven: A positive integer n (n\u22641000).\n\nReturn: The total number of subsets of {1,2,\u2026,n} modulo 1,000,000.\n(Including the empty set and the set itself.)\n\n\nSample Dataset\n--------------\n\n3\n\nSample Output\n-------------\n\n8\n\n\"\"\"\n\nimport sys\n#from math import factorial as fac\n\n# open a file and get n\nwith open(sys.argv[1], 'r') as in_file:\n n = int(in_file.read().strip())\n\n# this works, but...\n\"\"\"\n# count the subsets\nsubsets = 0\nfor k in range(0, n+1):\n subsets += (fac(n)//(fac(k)*fac(n-k)))\n\n# in Python, we can safely modulo in the very end\nprint(subsets % 1000000)\n\"\"\"\n\n# the mathematical truth is that the number\n# of subsets is equal to n!... and the pow\n# function in python supports modulo...\nprint(pow(2,n,1000000))\n"} {"doc_id": "0970655c2802f253988998e81bd964fd", "text": "\n## Python Crash Course\n\n# Exercise 6.7: People: \n# Start with the program you wrote for Exercise 6-1 (page 102). \n# Make two new dictionaries representing different people, and store all three dictionaries in a list called people. \n# Loop through your list of people. As you loop through the list, print everything you know about each person.\n#\n\n\ndef exercise_6_7():\n\n print(\"\\n\")\n \n myInfo = {\n 'first_name':'Akshay',\n 'last_name':'Moharir',\n 'age':29,\n 'city':'Novi'\n }\n\n yogeshInfo = {\n 'first_name':'Yogesh',\n 'last_name':'Dalal',\n 'age':29,\n 'city':'Novi'\n }\n\n manasiInfo = {\n 'first_name':'Manasi',\n 'last_name':'Kshirsagar',\n 'age':28,\n 'city':'Pune'\n }\n\n people = [myInfo, yogeshInfo, manasiInfo]\n\n for person in people:\n print(\"\\nFollowing is information about\",person['first_name'])\n print(\"Name:\", person['first_name'] + \" \" + person['last_name'])\n print(\"Age:\", person['age'])\n print(\"City:\", person['city'])\n print(\"***********************\")\n\n print(\"\\n\")\n\n\nif __name__ == '__main__':\n exercise_6_7()\n\n"} {"doc_id": "097e1d43b950fa9e7c8fa530925ceb92", "text": "'''\nDescription\n\nIn this exercise you will implement a Context Manger that can be used as a save\nfile for a game. Save files are a common implementation in the video game \nindustry and have several usages such as saving settings, campaign progress, \nuser info or changes in the game's layout. As the complexity can be immense \ndepending on scale, a simple implementation will here be used to store the \nusers' settings with their resolution, difficulty setting and their characters \nprogression in terms of level, name and how many hot dogs the character have ate\nso far.\nNote: In this exercise we will use the class-based approach as detailed above.\n\nSetup\n\u2022 Create a class called Character with three attributes, self._level, self._name\n and self._trait. Also create a property method allattributes that returns all \n the attributes formatted with newline between each (check example below)\n\u2022 Create a class called Settings with two attributes, self._resolution and \n self._difficulty. Also create a property method allsettings that returns \n [self._resolution + \"\\n\" + self._difficulty + \"\\n\"]\n\u2022 Create a context manager with the template above\n Note: Make these five attributes\u2019 properties by giving each of the variables \n a property method for retrieving their respective values, as discussed \n previously in the course this is a good practice.\n\n'''\n\n# https://www.pythontutorial.net/advanced-python/python-context-managers/\n\n# Method 4: Use the logging module\n# https://www.askpython.com/python/built-in-methods/python-print-to-file\n\n\nclass MyFileContextManager:\n def __init__(self, filename, operation):\n self._file = open(filename, operation)\n\n def __enter__(self):\n return self._file\n\n def __exit__(self, type, value, traceback):\n self._file.close()\n\n\nclass Character:\n # Create a class called Character with three attributes, self._level, self._name and self._trait.\n # w = write = ny fil -> filen finns inte eller skrivs \u00f6ver\n def __init__(self, level, name, trait):\n self._level = level\n self._name = name\n self._trait = trait\n with MyFileContextManager(\"game_data.txt\", 'w') as f:\n f.write(\"Attribute\\n\")\n f.write(str(self._level) + '\\n')\n f.write(self._name + '\\n')\n f.write(self._trait + '\\n')\n f.write(\"-------------------------\\n\")\n\n # By default, if the method is not a static python method, then implicitly\n # the object (self) is passed as argument.\n def allattributes(self):\n # Also create a property method allattributes that returns all\n # the attributes formatted with newline between each (check example below)\n with MyFileContextManager(\"game_data.txt\", 'r') as f:\n for row in f:\n print(row.strip()) # strip the newline character from the line\n\n\nclass Settings:\n # Create a class called Settings with two attributes, self._resolution and self._difficulty.\n # a = append , filen finns -> uppdateras, OBS att Character m\u00e5ste k\u00f6ras innan (skapa filen)\n def __init__(self, resolution, difficulty):\n self._resolution = resolution\n self._difficulty = difficulty\n with MyFileContextManager(\"game_data.txt\", 'a') as f:\n f.write(\"Graphics\\n\")\n f.write(self._resolution + '\\n')\n f.write(str(self._difficulty) + '\\n')\n f.write(\"-------------------------\\n\")\n\n def allsettings(self):\n # Also create a property method allsettings that returns [self._resolution + \"\\n\" + self._difficulty + \"\\n\"]\n skipp = bool\n with MyFileContextManager(\"game_data.txt\", 'r') as f:\n skipp = True\n for row in f:\n # hoppa fram i filen till Graphics..\n if skipp:\n if row == \"Graphics\\n\":\n print(row.strip())\n skipp = False\n else:\n # strip the newline character from the line\n print(row.strip())\n\n\n'''\nTasks\n\u2022 Create a character, set level and name to what you\u2019d like and trait to \n something that defines your character, for example I set mine to \"dogtamer\".\n\u2022 Create an instance of the Settings, resolution should be a string such \n as \"1280x720\" and difficulty in the range of 1-10\n\u2022 Using the contextmanager and the allsettings and allattributes methods \n write and create a file called saveFile.txt.\n'''\n\n# Create a character, set level and name to what you\u2019d like and trait to\n# something that defines your character,\nCharacter01 = Character(10, \"Char01\", \"atacker\")\nCharacter01.allattributes()\n\n# Create an instance of the Settings, resolution should be a string such as\n# \"1280x720\" and difficulty in the range of 1-10\nSettings01 = Settings(\"1280x720\", 5)\nSettings01.allsettings()\n# Using the contextmanager and the allsettings and allattributes methods\n# write and create a file called saveFile.txt.\n"} {"doc_id": "09cedd658b6f64ead5b5ecbaf7bc6f47", "text": "# if/else example\n\npassword = input(\"Enter your password: \")\nif password == \"secret\":\n print(\"That's correct, welcome!\")\nelse:\n print(\"Access denied.\")\n\n# elif example\n\nword = input(\"Enter something: \")\nprint(word)\nif word == \"hi\":\n print(\"Hi to you too!\")\nelif word == \"hello\":\n print(\"Hello hello!\")\nelse:\n print(\"I don't know what\", word, \"means.\")"} {"doc_id": "0a131087a4135d4b9a8ae8ea782c6e1f", "text": "# -*- coding: utf-8 -*-\n\"\"\"Points, Angles and Geographical Coordinates\n==============================================\n\"\"\"\nfrom math import radians, degrees, cos, sin, sqrt, pow, atan2\n\n\nclass Point(tuple):\n \"\"\"A Point in space (x, y, z).\"\"\"\n @property\n def x(self):\n return self[0]\n\n @property\n def y(self):\n return self[1]\n\n @property\n def z(self):\n return self[2]\n\n @property\n def radius(self):\n return sqrt(pow(self.x, 2) + pow(self.y, 2))\n\n @property\n def theta(self):\n return Angle.fromRadians(atan2(self.y, self.x))\n\n def __len__(self):\n return self.radius\n\n\nclass Angle(float):\n \"\"\"An Angle (in degrees) - a float with some extra methods.\"\"\"\n @classmethod\n def fromRadians(cls, radians):\n return cls(degrees(radians))\n\n @property\n def radians(self):\n \"\"\"Return the Angle in Radians.\"\"\"\n return radians(self)\n\n @property\n def cos(self):\n \"\"\"Return the cosine of the Angle.\"\"\"\n return cos(radians(self))\n\n @property\n def sin(self):\n \"\"\"Return the sine of the Angle.\"\"\"\n return sin(radians(self))\n\n @property\n def degrees(self):\n \"\"\"Return the whole number of Degrees in the Angle.\"\"\"\n return int(self)\n\n @property\n def minutes(self):\n \"\"\"Return the whole number of Minutes in the Angle.\"\"\"\n return int((self - self.degrees) / 60)\n\n @property\n def seconds(self):\n \"\"\"Return the number of Seconds in the Angle.\"\"\"\n return 0\n\n def __str__(self):\n return \"%d\u00b0 %d\u2032 %d\u2033\" % (self.degrees, self.minutes, self.seconds)\n # return \"%do %d' %d%s\" % (self.degrees, self.minutes, self.seconds, '\"')\n\n\nclass Coordinate(Point):\n \"\"\"Geographical Coordinate (Latitude, Longitude and Elevation).\n \"\"\"\n def __new__(self, (lat, lng, ele)):\n return Point.__new__(self, (Angle(lat), Angle(lng), ele))\n\n @property\n def latitude(self):\n \"\"\"Return the Latitude.\"\"\"\n return self[0]\n\n @property\n def longitude(self):\n \"\"\"Return the Longitude.\"\"\"\n return self[1]\n\n @property\n def elevation(self):\n \"\"\"Return the Elevation.\"\"\"\n return self[2]\n\n @property\n def northern(self):\n \"\"\"Return True if this is in the northern hemisphere.\"\"\"\n return (self.latitude >= 0)\n\n def __str__(self):\n return \"(%s, %s, %sm)\" % (self.latitude, self.longitude, self.elevation)\n"} {"doc_id": "0a1612dfd6fe6d9bd9e13e288a04effc", "text": "'''\nFind unpaired element\n\nGiven an array with odd number of elements, where (N - 1)/2 elements have duplicates and ONLY 1 is unique.\n\nInput: [1, 5, 3, 1, 5]\nOutput: 3\n\n=========================================\nUsing XOR find the unique element.\n* Example: 13 XOR 13 = 1101 XOR 1101 = 0.\n Time Complexity: O(N)\n Space Complexity: O(1)\n'''\n\n\n############\n# Solution #\n############\n\ndef find_unpaired_element(arr):\n unique = 0\n\n for el in arr:\n unique ^= el\n\n return unique\n\n\n###########\n# Testing #\n###########\n\n# Test 1\n# Correct result => 3\nprint(find_unpaired_element([1, 5, 3, 1, 5]))"} {"doc_id": "0a3c9a6da124f454d07fc0c9923b6fe2", "text": "'''\nGiven an integer array nums sorted in non-decreasing order and an integer target, return true if target is a majority element, or false otherwise.\n\nA majority element in an array nums is an element that appears more than nums.length / 2 times in the array.\n'''\n\nclass Solution:\n def isMajorityElement(self, nums: List[int], target: int) -> bool:\n \n l = len(nums)\n \n t_count = nums.count(target)\n \n if t_count > l/2:\n return True\n return False\n \n \n \n#another O log n\n\ndef isMajorityElement(self, nums, target):\n\n def search(a, x):\n lo, hi = 0, len(a)\n while lo < hi:\n mid = (lo + hi) // 2\n if a[mid] < x:\n lo = mid + 1\n else:\n hi = mid\n return lo\n \n N = len(nums)\n if nums[N // 2] != target:\n return False\n lo = search(nums, target)\n hi = search(nums, target + 1)\n return hi - lo > N // 2\n\n \n \n#-----------------------------\nDuring an interview, we would think a bit more. Letting x be our majority element, a sorted array containing a majority element would look like one of the following:\n\n[ x x x x x x x . . . . . . ] # majority at the beginning\n[ . . . x x x x x x x . . . ] # majority at the middle\n[ . . . . . . x x x x x x x ] # majority at the ending\nIf there is a majority element then when we examine the middle index of the array, we are guaranteed to find the majority element. So we can binary search for the beginning and end of the streak:\n\ndef isMajorityElement(self, nums, target):\n N = len(nums)\n if nums[N // 2] != target:\n return False\n lo = bisect.bisect_left(nums, target)\n hi = bisect.bisect_right(nums, target)\n return hi - lo > N // 2\n"} {"doc_id": "0a522f0786fdc9fb56ee1bbc9f810102", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n\n@author: Chris Lucas\n\"\"\"\n\nimport math\n\n\ndef distance(p1, p2):\n \"\"\"\n The euclidean distance between two points.\n\n Parameters\n ----------\n p1 : list or array\n A point in 2D space.\n p2 : list or array\n A point in 2D space.\n\n Returns\n -------\n distance : float\n The euclidean distance between the two points.\n \"\"\"\n return math.hypot(*(p1-p2))\n\n\ndef perpedicular_line(line, p):\n \"\"\"\n Returns a perpendicular line to a line at a point.\n\n Parameters\n ----------\n line : (1x3) array-like\n The a, b, and c coefficients (ax + by + c = 0) of a line.\n p : (1x2) array-like\n The coordinates of a point on the line.\n\n Returns\n -------\n line : (1x3) array-like\n The a, b, and c coefficients (ax + by + c = 0) of the line\n perpendicular to the input line at point p.\n \"\"\"\n a, b, c = line\n pa = b\n pb = -a\n pc = -(p[0] * b - p[1] * a)\n return [pa, pb, pc]\n"} {"doc_id": "0a9eda80472002e8094c871599ca9b5b", "text": "## -*- coding: utf-8 -*-\n\n\"\"\"\nfirst\n=====\n\nfirst is the function you always missed in Python.\n\nIn the simplest case, it returns the first true element from an iterable:\n\n>>> from first import first\n>>> first([0, False, None, [], (), 42])\n42\n\nOr None if there is none:\n\n>>> from first import first\n>>> first([]) is None\nTrue\n>>> first([0, False, None, [], ()]) is None\nTrue\n\nIt also supports the passing of a key argument to help selecting the first\nmatch in a more advanced way.\n\n>>> from first import first\n>>> first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0)\n4\n\n:copyright: (c) 2012 by Hynek Schlawack.\n:license: MIT, see LICENSE for more details.\n\n\"\"\"\n\n__title__ = 'first'\n__version__ = '2.0.1'\n__author__ = 'Hynek Schlawack'\n__license__ = 'MIT'\n__copyright__ = 'Copyright 2012\u20132013 Hynek Schlawack'\n\n\ndef first(iterable, default=None, key=None):\n \"\"\"\n Return first element of `iterable` that evaluates true, else return None\n (or an optional default value).\n\n >>> first([0, False, None, [], (), 42])\n 42\n\n >>> first([0, False, None, [], ()]) is None\n True\n\n >>> first([0, False, None, [], ()], default='ohai')\n 'ohai'\n\n >>> import re\n >>> m = first(re.match(regex, 'abc') for regex in ['b.*', 'a(.*)'])\n >>> m.group(1)\n 'bc'\n\n The optional `key` argument specifies a one-argument predicate function\n like that used for `filter()`. The `key` argument, if supplied, must be\n in keyword form. For example:\n\n >>> first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0)\n 4\n\n \"\"\"\n if key is None:\n for el in iterable:\n if el:\n return el\n else:\n for el in iterable:\n if key(el):\n return el\n\n return default\n"} {"doc_id": "0ab605b999dd4e56f258c1da421d3ca4", "text": "\"\"\"Utilities related to binary bits.\"\"\"\n\ndef bit(n):\n \"\"\"\n Parameters\n ----------\n n : :class:`int`\n The bit to set.\n\n Returns\n ------\n :class:`int`\n The number with the nth bit set.\n\n Examples\n --------\n >>> import dolor\n >>> dolor.util.bit(0)\n 1\n >>> dolor.util.bit(1)\n 2\n >>> dolor.util.bit(2)\n 4\n \"\"\"\n\n return (1 << n)\n\ndef to_signed(val, *, bits=32):\n \"\"\"Converts a number to its signed counterpart.\n\n Parameters\n ----------\n val : :class:`int`\n The value to convert.\n bits : :class:`int`, optional\n How many bits to use when converting\n ``val`` to its signed counterpart.\n\n Returns\n -------\n :class:`int`\n ``val``'s signed counterpart.\n\n Examples\n --------\n >>> import dolor\n >>> dolor.util.to_signed(2**32 - 1)\n -1\n >>> dolor.util.to_signed(2**64 - 1, bits=64)\n -1\n \"\"\"\n\n if val > bit(bits - 1) - 1:\n val -= bit(bits)\n\n return val\n\ndef to_unsigned(val, *, bits=32):\n \"\"\"Converts a number to its unsigned counterpart.\n\n Parameters\n ----------\n val : :class:`int`\n The value to convert.\n bits : :class:`int`, optional\n How many bits to use when converting\n ``val`` to its unsigned counterpart.\n\n Returns\n -------\n :class:`int`\n ``val``'s unsigned counterpart.\n\n Examples\n --------\n >>> import dolor\n >>> dolor.util.to_unsigned(-1)\n 4294967295\n >>> dolor.util.to_unsigned(-1, bits=64)\n 18446744073709551615\n \"\"\"\n\n if val < 0:\n val += bit(bits)\n\n return val\n\ndef urshift(val, n, *, bits=32):\n \"\"\"Performs an unsigned right shift on a number.\n\n Parameters\n ----------\n val : :class:`int`\n The value to shift.\n n : :class:`int`\n How many bits to shift ``val``.\n bits : :class:`int`, optional\n How many bits should be used for the \"unsigned\"\n part of \"unsigned right shift\".\n\n Returns\n -------\n :class:`int`\n The resulting unsigned right shifted number.\n\n Examples\n --------\n >>> import dolor\n >>> dolor.util.urshift(2, 1)\n 1\n >>> dolor.util.urshift(-1, 1)\n 2147483647\n >>> dolor.util.urshift(-1, 1, bits=64)\n 9223372036854775807\n \"\"\"\n\n return to_unsigned(val, bits=bits) >> n\n"} {"doc_id": "0b06caf58b411aac43b9c368d2c4f412", "text": "import math\n\n# Returns a bigger of the two numbers\ndef func1(x, y):\n if x >= y:\n return x\n return y\n\n\n# Returns a dictionary counting charaters in a string\ndef func2(s):\n d = dict()\n for c in set(s):\n d[c] = s.count(c)\n return d\n\n\n# Returns a squared root of a sum of squared numbers\ndef func3(*nums):\n squared_nums = [n**2 for n in nums]\n sum_squared_nums = sum(squared_nums)\n return math.sqrt(sum_squared_nums)\n\nprint(\"#==========================================\")\n\n# Convert func1() to a lambda expression\nlambda1 = lambda x, y: x if x >= y else y\nprint(str(func1(5, 4)) + ', ' + str(lambda1(5, 4)))\nprint(str(func1(4, 5)) + ', ' + str(lambda1(4, 5)))\n\nprint(\"#------------------------------\")\n\n# Convert func2() to a lambda expression\nlambda2 = lambda s: dict([(c, s.count(c)) for c in set(s)])\nprint(func2('DataCamp'))\nprint(lambda2('DataCamp'))\n\nprint(\"#------------------------------\")\n\n# Convert func3() to a lambda expression\nlambda3 = lambda *nums: math.sqrt(sum([n**2 for n in nums]))\nprint(str(func3(3, 4)) + ', ' + str(lambda3(3, 4)))\nprint(str(func3(3, 4, 5)) + ', ' + str(lambda3(3, 4, 5)))\n"} {"doc_id": "0b5a9244bc0073714b84b1710ae86f92", "text": "\"\"\"\nFile: anagram.py\nName: \u9ec3\u79d1\u8afa\n----------------------------------\nThis program recursively finds all the anagram(s)\nfor the word input by user and terminates when the\ninput string matches the EXIT constant defined\nat line 19\n\nIf you correctly implement this program, you should see the\nnumber of anagrams for each word listed below:\n * arm -> 3 anagrams\n * contains -> 5 anagrams\n * stop -> 6 anagrams\n * tesla -> 10 anagrams\n * spear -> 12 anagrams\n\"\"\"\n\n# Constants\nFILE = 'dictionary.txt' # This is the filename of an English dictionary\nEXIT = '-1' # Controls when to stop the loop\n\nword_list = []\n\n\ndef main():\n global word_list\n word_list = read_dictionary()\n print('Welcome to stanCode \"Anagram Generator\" (or -1 to quit)')\n while True:\n search_word = input('Find anagrams for: ')\n if search_word == EXIT:\n break\n else:\n anagram_list = find_anagrams(search_word)\n print(f'{len(anagram_list)} anagrams: {anagram_list}')\n\n\ndef read_dictionary():\n \"\"\"\n :return: list, containing all the words in the file 'dictionary.txt'\n \"\"\"\n with open(FILE, 'r') as f:\n for line in f:\n word = line.strip()\n word_list.append(word)\n return word_list\n\n\ndef find_anagrams(s):\n \"\"\"\n :param s: str, the input word\n :return: list, a list containing all the anagrams of the input word\n \"\"\"\n print('Searching...')\n return find_helper(s, [], [])\n\n\ndef find_helper(s, current, ana_list):\n \"\"\"\n :param s: str, the input word\n :param current: list, containing the permutations of characters in the input word saved in an index form\n :param ana_list: list, consisting of anagrams of the input word\n :return: a list containing all the anagrams of the input word\n \"\"\"\n if len(current) == len(s):\n str_current = ''\n for ele in current:\n str_current += s[ele]\n if str_current in word_list and str_current not in ana_list:\n print(f'Found: {str_current}')\n ana_list.append(str_current)\n print('Searching...')\n else:\n for i in range(len(s)):\n if len(current) < len(s):\n if i not in current:\n current.append(i)\n str_current = ''\n for ele in current:\n str_current += s[ele]\n # Choose\n if has_prefix(str_current):\n find_helper(s, current, ana_list)\n else:\n pass\n # # Explore\n current.pop()\n # Un-choose\n return ana_list\n\n\ndef has_prefix(sub_s):\n \"\"\"\n :param sub_s: str, a prefix to be tested\n :return: Boolean, indicating whether anagrams that start with the tested prefix exist\n \"\"\"\n for word in word_list:\n if word.startswith(sub_s):\n return True\n return False\n\n\nif __name__ == '__main__':\n main()\n"} {"doc_id": "0b6b51f32bd0cf535bffc7f08e9364c4", "text": "'''\nInterleaving Strings\n\nGiven are three strings A, B and C.\nC is said to be interleaving of A and B, if:\n- it contains all characters of A and B, and\n- order of all characters from A and B is preserved in C\nYour task is to count in how many ways C can be formed by interleaving of A and B.\n\nInput: A='xy', B= 'xz', C: 'xxyz'\nOutput: 2\nOutput explanation: \n 1) Take 'x' from A, then 'x' from B, then 'y' from A and at the end 'z' from B.\n 2) Take 'x' from B, then 'x' from A, then 'y' from A and at the end 'z' from B.\n\n=========================================\n2D Dynamic programming solution.\n Time Complexity: O(N*M)\n Space Complexity: O(N*M)\n1D Dynamic programming solution. Only the last two rows from the whole matrix are used, but that could be represented using only 1 row.\n Time Complexity: O(N*M)\n Space Complexity: O(M)\n'''\n\n##############\n# Solution 1 #\n##############\n\ndef interleaving_strings_1(A, B, C):\n nA, nB, nC = len(A), len(B), len(C)\n if nA + nB != nC:\n return 0\n \n dp = [[0 for j in range(nB + 1)] for i in range(nA + 1)]\n\n # starting values\n dp[0][0] = 1\n\n for i in range(1, nA + 1):\n if A[i - 1] == C[i - 1]:\n # short form of if A[i - 1] == C[i - 1] and dp[i - 1][0] == 1\n # dp[i][0] and dp[0][1] can be only 0 or 1\n dp[i][0] = dp[i - 1][0]\n\n for i in range(1, nB + 1):\n if B[i - 1] == C[i - 1]:\n dp[0][i] = dp[0][i - 1]\n \n # run dp\n for i in range(1, nA + 1):\n for j in range(1, nB + 1):\n if A[i - 1] == C[i + j - 1]:\n # look for the dp value from the previous position\n dp[i][j] += dp[i - 1][j]\n if B[j - 1] == C[i + j - 1]:\n # look for the dp value from the previous position\n dp[i][j] += dp[i][j - 1]\n\n return dp[nA][nB]\n\n\n##############\n# Solution 2 #\n##############\n\ndef interleaving_strings_2(A, B, C):\n nA, nB, nC = len(A), len(B), len(C)\n if nA + nB != nC:\n return 0\n \n dp = [0 for j in range(nB + 1)]\n\n # starting values\n dp[0] = 1\n\n for i in range(1, nB + 1):\n if B[i - 1] == C[i - 1]:\n dp[i] = dp[i - 1]\n \n # run dp\n for i in range(1, nA + 1):\n if A[i - 1] != C[i - 1]:\n # reset the value\n dp[0] = 0\n\n for j in range(1, nB + 1):\n if A[i - 1] != C[i + j - 1]:\n # reset the value\n dp[j] = 0\n if B[j - 1] == C[i + j - 1]:\n dp[j] += dp[j - 1]\n\n return dp[nB]\n\n\n###########\n# Testing #\n###########\n\n# Test 1\n# Correct result => 2\na, b, c = 'xy', 'xz', 'xxyz'\nprint(interleaving_strings_1(a, b, c))\nprint(interleaving_strings_2(a, b, c))"} {"doc_id": "0b94c53bd2c6247c5623049326dfb491", "text": "#########\n# Homework 2\n# Dalston Ward\n# August 10-11, 2014\n#########\n\nfrom random import uniform\n\n###########the main class for the homework\nclass Portfolio():\n\t\n#########required arguments are account holder (a name) and the initial deposit. \n\tdef __init__(self, account_holder, initial_deposit = 0):\n\t\tself.funds = initial_deposit\n\t\tself.stocks = {} #store stocks purchased here\n\t\tself.mutual_funds = {} #store mutual funds purchased here \n\t\tself.account_holder = account_holder \n\t\tself.history = History() #store account history here!\n\t\n############for making a deposit to the account\n\tdef addCash(self, amount):\n\t\t#try/except makes sure that you're giving the right input. \n\t\ttry:\n\t\t\tfloat(amount)\n\t\t\tif amount <= 0:\n\t\t\t\traise Exception \n\t\texcept:\n\t\t\tprint \"Not a valid amount of money. Please enter numeric characters greater than zero only.\"\n\t\t\traise Exception\n\t\tself.funds += amount\n\t\tself.history.log.append(\"$%.2f deposited. Available funds now $%.2f.\" % (amount, self.funds))\n\t\tprint \"Congrats! $%.2f added to your account. Total balance now $%.2f.\" % (amount, self.funds)\n\n############# for withdrawing funds from the account \t\t\n\tdef withdrawCash(self, amount):\n\t\ttry: #try/except to make sure you're giving the right input\n\t\t\tfloat(amount)\n\t\texcept:\n\t\t\tprint \"Not a valid amount of money. Please enter numeric characters only.\"\n\t\t\traise Exception\n\t\tif self.funds >= amount: # Can't take out more money than you're got! \n\t\t\tself.funds -= amount\n\t\t\tself.history.log.append(\"$%.2f withdrawn. Available funds now $%.2f.\" % (amount, self.funds))\n\t\t\tprint \"Congrats! $%.2f withdrawn from your account. Total balance now $%.2f.\" % (amount, self.funds)\n\t\telse:\n\t\t\tprint \"Withdraw amount exceeds account balance. Transaction not completed.\"\t\n\t\t\t\n######## function to buy some new stocks. \t\t\n\tdef buyStock(self, n_shares, stock_name):\n\t\ttry:\n\t\t\tint(n_shares) #can only buy integer numbers of stocks\n\t\t\tif n_shares <= 0:\n\t\t\t\traise Exception\n\t\texcept:\n\t\t\tprint \"Can only buy positive, whole number shares of stocks. Please enter a valid number of shares\"\n\t\t\traise Exception\n\t\tif n_shares * stock_name.price > self.funds:\n\t\t\tprint \"Can't complete transaction. Not enough funds!\"\n\t\telse:\n\t\t\tself.funds -= n_shares*stock_name.price #update funds\n\t\t\tif stock_name.tick_sym not in self.stocks.keys(): #create a key if not pre-existing\n\t\t\t\tself.stocks[stock_name.tick_sym] = n_shares\n\t\t\telse:\n\t\t\t\tself.stocks[stock_name.tick_sym] += n_shares #else update key\n\t\t\tself.history.log.append(\"%d share(s) of %s purchased.\" % (n_shares, stock_name.tick_sym))\n\t\t\tself.history.log.append(\"$%.2f used to purchased stock. Available funds now $%.2f.\" % (n_shares*stock_name.price, self.funds))\n\t\t\tprint \"Congrats! You purchased %d share(s) of %s at a total cost of $%.2f.\" % (n_shares, stock_name.tick_sym, n_shares * stock_name.price)\t\t\t\n\t\t\n#########function to sell stocks back. Takes as arguments the number of shares to sell and the stock to sell\n\tdef sellStock(self, n_shares, stock_name):\n\t\ttry: #make sure that its an integer number of shares and that you own that stock\n\t\t\tint(n_shares)\n\t\t\tif stock_name.tick_sym not in self.stocks.keys():\n\t\t\t\traise Exception\n\t\texcept:\n\t\t\tprint \"Can only sell whole shares of stocks in your portfolio. Please enter a valid number of shares a stock you own.\"\n\t\t\traise Exception\t\t\n\t\tif self.stocks[stock_name.tick_sym] < n_shares: #make sure that you aren't selling more shares than you own!\n\t\t\tprint \"Cannot sell more shares than you own! Transaction not completed.\"\n\t\telse:\t\t\n\t\t\tif self.stocks[stock_name.tick_sym] == n_shares: #remove this stock from your portfolio entirely if selling all shares \n\t\t\t\tself.stocks.pop(stock_name.tick_sym, None)\t\t\t\t\n\t\t\telse: #just update your number of shares\n\t\t\t\tself.stocks[stock_name.tick_sym] -= n_shares\t\t\t\n\t\t\tincome = n_shares * uniform(.5 * stock_name.price, 1.5 * stock_name.price) #sale price\n\t\t\tself.funds += income #update funds\n\t\t\tself.history.log.append(\"%d share(s) of %s sold.\" % (n_shares, stock_name.tick_sym))\n\t\t\tself.history.log.append(\"$%.2f earned from sale. Available funds now $%.2f.\" % (income, self.funds))\n\t\t\tprint \"Congrats! You earned $%.2f from this sale\" % income\n\n########## function to buy mutual funds. Takes as arguments how much to buy and which fund to purchase\n\tdef buyMutualFund(self, shares, mf_name):\n\t\ttry: #make sure that its an appropriate number of shares to purchase\n\t\t\tfloat(shares)\n\t\t\tif shares <= 0:\n\t\t\t\traise Exception\n\t\texcept:\n\t\t\tprint \"Can only buy positive shares of stocks. Please enter a valid number of shares.\"\n\t\t\traise Exception\t\n\t\tif shares > self.funds: #make sure you can afford this transaction\n\t\t\tprint \"Can't complete transaction. Not enough funds!\"\n\t\telse:\n\t\t\tself.funds -= shares #update funds\n\t\t\tif mf_name.tick_sym not in self.mutual_funds.keys(): #create a key if not pre-existing\n\t\t\t\tself.mutual_funds[mf_name.tick_sym] = shares\n\t\t\telse:\n\t\t\t\tself.mutual_funds[mf_name.tick_sym] += shares #else update key\n\t\t\tself.history.log.append(\"%d share(s) of %s purchased.\" % (shares, mf_name.tick_sym)) #update history\n\t\t\tself.history.log.append(\"$%.2f used to purchased mutual funds. Available funds now $%.2f.\" % (shares, self.funds)) #update history \n\t\t\tprint \"Congrats! You purchased %.f share(s) of %s at a total cost of $%.2f.\" % (shares, mf_name.tick_sym, shares)\t\t\n\n#########function to sell mutual funds shares back. Takes as arguments the number of shares to sell and the mutual fund to sell\n\tdef sellMutualFund(self, shares, mf_name):\n\t\ttry: #make sure that its a positive number and that you own that stock\n\t\t\tfloat(shares)\n\t\t\tif mf_name.tick_sym not in self.mutual_funds.keys():\n\t\t\t\traise Exception\n\t\t\tif shares <= 0:\n\t\t\t\traise Exception\n\t\texcept:\n\t\t\tprint \"Can only sell positive shares of mutual funds in your portfolio. Please enter a valid number of shares a mutual fund you own.\"\n\t\t\traise Exception\t\t\n\t\tif self.mutual_funds[mf_name.tick_sym] < shares: #make sure that you aren't selling more shares than you own!\n\t\t\tprint \"Cannot sell more shares than you own! Transaction not completed.\"\n\t\telse:\t\n\t\t\tif self.mutual_funds[mf_name.tick_sym] == shares: #remove this mutual fund from your portfolio entirely if selling all shares \n\t\t\t\tself.mutual_funds.pop(mf_name.tick_sym, None)\t\t\t\t\n\t\t\telse: #just update your number of shares\n\t\t\t\tself.mutual_funds[mf_name.tick_sym] -= shares\t\t\t\n\t\t\tincome = shares * uniform(0.9, 1.2) #sale price\n\t\t\tself.funds += income #update funds\n\t\t\tself.history.log.append(\"%d share(s) of %s sold.\" % (shares, mf_name.tick_sym)) #update history\n\t\t\tself.history.log.append(\"$%.2f earned from sale of mutual funds. Available funds now $%.2f.\" % (income, self.funds)) #update history. \n\t\t\tprint \"Congrats! You earned $%.2f from this sale\" % income\t\n\t\n######### function to print the portfolio\n\tdef __str__(self):\n\t\towner_print = \"Account holder: %s\\n\" % self.account_holder #Who's account?\n\t\tfunds_print = \"Available Funds: $%.2f \\n\" % self.funds #current balance\n\t\tstocks_print = \"Stocks: \\n\" #next two lines create owned stocks string\n\t\tfor stock in self.stocks:\n\t\t \t\tstocks_print += (\"\\t\" + str(self.stocks[stock]) + \" \" + stock + \"\\n\")\n\t\tmutual_funds_print = \"Mutual Funds: \\n\" #next two lines create owned MF's string\n\t\tfor mutual_fund in self.mutual_funds:\n\t\t\tmutual_funds_print += (\"\\t\" + str(self.mutual_funds[mutual_fund]) + \" \" + mutual_fund + \"\\n\")\n\t\treturn owner_print + funds_print + stocks_print + mutual_funds_print #put it all together and return. \t\t\n\n\t\t\nclass Stock():\n\tdef __init__(self, price, tick_sym):\n\t\ttry:\n\t\t\tif not isinstance(tick_sym, str): #Make sure the input is appropriate\n\t\t\t\traise Exception\n\t\texcept:\n\t\t\tprint \"Not a valid ticker symbol. Please enter a string.\"\n\t\t\traise Exception\n\t\ttry:\n\t\t\tfloat(price)\n\t\texcept: \n\t\t\tprint \"Not a valid stock price. Please enter numeric characters only\" \n\t\t\traise Exception\n\t\tself.tick_sym = tick_sym\n\t\tself.price = price\n\t\t\n\tdef __str__(self):\n\t\treturn \"Stock name: %s; Price per share: $%d\" % (self.tick_sym, self.price)\n\t\nclass MutualFund():\n\tdef __init__(self, tick_sym):\n\t\ttry:\n\t\t\tif not isinstance(tick_sym, str): #Make sure the input is appropriate\n\t\t\t\traise Exception\n\t\texcept:\n\t\t\tprint \"Not a valid ticker symbol. Please enter a string.\"\n\t\t\traise Exception\n\t\tself.tick_sym = tick_sym\n\t\n\tdef __str__(self):\n\t\treturn \"Mutual Fund name is %s.\" % self.tick_sym\n\n# I created the history class so that I could specify a specific way to print the history. \nclass History():\n\tdef __init__(self):\n\t\tself.log = []\n\t\n\tdef __str__(self):\n\t\treturn \"Transaction history: \\n\" + '\\n'.join(self.log)\t\t\t\t\n#\t\t\n# portfolio = Portfolio(\"Dalston Ward\")\n# portfolio.addCash(50)\n# print portfolio.funds\n# #portfolio.addCash(\"Fifty\")\n# #portfolio.addCash(-5)\n# stock = Stock(22, \"woo\")\n# stock2 = Stock(5, \"DGW\")\n# portfolio.buyStock(1, stock)\n# print portfolio.stocks\n# print portfolio\n# portfolio.addCash(50)\n# print portfolio.funds\n# portfolio.buyStock(1, stock)\n# print portfolio.stocks\n# portfolio.buyStock(3, stock2)\n# print portfolio.stocks\n# portfolio.sellStock(3, stock2)\n# print portfolio.stocks\n# portfolio.withdrawCash(2)\n# mf1 = MutualFund(\"HEY\")\n# mf2 = MutualFund(\"HO\")\n# portfolio.buyMutualFund(1.7,mf1)\n# print portfolio.mutual_funds\n# portfolio.sellMutualFund(.5, mf1)\n# portfolio.buyMutualFund(.9, mf2)\n# print portfolio.mutual_funds\n# print portfolio\n# portfolio.sellMutualFund(.5, mf1)\n# print portfolio\n# print portfolio.history\n# portfolio = Portfolio(\"Dalston Ward\")\n# portfolio.addCash(50)\n# print portfolio.history\n# \n# \n"} {"doc_id": "0bb8079f8cafcdee9fe00aa6c0fdc6e4", "text": "\"\"\"\r\nGet a reverse of list\r\n---------------------\r\n\r\nInput: (list) original list\r\n\r\nReturn: None\r\n\r\nOutput: list update the original lsit with the reversed elements \r\n\"\"\"\r\n\r\n# Original list\r\ncars = [\"Audi\", \"BMW\", \"Chrysler\", \"Dodge\"]\r\nprint('Original list: {}'.format(cars))\r\n\r\n# Using [::-1] slice operator to get back the reversed list \r\nreverse_1 = cars[::-1]\r\nprint('\\nReversed list (1): {}'.format(reverse_1))\r\n\r\n# Reverse function does not have any return value.\r\n# It updates the list with the reversed elements.\r\n# reverse_2 is used for demonstration purpose\r\n# since function is inplace, the \"cars.reverse()\" is enough to use\r\nreverse_2 = cars.reverse()\r\nprint('\\nReversed list (2): {}'.format(cars))\r\nprint('The return value of function is: {}'.format(reverse_2))\r\n"} {"doc_id": "0c0728b09a322e499bba5067c489ba21", "text": "\"\"\"\nName: Gibbs\nFile: caesar.py\n------------------------------\nThis program demonstrates the idea of caesar cipher.\nUsers will be asked to input a number to produce shifted\nALPHABET as the cipher table. After that, any strings typed\nin will be encrypted.\n\"\"\"\n\n\n# This constant shows the original order of alphabetic sequence.\nALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n\n\ndef main():\n \"\"\"\n This function can help to decipher any ciphered strings put in.\n \"\"\"\n secret = int(input('Secret number: ')) # decides new shifted order of the alphabetic sequence\n ciphered_string = input(\"What's the ciphered string? \")\n ciphered_string = ciphered_string.upper()\n ans = deciphered_string(ciphered_string, secret)\n print('The deciphered string is: '+ans)\n\n\ndef alphabet(secret):\n \"\"\"\n This function gets the new shifted alphabet sequence according to the rule.\n :param secret: the number to shift the alphabet sequence\n :return: a new shifted alphabet sequence\n \"\"\"\n new_alphabet = ''\n secret = secret % 26 # make sure the shift number in the range from 0 ~ 26\n new_alphabet += ALPHABET[26-secret:26]\n new_alphabet += ALPHABET[:26-secret]\n return new_alphabet\n\n\ndef deciphered_string(ciphered_string, secret):\n \"\"\"\n This function helps to get the deciphered string.\n :param secret: The number decides new shifted order of the alphabetic sequence.\n :param ciphered_string: the ciphered string required to be deciphered\n :return: the deciphered string\n \"\"\"\n new_alphabet = alphabet(secret)\n ans = ''\n for i in ciphered_string:\n if i in new_alphabet:\n j = new_alphabet.find(i)\n ans += ALPHABET[j]\n else:\n ans += i\n return ans\n\n\n\n##### DO NOT EDIT THE CODE BELOW THIS LINE #####\nif __name__ == '__main__':\n main()\n"} {"doc_id": "0c63e072ea885fec262ceef76f23a4a6", "text": "\"\"\"\nProblem #239: Sliding Window Maximum\n===================================\n\nYou are given an array of integers nums, there is a sliding window of size\nk which is moving from the very left of the array to the very right. You\ncan only see the k numbers in the window. Each time the sliding window\nmoves right by one position.\n\nReturn the max sliding window.\n\nExample 1:\n---------\n\nInput: nums = [1,3,-1,-3,5,3,6,7], k = 3\nOutput: [3,3,5,5,6,7]\nExplanation:\nWindow position Max\n--------------- -----\n[1 3 -1] -3 5 3 6 7 3\n 1 [3 -1 -3] 5 3 6 7 3\n 1 3 [-1 -3 5] 3 6 7 5\n 1 3 -1 [-3 5 3] 6 7 5\n 1 3 -1 -3 [5 3 6] 7 6\n 1 3 -1 -3 5 [3 6 7] 7\n\nExample 2:\n---------\nInput: nums = [1], k = 1\nOutput: [1]\n\nExample 3:\n---------\nInput: nums = [1,-1], k = 1\nOutput: [1,-1]\n\nExample 4:\n---------\nInput: nums = [9,11], k = 2\nOutput: [11]\n\nExample 5:\n---------\nInput: nums = [4,-2], k = 2\nOutput: [4]\n\n\nConstraints:\n-----------\n1 <= nums.length <= 105\n-104 <= nums[i] <= 104\n1 <= k <= nums.length\n\n\"\"\"\n\nfrom collections import deque\n\n\n# Time: O(n)\n# Space: O(k)\ndef sliding_window_max(nums, k):\n win = deque()\n acc = []\n\n for i, a in enumerate(nums):\n # enqueue\n while win and nums[win[-1]] <= a:\n win.pop()\n win.append(i)\n\n # find max\n if i >= k - 1:\n acc.append(win[0])\n\n # dequeue\n if win[0] <= i - k + 1:\n win.popleft()\n\n if len(nums) < k:\n acc.append(win[0])\n\n return acc\n\n\n"} {"doc_id": "0c7c3e4d8465b49c199bb25d86a219d9", "text": "\"\"\"\r\nThis is a program that will check how many times probably your password was exposed previously in data breaches.\r\n\r\nProgrammer: Hugo Le\u00e7a Ribeiro\r\nDate: 20/04/2020\r\n\"\"\"\r\n\r\nimport requests\r\nimport hashlib\r\nfrom time import sleep\r\n\r\n\r\ndef request_api_data(query_char):\r\n url = 'https://api.pwnedpasswords.com/range/' + query_char\r\n res = requests.get(url)\r\n if res.status_code != 200:\r\n raise RuntimeError(f'Error fetching: {res.status_code}, check the api and try again.')\r\n return res\r\n\r\n\r\n# This function will check how possibles times appears that password\r\ndef get_password_leaks_count(hashes, hash_to_check):\r\n hashes = (line.split(':') for line in hashes.text.splitlines())\r\n for h, count in hashes:\r\n if h == hash_to_check:\r\n return count\r\n return 0\r\n\r\n\r\n# Response is ok if it is equal to 200.\r\ndef pwned_api_check(password):\r\n sha1password = (hashlib.sha1(password.encode('utf-8')).hexdigest().upper())\r\n first5_char, tail = sha1password[:5], sha1password[5:]\r\n response = request_api_data(first5_char)\r\n return get_password_leaks_count(response, tail)\r\n\r\n\r\n# The main function here we will check each password inside the list of passwords.\r\ndef main(args):\r\n print('-' * 20)\r\n print(f'Ok. You inputted these passwords: {args}. \\nLets begin the test.\\n')\r\n for password in args:\r\n count = pwned_api_check(password)\r\n if count:\r\n print(f'{password} was found {count} times... \\033[1;31m you should probably change your password!\\033[m')\r\n else:\r\n print(f'{password} was NOT found. \\033[0;32mCarry on!\\033[m')\r\n sleep(1)\r\n return '\\nDone!'\r\n\r\n\r\n# A function to capture each password and put it into a list (passwords)\r\ndef capture_passwords():\r\n passwords = list()\r\n affirmative = ['YES', 'Y']\r\n negative = ['NO', 'N']\r\n try:\r\n keep_going = True\r\n while keep_going:\r\n password = str(input('Input here a password: '))\r\n passwords.append(password)\r\n while True:\r\n going = str(input('Do you want to input another password? [Y/N] ')).upper()\r\n if going in affirmative:\r\n break\r\n elif going in negative:\r\n keep_going = False\r\n break\r\n else:\r\n print('Sorry, wrong key was inputted. Try again!')\r\n return passwords\r\n except:\r\n print('Ow no, something went wrong!')\r\n\r\n\r\n# Main Program\r\nlist_passwords = capture_passwords()\r\nprint(main(list_passwords))\r\n"} {"doc_id": "0ca56bafc153acd6170e4381747cfedf", "text": "'''\n0. \u8bbe\u8ba1\u4e00\u4e2a\u9a8c\u8bc1\u7528\u6237\u5bc6\u7801\u7a0b\u5e8f\uff0c\u7528\u6237\u53ea\u6709\u4e09\u6b21\u673a\u4f1a\u8f93\u5165\u9519\u8bef\uff0c\u4e0d\u8fc7\u5982\u679c\u7528\u6237\u8f93\u5165\u7684\u5185\u5bb9\u4e2d\u5305\u542b\"*\"\u5219\u4e0d\u8ba1\u7b97\u5728\u5185\u3002\n\n1. \u7f16\u5199\u4e00\u4e2a\u7a0b\u5e8f\uff0c\u6c42 100~999 \u4e4b\u95f4\u7684\u6240\u6709\u6c34\u4ed9\u82b1\u6570\u3002\n\u5982\u679c\u4e00\u4e2a 3 \u4f4d\u6570\u7b49\u4e8e\u5176\u5404\u4f4d\u6570\u5b57\u7684\u7acb\u65b9\u548c\uff0c\u5219\u79f0\u8fd9\u4e2a\u6570\u4e3a\u6c34\u4ed9\u82b1\u6570\u3002\u4f8b\u5982\uff1a153 = 1^3 + 5^3 + 3^3\uff0c\u56e0\u6b64 153 \u5c31\u662f\u4e00\u4e2a\u6c34\u4ed9\u82b1\u6570\u3002\n\n2. \u4e09\u8272\u7403\u95ee\u9898\n\u6709\u7ea2\u3001\u9ec4\u3001\u7eff\u4e09\u79cd\u989c\u8272\u7684\u6c42\uff0c\u5176\u4e2d\u7ea2\u7403 3 \u4e2a\uff0c\u9ec4\u7403 3 \u4e2a\uff0c\u7eff\u7403 6 \u4e2a\u3002\u5148\u5c06\u8fd9 12 \u4e2a\u7403\u6df7\u5408\u653e\u5728\u4e00\u4e2a\u76d2\u5b50\u4e2d\uff0c\u4ece\u4e2d\u4efb\u610f\u6478\u51fa 8 \u4e2a\u7403\uff0c\u7f16\u7a0b\u8ba1\u7b97\u6478\u51fa\u7403\u7684\u5404\u79cd\u989c\u8272\u642d\u914d\u3002\n \u4e0d\u77e5\u9053\n\n3.\u8bf7\u5199\u4e0b\u8fd9\u4e00\u8282\u8bfe\u4f60\u5b66\u4e60\u5230\u7684\u5185\u5bb9\uff1a\u683c\u5f0f\u4e0d\u9650\uff0c\u56de\u5fc6\u5e76\u590d\u8ff0\u662f\u52a0\u5f3a\u8bb0\u5fc6\u7684\u597d\u65b9\u5f0f\uff01\n range()\n\n'''\n\n'''\norigin = '123456'\ncount = 3\nwhile True:\n pwd = input('\u8bf7\u8f93\u5165\u5bc6\u7801\uff1a')\n if origin == pwd:\n print('\u5bc6\u7801\u8f93\u5165\u6210\u529f')\n else:\n if pwd.__contains__('*'):\n print('\u5bc6\u7801\u8f93\u5165\u9519\u8bef')\n continue\n else:\n count -= 1\n if count <= 0:\n print('\u5bc6\u7801\u8f93\u5165\u9519\u8bef\u8d85\u8fc7\u4e09\u6b21\uff0c\u8d26\u6237\u88ab\u9501\u5b9a\uff01')\n break\n\n\nnum = 100\nwhile num < 1000:\n if (num / 100 * num / 100 + num / 10 * num / 10 + num % 100 * num % 100) == num:\n print(\"\u6c34\u4ed9\u82b1\u6570\u662f:\" + str(num))\n'''\n\nfor red in range(1, 4):\n for yellow in range(1, 4):\n for green in range(1,9):\n print(str(red) + str(yellow) + str(green))\n\ncount = 3\npassword = 'FishC.com'\nwhile count:\n passwd = input('\u8bf7\u8f93\u5165\u5bc6\u7801\uff1a')\n if passwd == password:\n print('\u5bc6\u7801\u6b63\u786e\uff0c\u8fdb\u5165\u7a0b\u5e8f......')\n break\n elif '*' in passwd:\n print('\u5bc6\u7801\u4e0d\u80fd\u542b\u6709\"*\"\u53f7\uff01\u60a8\u8fd8\u6709', count, '\u6b21\u673a\u4f1a\uff01', end=' ')\n continue\n else:\n print('\u5bc6\u7801\u8f93\u5165\u9519\u8bef\uff01\u60a8\u8fd8\u6709', count - 1, '\u6b21\u673a\u4f1a\uff01', end=' ')\n count -= 1\n\nfor i in range(100, 1000):\n sum = 0\n temp = i\n while temp:\n sum = sum + (temp%10) ** 3\n temp //= 10 #\u6ce8\u610f\u8fd9\u91cc\u8981\u662f\u7528\u5730\u677f\u9664\u54e6~\n if sum == i:\n print(i)\n\n# range(2,7)\u662f\u4ea7\u751f[2,3,4,5,6]5\u4e2a\u6570\uff0c\u7eff\u7403\u4e0d\u80fd\u662f1\u4e2a\uff0c\u4ee5\u4e3a\u5982\u679c\u7eff\u7403\u662f1\u4e2a\u7684\u8bdd\uff0c\n# \u7ea2\u7403+\u9ec4\u7403\u9700\u8981\u67097\u4e2a\u624d\u80fd\u7b26\u5408\u9898\u610f\uff0c\u800c\u7ea2\u7403\u548c\u9ec4\u7403\u6bcf\u79cd\u53ea\u67093\u4e2a\uff0c\u56e0\u6b64\u662frange(2,7)\nprint('red\\tyellow\\tgreen')\nfor red in range(0, 4):\n for yellow in range(0, 4):\n for green in range(2, 7):\n if red + yellow + green == 8:\n # \u6ce8\u610f\uff0c\u4e0b\u8fb9\u4e0d\u662f\u5b57\u7b26\u4e32\u62fc\u63a5\uff0c\u56e0\u6b64\u4e0d\u7528\u2018+\u2019\u54e6\n print(red, '\\t', yellow, '\\t', green)"} {"doc_id": "0ce6405bfb327501da96dc233578064a", "text": "print('=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=')\nprint('\\t <<<<<< AC04 - L\u00d3GICA DE PROGRAMA\u00c7\u00c3O >>>>>>')\nprint('-----------------------------------------------------------------')\nwhile True:\n try:\n n = int(input('Digite a quantidade de nomes da Lista: '))\n if 3 < n < 10:\n break\n else:\n print('Erro! Por favor, digite um valor entre 4 e 9.')\n print('-----------------------------------------------------------------')\n except:\n print('Erro! Por favor, digite um
Write a program to check whether a given number is an ugly number.
\n\nUgly numbers are positive numbers whose prime factors only include 2, 3, 5.
Example 1:
\n\n\nInput: 6\nOutput: true\nExplanation: 6 = 2 × 3\n\n
Example 2:
\n\n\nInput: 8\nOutput: true\nExplanation: 8 = 2 × 2 × 2\n\n\n
Example 3:
\n\n\nInput: 14\nOutput: false \nExplanation:\n\n14is not ugly since it includes another prime factor7.\n
Note:
\n\n1 is typically treated as an ugly number.\u7f16\u5199\u4e00\u4e2a\u7a0b\u5e8f\u5224\u65ad\u7ed9\u5b9a\u7684\u6570\u662f\u5426\u4e3a\u4e11\u6570\u3002
\n\n\u4e11\u6570\u5c31\u662f\u53ea\u5305\u542b\u8d28\u56e0\u6570 2, 3, 5 \u7684\u6b63\u6574\u6570\u3002
\u793a\u4f8b 1:
\n\n\u8f93\u5165: 6\n\u8f93\u51fa: true\n\u89e3\u91ca: 6 = 2 × 3\n\n
\u793a\u4f8b 2:
\n\n\u8f93\u5165: 8\n\u8f93\u51fa: true\n\u89e3\u91ca: 8 = 2 × 2 × 2\n\n\n
\u793a\u4f8b 3:
\n\n\u8f93\u5165: 14\n\u8f93\u51fa: false \n\u89e3\u91ca:\n\n14\u4e0d\u662f\u4e11\u6570\uff0c\u56e0\u4e3a\u5b83\u5305\u542b\u4e86\u53e6\u5916\u4e00\u4e2a\u8d28\u56e0\u65707\u3002
\u8bf4\u660e\uff1a
\n\n1 \u662f\u4e11\u6570\u3002\u7f16\u5199\u4e00\u4e2a\u7a0b\u5e8f\u5224\u65ad\u7ed9\u5b9a\u7684\u6570\u662f\u5426\u4e3a\u4e11\u6570\u3002
\n\n\u4e11\u6570\u5c31\u662f\u53ea\u5305\u542b\u8d28\u56e0\u6570 2, 3, 5 \u7684\u6b63\u6574\u6570\u3002
\u793a\u4f8b 1:
\n\n\u8f93\u5165: 6\n\u8f93\u51fa: true\n\u89e3\u91ca: 6 = 2 × 3\n\n
\u793a\u4f8b 2:
\n\n\u8f93\u5165: 8\n\u8f93\u51fa: true\n\u89e3\u91ca: 8 = 2 × 2 × 2\n\n\n
\u793a\u4f8b 3:
\n\n\u8f93\u5165: 14\n\u8f93\u51fa: false \n\u89e3\u91ca:\n\n14\u4e0d\u662f\u4e11\u6570\uff0c\u56e0\u4e3a\u5b83\u5305\u542b\u4e86\u53e6\u5916\u4e00\u4e2a\u8d28\u56e0\u65707\u3002
\u8bf4\u660e\uff1a
\n\n1 \u662f\u4e11\u6570\u3002In a given integer array nums, there is always exactly one largest element.
Find whether the largest element in the array is at least twice as much as every other number in the array.
\n\nIf it is, return the index of the largest element, otherwise return -1.
\n\nExample 1:
\n\n\nInput: nums = [3, 6, 1, 0]\nOutput: 1\nExplanation: 6 is the largest integer, and for every other number in the array x,\n6 is more than twice as big as x. The index of value 6 is 1, so we return 1.\n\n\n
\n\n
Example 2:
\n\n\nInput: nums = [1, 2, 3, 4]\nOutput: -1\nExplanation: 4 isn't at least as big as twice the value of 3, so we return -1.\n\n\n
\n\n
Note:
\n\nnums will have a length in the range [1, 50].nums[i] will be an integer in the range [0, 99].\n
\u5728\u4e00\u4e2a\u7ed9\u5b9a\u7684\u6570\u7ec4nums\u4e2d\uff0c\u603b\u662f\u5b58\u5728\u4e00\u4e2a\u6700\u5927\u5143\u7d20 \u3002
\u67e5\u627e\u6570\u7ec4\u4e2d\u7684\u6700\u5927\u5143\u7d20\u662f\u5426\u81f3\u5c11\u662f\u6570\u7ec4\u4e2d\u6bcf\u4e2a\u5176\u4ed6\u6570\u5b57\u7684\u4e24\u500d\u3002
\n\n\u5982\u679c\u662f\uff0c\u5219\u8fd4\u56de\u6700\u5927\u5143\u7d20\u7684\u7d22\u5f15\uff0c\u5426\u5219\u8fd4\u56de-1\u3002
\n\n\u793a\u4f8b 1:
\n\n\n\u8f93\u5165: nums = [3, 6, 1, 0]\n\u8f93\u51fa: 1\n\u89e3\u91ca: 6\u662f\u6700\u5927\u7684\u6574\u6570, \u5bf9\u4e8e\u6570\u7ec4\u4e2d\u7684\u5176\u4ed6\u6574\u6570,\n6\u5927\u4e8e\u6570\u7ec4\u4e2d\u5176\u4ed6\u5143\u7d20\u7684\u4e24\u500d\u30026\u7684\u7d22\u5f15\u662f1, \u6240\u4ee5\u6211\u4eec\u8fd4\u56de1.\n\n\n
\n\n
\u793a\u4f8b 2:
\n\n\n\u8f93\u5165: nums = [1, 2, 3, 4]\n\u8f93\u51fa: -1\n\u89e3\u91ca: 4\u6ca1\u6709\u8d85\u8fc73\u7684\u4e24\u500d\u5927, \u6240\u4ee5\u6211\u4eec\u8fd4\u56de -1.\n\n\n
\n\n
\u63d0\u793a:
\n\nnums \u7684\u957f\u5ea6\u8303\u56f4\u5728[1, 50].nums[i] \u7684\u6574\u6570\u8303\u56f4\u5728 [0, 99].\u5728\u4e00\u4e2a\u7ed9\u5b9a\u7684\u6570\u7ec4nums\u4e2d\uff0c\u603b\u662f\u5b58\u5728\u4e00\u4e2a\u6700\u5927\u5143\u7d20 \u3002
\u67e5\u627e\u6570\u7ec4\u4e2d\u7684\u6700\u5927\u5143\u7d20\u662f\u5426\u81f3\u5c11\u662f\u6570\u7ec4\u4e2d\u6bcf\u4e2a\u5176\u4ed6\u6570\u5b57\u7684\u4e24\u500d\u3002
\n\n\u5982\u679c\u662f\uff0c\u5219\u8fd4\u56de\u6700\u5927\u5143\u7d20\u7684\u7d22\u5f15\uff0c\u5426\u5219\u8fd4\u56de-1\u3002
\n\n\u793a\u4f8b 1:
\n\n\n\u8f93\u5165: nums = [3, 6, 1, 0]\n\u8f93\u51fa: 1\n\u89e3\u91ca: 6\u662f\u6700\u5927\u7684\u6574\u6570, \u5bf9\u4e8e\u6570\u7ec4\u4e2d\u7684\u5176\u4ed6\u6574\u6570,\n6\u5927\u4e8e\u6570\u7ec4\u4e2d\u5176\u4ed6\u5143\u7d20\u7684\u4e24\u500d\u30026\u7684\u7d22\u5f15\u662f1, \u6240\u4ee5\u6211\u4eec\u8fd4\u56de1.\n\n\n
\n\n
\u793a\u4f8b 2:
\n\n\n\u8f93\u5165: nums = [1, 2, 3, 4]\n\u8f93\u51fa: -1\n\u89e3\u91ca: 4\u6ca1\u6709\u8d85\u8fc73\u7684\u4e24\u500d\u5927, \u6240\u4ee5\u6211\u4eec\u8fd4\u56de -1.\n\n\n
\n\n
\u63d0\u793a:
\n\nnums \u7684\u957f\u5ea6\u8303\u56f4\u5728[1, 50].nums[i] \u7684\u6574\u6570\u8303\u56f4\u5728 [0, 99].Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
\nFind the maximum area of an island in the given 2D array.\n(If there is no island, the maximum area is 0.)\n
\nExample 1:
\n
\n[[0,0,1,0,0,0,0,1,0,0,0,0,0],\n [0,0,0,0,0,0,0,1,1,1,0,0,0],\n [0,1,1,0,1,0,0,0,0,0,0,0,0],\n [0,1,0,0,1,1,0,0,1,0,1,0,0],\n [0,1,0,0,1,1,0,0,1,1,1,0,0],\n [0,0,0,0,0,0,0,0,0,0,1,0,0],\n [0,0,0,0,0,0,0,1,1,1,0,0,0],\n [0,0,0,0,0,0,0,1,1,0,0,0,0]]\n\nGiven the above grid, return
6.\n\nNote the answer is not 11, because the island must be connected 4-directionally.\n\n\nExample 2:
\n
[[0,0,0,0,0,0,0,0]]\nGiven the above grid, return
0.\n\n\nNote:\nThe length of each dimension in the given grid does not exceed 50.\n
\u7ed9\u5b9a\u4e00\u4e2a\u5305\u542b\u4e86\u4e00\u4e9b 0 \u548c 1\u7684\u975e\u7a7a\u4e8c\u7ef4\u6570\u7ec4 grid , \u4e00\u4e2a \u5c9b\u5c7f \u662f\u7531\u56db\u4e2a\u65b9\u5411 (\u6c34\u5e73\u6216\u5782\u76f4) \u7684 1 (\u4ee3\u8868\u571f\u5730) \u6784\u6210\u7684\u7ec4\u5408\u3002\u4f60\u53ef\u4ee5\u5047\u8bbe\u4e8c\u7ef4\u77e9\u9635\u7684\u56db\u4e2a\u8fb9\u7f18\u90fd\u88ab\u6c34\u5305\u56f4\u7740\u3002
\u627e\u5230\u7ed9\u5b9a\u7684\u4e8c\u7ef4\u6570\u7ec4\u4e2d\u6700\u5927\u7684\u5c9b\u5c7f\u9762\u79ef\u3002(\u5982\u679c\u6ca1\u6709\u5c9b\u5c7f\uff0c\u5219\u8fd4\u56de\u9762\u79ef\u4e3a0\u3002)
\n\n\u793a\u4f8b 1:
\n\n\n[[0,0,1,0,0,0,0,1,0,0,0,0,0],\n [0,0,0,0,0,0,0,1,1,1,0,0,0],\n [0,1,1,0,1,0,0,0,0,0,0,0,0],\n [0,1,0,0,1,1,0,0,1,0,1,0,0],\n [0,1,0,0,1,1,0,0,1,1,1,0,0],\n [0,0,0,0,0,0,0,0,0,0,1,0,0],\n [0,0,0,0,0,0,0,1,1,1,0,0,0],\n [0,0,0,0,0,0,0,1,1,0,0,0,0]]\n\n\n
\u5bf9\u4e8e\u4e0a\u9762\u8fd9\u4e2a\u7ed9\u5b9a\u77e9\u9635\u5e94\u8fd4\u56de 6\u3002\u6ce8\u610f\u7b54\u6848\u4e0d\u5e94\u8be5\u662f11\uff0c\u56e0\u4e3a\u5c9b\u5c7f\u53ea\u80fd\u5305\u542b\u6c34\u5e73\u6216\u5782\u76f4\u7684\u56db\u4e2a\u65b9\u5411\u7684‘1’\u3002
\u793a\u4f8b 2:
\n\n\n[[0,0,0,0,0,0,0,0]]\n\n
\u5bf9\u4e8e\u4e0a\u9762\u8fd9\u4e2a\u7ed9\u5b9a\u7684\u77e9\u9635, \u8fd4\u56de 0\u3002
\u6ce8\u610f: \u7ed9\u5b9a\u7684\u77e9\u9635grid \u7684\u957f\u5ea6\u548c\u5bbd\u5ea6\u90fd\u4e0d\u8d85\u8fc7 50\u3002
\u7ed9\u5b9a\u4e00\u4e2a\u5305\u542b\u4e86\u4e00\u4e9b 0 \u548c 1\u7684\u975e\u7a7a\u4e8c\u7ef4\u6570\u7ec4 grid , \u4e00\u4e2a \u5c9b\u5c7f \u662f\u7531\u56db\u4e2a\u65b9\u5411 (\u6c34\u5e73\u6216\u5782\u76f4) \u7684 1 (\u4ee3\u8868\u571f\u5730) \u6784\u6210\u7684\u7ec4\u5408\u3002\u4f60\u53ef\u4ee5\u5047\u8bbe\u4e8c\u7ef4\u77e9\u9635\u7684\u56db\u4e2a\u8fb9\u7f18\u90fd\u88ab\u6c34\u5305\u56f4\u7740\u3002
\u627e\u5230\u7ed9\u5b9a\u7684\u4e8c\u7ef4\u6570\u7ec4\u4e2d\u6700\u5927\u7684\u5c9b\u5c7f\u9762\u79ef\u3002(\u5982\u679c\u6ca1\u6709\u5c9b\u5c7f\uff0c\u5219\u8fd4\u56de\u9762\u79ef\u4e3a0\u3002)
\n\n\u793a\u4f8b 1:
\n\n\n[[0,0,1,0,0,0,0,1,0,0,0,0,0],\n [0,0,0,0,0,0,0,1,1,1,0,0,0],\n [0,1,1,0,1,0,0,0,0,0,0,0,0],\n [0,1,0,0,1,1,0,0,1,0,1,0,0],\n [0,1,0,0,1,1,0,0,1,1,1,0,0],\n [0,0,0,0,0,0,0,0,0,0,1,0,0],\n [0,0,0,0,0,0,0,1,1,1,0,0,0],\n [0,0,0,0,0,0,0,1,1,0,0,0,0]]\n\n\n
\u5bf9\u4e8e\u4e0a\u9762\u8fd9\u4e2a\u7ed9\u5b9a\u77e9\u9635\u5e94\u8fd4\u56de 6\u3002\u6ce8\u610f\u7b54\u6848\u4e0d\u5e94\u8be5\u662f11\uff0c\u56e0\u4e3a\u5c9b\u5c7f\u53ea\u80fd\u5305\u542b\u6c34\u5e73\u6216\u5782\u76f4\u7684\u56db\u4e2a\u65b9\u5411\u7684‘1’\u3002
\u793a\u4f8b 2:
\n\n\n[[0,0,0,0,0,0,0,0]]\n\n
\u5bf9\u4e8e\u4e0a\u9762\u8fd9\u4e2a\u7ed9\u5b9a\u7684\u77e9\u9635, \u8fd4\u56de 0\u3002
\u6ce8\u610f: \u7ed9\u5b9a\u7684\u77e9\u9635grid \u7684\u957f\u5ea6\u548c\u5bbd\u5ea6\u90fd\u4e0d\u8d85\u8fc7 50\u3002
Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'.
\n'.' Matches any single character.\n'*' Matches zero or more of the preceding element.\n\n\n
The matching should cover the entire input string (not partial).
\n\nNote:
\n\ns could be empty and contains only lowercase letters a-z.p could be empty and contains only lowercase letters a-z, and characters like . or *.Example 1:
\n\n\nInput:\ns = "aa"\np = "a"\nOutput: false\nExplanation: "a" does not match the entire string "aa".\n\n\n
Example 2:
\n\n\nInput:\ns = "aa"\np = "a*"\nOutput: true\nExplanation: '*' means zero or more of the precedeng element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".\n\n\n
Example 3:
\n\n\nInput:\ns = "ab"\np = ".*"\nOutput: true\nExplanation: ".*" means "zero or more (*) of any character (.)".\n\n\n
Example 4:
\n\n\nInput:\ns = "aab"\np = "c*a*b"\nOutput: true\nExplanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches "aab".\n\n\n
Example 5:
\n\n\nInput:\ns = "mississippi"\np = "mis*is*p*."\nOutput: false\n\n
\u7ed9\u5b9a\u4e00\u4e2a\u5b57\u7b26\u4e32 (s) \u548c\u4e00\u4e2a\u5b57\u7b26\u6a21\u5f0f (p)\u3002\u5b9e\u73b0\u652f\u6301 '.' \u548c '*' \u7684\u6b63\u5219\u8868\u8fbe\u5f0f\u5339\u914d\u3002
'.' \u5339\u914d\u4efb\u610f\u5355\u4e2a\u5b57\u7b26\u3002\n'*' \u5339\u914d\u96f6\u4e2a\u6216\u591a\u4e2a\u524d\u9762\u7684\u5143\u7d20\u3002\n\n\n
\u5339\u914d\u5e94\u8be5\u8986\u76d6\u6574\u4e2a\u5b57\u7b26\u4e32 (s) \uff0c\u800c\u4e0d\u662f\u90e8\u5206\u5b57\u7b26\u4e32\u3002
\u8bf4\u660e:
\n\ns \u53ef\u80fd\u4e3a\u7a7a\uff0c\u4e14\u53ea\u5305\u542b\u4ece a-z \u7684\u5c0f\u5199\u5b57\u6bcd\u3002p \u53ef\u80fd\u4e3a\u7a7a\uff0c\u4e14\u53ea\u5305\u542b\u4ece a-z \u7684\u5c0f\u5199\u5b57\u6bcd\uff0c\u4ee5\u53ca\u5b57\u7b26 . \u548c *\u3002\u793a\u4f8b 1:
\n\n\u8f93\u5165:\ns = "aa"\np = "a"\n\u8f93\u51fa: false\n\u89e3\u91ca: "a" \u65e0\u6cd5\u5339\u914d "aa" \u6574\u4e2a\u5b57\u7b26\u4e32\u3002\n\n\n
\u793a\u4f8b 2:
\n\n\u8f93\u5165:\ns = "aa"\np = "a*"\n\u8f93\u51fa: true\n\u89e3\u91ca: '*' \u4ee3\u8868\u53ef\u5339\u914d\u96f6\u4e2a\u6216\u591a\u4e2a\u524d\u9762\u7684\u5143\u7d20, \u5373\u53ef\u4ee5\u5339\u914d 'a' \u3002\u56e0\u6b64, \u91cd\u590d 'a' \u4e00\u6b21, \u5b57\u7b26\u4e32\u53ef\u53d8\u4e3a "aa"\u3002\n\n\n
\u793a\u4f8b 3:
\n\n\u8f93\u5165:\ns = "ab"\np = ".*"\n\u8f93\u51fa: true\n\u89e3\u91ca: ".*" \u8868\u793a\u53ef\u5339\u914d\u96f6\u4e2a\u6216\u591a\u4e2a('*')\u4efb\u610f\u5b57\u7b26('.')\u3002\n\n\n\u793a\u4f8b 4:
\n\n\u8f93\u5165:\ns = "aab"\np = "c*a*b"\n\u8f93\u51fa: true\n\u89e3\u91ca: 'c' \u53ef\u4ee5\u4e0d\u88ab\u91cd\u590d, 'a' \u53ef\u4ee5\u88ab\u91cd\u590d\u4e00\u6b21\u3002\u56e0\u6b64\u53ef\u4ee5\u5339\u914d\u5b57\u7b26\u4e32 "aab"\u3002\n\n\n
\u793a\u4f8b 5:
\n\n\u8f93\u5165:\ns = "mississippi"\np = "mis*is*p*."\n\u8f93\u51fa: false\n
\u7ed9\u5b9a\u4e00\u4e2a\u5b57\u7b26\u4e32 (s) \u548c\u4e00\u4e2a\u5b57\u7b26\u6a21\u5f0f (p)\u3002\u5b9e\u73b0\u652f\u6301 '.' \u548c '*' \u7684\u6b63\u5219\u8868\u8fbe\u5f0f\u5339\u914d\u3002
'.' \u5339\u914d\u4efb\u610f\u5355\u4e2a\u5b57\u7b26\u3002\n'*' \u5339\u914d\u96f6\u4e2a\u6216\u591a\u4e2a\u524d\u9762\u7684\u5143\u7d20\u3002\n\n\n
\u5339\u914d\u5e94\u8be5\u8986\u76d6\u6574\u4e2a\u5b57\u7b26\u4e32 (s) \uff0c\u800c\u4e0d\u662f\u90e8\u5206\u5b57\u7b26\u4e32\u3002
\u8bf4\u660e:
\n\ns \u53ef\u80fd\u4e3a\u7a7a\uff0c\u4e14\u53ea\u5305\u542b\u4ece a-z \u7684\u5c0f\u5199\u5b57\u6bcd\u3002p \u53ef\u80fd\u4e3a\u7a7a\uff0c\u4e14\u53ea\u5305\u542b\u4ece a-z \u7684\u5c0f\u5199\u5b57\u6bcd\uff0c\u4ee5\u53ca\u5b57\u7b26 . \u548c *\u3002\u793a\u4f8b 1:
\n\n\u8f93\u5165:\ns = "aa"\np = "a"\n\u8f93\u51fa: false\n\u89e3\u91ca: "a" \u65e0\u6cd5\u5339\u914d "aa" \u6574\u4e2a\u5b57\u7b26\u4e32\u3002\n\n\n
\u793a\u4f8b 2:
\n\n\u8f93\u5165:\ns = "aa"\np = "a*"\n\u8f93\u51fa: true\n\u89e3\u91ca: '*' \u4ee3\u8868\u53ef\u5339\u914d\u96f6\u4e2a\u6216\u591a\u4e2a\u524d\u9762\u7684\u5143\u7d20, \u5373\u53ef\u4ee5\u5339\u914d 'a' \u3002\u56e0\u6b64, \u91cd\u590d 'a' \u4e00\u6b21, \u5b57\u7b26\u4e32\u53ef\u53d8\u4e3a "aa"\u3002\n\n\n
\u793a\u4f8b 3:
\n\n\u8f93\u5165:\ns = "ab"\np = ".*"\n\u8f93\u51fa: true\n\u89e3\u91ca: ".*" \u8868\u793a\u53ef\u5339\u914d\u96f6\u4e2a\u6216\u591a\u4e2a('*')\u4efb\u610f\u5b57\u7b26('.')\u3002\n\n\n\u793a\u4f8b 4:
\n\n\u8f93\u5165:\ns = "aab"\np = "c*a*b"\n\u8f93\u51fa: true\n\u89e3\u91ca: 'c' \u53ef\u4ee5\u4e0d\u88ab\u91cd\u590d, 'a' \u53ef\u4ee5\u88ab\u91cd\u590d\u4e00\u6b21\u3002\u56e0\u6b64\u53ef\u4ee5\u5339\u914d\u5b57\u7b26\u4e32 "aab"\u3002\n\n\n
\u793a\u4f8b 5:
\n\n\u8f93\u5165:\ns = "mississippi"\np = "mis*is*p*."\n\u8f93\u51fa: false\n\"\"\"\n\n\nclass Solution(object):\n def isMatch(self, s, p):\n \"\"\"\n :type s: str\n :type p: str\n :rtype: bool\n \"\"\"\n "} {"doc_id": "11dd53c78a65717ce22687e53ce4d4dd", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # Coding Exercises (Part 2)\n\n# ## Full Data Workflow A-Z: Cleaning Data\n\n# ### Exercise 11: Cleaning messy Data\n\n# Now, you will have the opportunity to analyze your own dataset.
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
\n\nThe update(i, val) function modifies nums by updating the element at index i to val.
\n\nExample:
\n\n\nGiven nums = [1, 3, 5]\n\nsumRange(0, 2) -> 9\nupdate(1, 2)\nsumRange(0, 2) -> 8\n\n\n
Note:
\n\n\u7ed9\u5b9a\u4e00\u4e2a\u6574\u6570\u6570\u7ec4 nums\uff0c\u6c42\u51fa\u6570\u7ec4\u4ece\u7d22\u5f15 i \u5230 j (i ≤ j) \u8303\u56f4\u5185\u5143\u7d20\u7684\u603b\u548c\uff0c\u5305\u542b i, j \u4e24\u70b9\u3002
\n\nupdate(i, val) \u51fd\u6570\u53ef\u4ee5\u901a\u8fc7\u5c06\u4e0b\u6807\u4e3a i \u7684\u6570\u503c\u66f4\u65b0\u4e3a val\uff0c\u4ece\u800c\u5bf9\u6570\u5217\u8fdb\u884c\u4fee\u6539\u3002
\n\n\u793a\u4f8b:
\n\nGiven nums = [1, 3, 5]\n\nsumRange(0, 2) -> 9\nupdate(1, 2)\nsumRange(0, 2) -> 8\n\n\n
\u8bf4\u660e:
\n\n\u7ed9\u5b9a\u4e00\u4e2a\u6574\u6570\u6570\u7ec4 nums\uff0c\u6c42\u51fa\u6570\u7ec4\u4ece\u7d22\u5f15 i \u5230 j (i ≤ j) \u8303\u56f4\u5185\u5143\u7d20\u7684\u603b\u548c\uff0c\u5305\u542b i, j \u4e24\u70b9\u3002
\n\nupdate(i, val) \u51fd\u6570\u53ef\u4ee5\u901a\u8fc7\u5c06\u4e0b\u6807\u4e3a i \u7684\u6570\u503c\u66f4\u65b0\u4e3a val\uff0c\u4ece\u800c\u5bf9\u6570\u5217\u8fdb\u884c\u4fee\u6539\u3002
\n\n\u793a\u4f8b:
\n\nGiven nums = [1, 3, 5]\n\nsumRange(0, 2) -> 9\nupdate(1, 2)\nsumRange(0, 2) -> 8\n\n\n
\u8bf4\u660e:
\n\nGiven a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words. It is guaranteed there is at least one word that isn't banned, and that the answer is unique.
\n\nWords in the list of banned words are given in lowercase, and free of punctuation. Words in the paragraph are not case sensitive. The answer is in lowercase.
\n\n\nExample:\nInput: \nparagraph = "Bob hit a ball, the hit BALL flew far after it was hit."\nbanned = ["hit"]\nOutput: "ball"\nExplanation: \n"hit" occurs 3 times, but it is a banned word.\n"ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph. \nNote that words in the paragraph are not case sensitive,\nthat punctuation is ignored (even if adjacent to words, such as "ball,"), \nand that "hit" isn't the answer even though it occurs more because it is banned.\n\n\n
\n\n
Note:
\n\n1 <= paragraph.length <= 1000.1 <= banned.length <= 100.1 <= banned[i].length <= 10.paragraph may have uppercase symbols, and even if it is a proper noun.)paragraph only consists of letters, spaces, or the punctuation symbols !?',;.paragraph are always separated by a space.
\u7ed9\u5b9a\u4e00\u4e2a\u6bb5\u843d (paragraph) \u548c\u4e00\u4e2a\u7981\u7528\u5355\u8bcd\u5217\u8868 (banned)\u3002\u8fd4\u56de\u51fa\u73b0\u6b21\u6570\u6700\u591a\uff0c\u540c\u65f6\u4e0d\u5728\u7981\u7528\u5217\u8868\u4e2d\u7684\u5355\u8bcd\u3002\u9898\u76ee\u4fdd\u8bc1\u81f3\u5c11\u6709\u4e00\u4e2a\u8bcd\u4e0d\u5728\u7981\u7528\u5217\u8868\u4e2d\uff0c\u800c\u4e14\u7b54\u6848\u552f\u4e00\u3002
\n\n\u7981\u7528\u5217\u8868\u4e2d\u7684\u5355\u8bcd\u7528\u5c0f\u5199\u5b57\u6bcd\u8868\u793a\uff0c\u4e0d\u542b\u6807\u70b9\u7b26\u53f7\u3002\u6bb5\u843d\u4e2d\u7684\u5355\u8bcd\u4e0d\u533a\u5206\u5927\u5c0f\u5199\u3002\u7b54\u6848\u90fd\u662f\u5c0f\u5199\u5b57\u6bcd\u3002
\n\n\n\u793a\u4f8b:\n\u8f93\u5165: \nparagraph = "Bob hit a ball, the hit BALL flew far after it was hit."\nbanned = ["hit"]\n\u8f93\u51fa: "ball"\n\u89e3\u91ca: \n"hit" \u51fa\u73b0\u4e863\u6b21\uff0c\u4f46\u5b83\u662f\u4e00\u4e2a\u7981\u7528\u7684\u5355\u8bcd\u3002\n"ball" \u51fa\u73b0\u4e862\u6b21 (\u540c\u65f6\u6ca1\u6709\u5176\u4ed6\u5355\u8bcd\u51fa\u73b02\u6b21)\uff0c\u6240\u4ee5\u5b83\u662f\u6bb5\u843d\u91cc\u51fa\u73b0\u6b21\u6570\u6700\u591a\u7684\uff0c\u4e14\u4e0d\u5728\u7981\u7528\u5217\u8868\u4e2d\u7684\u5355\u8bcd\u3002 \n\u6ce8\u610f\uff0c\u6240\u6709\u8fd9\u4e9b\u5355\u8bcd\u5728\u6bb5\u843d\u91cc\u4e0d\u533a\u5206\u5927\u5c0f\u5199\uff0c\u6807\u70b9\u7b26\u53f7\u9700\u8981\u5ffd\u7565\uff08\u5373\u4f7f\u662f\u7d27\u6328\u7740\u5355\u8bcd\u4e5f\u5ffd\u7565\uff0c \u6bd4\u5982 "ball,"\uff09\uff0c \n"hit"\u4e0d\u662f\u6700\u7ec8\u7684\u7b54\u6848\uff0c\u867d\u7136\u5b83\u51fa\u73b0\u6b21\u6570\u66f4\u591a\uff0c\u4f46\u5b83\u5728\u7981\u7528\u5355\u8bcd\u5217\u8868\u4e2d\u3002\n\n\n
\u8bf4\u660e:
\n\n1 <= \u6bb5\u843d\u957f\u5ea6 <= 1000.1 <= \u7981\u7528\u5355\u8bcd\u4e2a\u6570 <= 100.1 <= \u7981\u7528\u5355\u8bcd\u957f\u5ea6 <= 10.paragraph \u91cc\u662f\u5927\u5199\u7684\uff0c\u5373\u4f7f\u662f\u4e00\u4e9b\u7279\u5b9a\u7684\u540d\u8bcd\uff0c\u7b54\u6848\u90fd\u662f\u5c0f\u5199\u7684\u3002)paragraph \u53ea\u5305\u542b\u5b57\u6bcd\u3001\u7a7a\u683c\u548c\u4e0b\u5217\u6807\u70b9\u7b26\u53f7!?',;.paragraph \u91cc\u5355\u8bcd\u4e4b\u95f4\u90fd\u7531\u7a7a\u683c\u9694\u5f00\u3002\u7ed9\u5b9a\u4e00\u4e2a\u6bb5\u843d (paragraph) \u548c\u4e00\u4e2a\u7981\u7528\u5355\u8bcd\u5217\u8868 (banned)\u3002\u8fd4\u56de\u51fa\u73b0\u6b21\u6570\u6700\u591a\uff0c\u540c\u65f6\u4e0d\u5728\u7981\u7528\u5217\u8868\u4e2d\u7684\u5355\u8bcd\u3002\u9898\u76ee\u4fdd\u8bc1\u81f3\u5c11\u6709\u4e00\u4e2a\u8bcd\u4e0d\u5728\u7981\u7528\u5217\u8868\u4e2d\uff0c\u800c\u4e14\u7b54\u6848\u552f\u4e00\u3002
\n\n\u7981\u7528\u5217\u8868\u4e2d\u7684\u5355\u8bcd\u7528\u5c0f\u5199\u5b57\u6bcd\u8868\u793a\uff0c\u4e0d\u542b\u6807\u70b9\u7b26\u53f7\u3002\u6bb5\u843d\u4e2d\u7684\u5355\u8bcd\u4e0d\u533a\u5206\u5927\u5c0f\u5199\u3002\u7b54\u6848\u90fd\u662f\u5c0f\u5199\u5b57\u6bcd\u3002
\n\n\n\u793a\u4f8b:\n\u8f93\u5165: \nparagraph = "Bob hit a ball, the hit BALL flew far after it was hit."\nbanned = ["hit"]\n\u8f93\u51fa: "ball"\n\u89e3\u91ca: \n"hit" \u51fa\u73b0\u4e863\u6b21\uff0c\u4f46\u5b83\u662f\u4e00\u4e2a\u7981\u7528\u7684\u5355\u8bcd\u3002\n"ball" \u51fa\u73b0\u4e862\u6b21 (\u540c\u65f6\u6ca1\u6709\u5176\u4ed6\u5355\u8bcd\u51fa\u73b02\u6b21)\uff0c\u6240\u4ee5\u5b83\u662f\u6bb5\u843d\u91cc\u51fa\u73b0\u6b21\u6570\u6700\u591a\u7684\uff0c\u4e14\u4e0d\u5728\u7981\u7528\u5217\u8868\u4e2d\u7684\u5355\u8bcd\u3002 \n\u6ce8\u610f\uff0c\u6240\u6709\u8fd9\u4e9b\u5355\u8bcd\u5728\u6bb5\u843d\u91cc\u4e0d\u533a\u5206\u5927\u5c0f\u5199\uff0c\u6807\u70b9\u7b26\u53f7\u9700\u8981\u5ffd\u7565\uff08\u5373\u4f7f\u662f\u7d27\u6328\u7740\u5355\u8bcd\u4e5f\u5ffd\u7565\uff0c \u6bd4\u5982 "ball,"\uff09\uff0c \n"hit"\u4e0d\u662f\u6700\u7ec8\u7684\u7b54\u6848\uff0c\u867d\u7136\u5b83\u51fa\u73b0\u6b21\u6570\u66f4\u591a\uff0c\u4f46\u5b83\u5728\u7981\u7528\u5355\u8bcd\u5217\u8868\u4e2d\u3002\n\n\n
\u8bf4\u660e:
\n\n1 <= \u6bb5\u843d\u957f\u5ea6 <= 1000.1 <= \u7981\u7528\u5355\u8bcd\u4e2a\u6570 <= 100.1 <= \u7981\u7528\u5355\u8bcd\u957f\u5ea6 <= 10.paragraph \u91cc\u662f\u5927\u5199\u7684\uff0c\u5373\u4f7f\u662f\u4e00\u4e9b\u7279\u5b9a\u7684\u540d\u8bcd\uff0c\u7b54\u6848\u90fd\u662f\u5c0f\u5199\u7684\u3002)paragraph \u53ea\u5305\u542b\u5b57\u6bcd\u3001\u7a7a\u683c\u548c\u4e0b\u5217\u6807\u70b9\u7b26\u53f7!?',;.paragraph \u91cc\u5355\u8bcd\u4e4b\u95f4\u90fd\u7531\u7a7a\u683c\u9694\u5f00\u3002In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data.\n
\n\n\nYou're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.
\n\nThe reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were.\n
\n\n\nIf the 'reshape' operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.\n
\n\nExample 1:
\n
\nInput: \nnums = \n[[1,2],\n [3,4]]\nr = 1, c = 4\nOutput: \n[[1,2,3,4]]\nExplanation:\n\n\n
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.\n
Example 2:
\n
\nInput: \nnums = \n[[1,2],\n [3,4]]\nr = 2, c = 4\nOutput: \n[[1,2],\n [3,4]]\nExplanation:\n\n\n
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.\n
Note:
\n
\u5728MATLAB\u4e2d\uff0c\u6709\u4e00\u4e2a\u975e\u5e38\u6709\u7528\u7684\u51fd\u6570 reshape\uff0c\u5b83\u53ef\u4ee5\u5c06\u4e00\u4e2a\u77e9\u9635\u91cd\u5851\u4e3a\u53e6\u4e00\u4e2a\u5927\u5c0f\u4e0d\u540c\u7684\u65b0\u77e9\u9635\uff0c\u4f46\u4fdd\u7559\u5176\u539f\u59cb\u6570\u636e\u3002
\u7ed9\u51fa\u4e00\u4e2a\u7531\u4e8c\u7ef4\u6570\u7ec4\u8868\u793a\u7684\u77e9\u9635\uff0c\u4ee5\u53ca\u4e24\u4e2a\u6b63\u6574\u6570r\u548cc\uff0c\u5206\u522b\u8868\u793a\u60f3\u8981\u7684\u91cd\u6784\u7684\u77e9\u9635\u7684\u884c\u6570\u548c\u5217\u6570\u3002
\u91cd\u6784\u540e\u7684\u77e9\u9635\u9700\u8981\u5c06\u539f\u59cb\u77e9\u9635\u7684\u6240\u6709\u5143\u7d20\u4ee5\u76f8\u540c\u7684\u884c\u904d\u5386\u987a\u5e8f\u586b\u5145\u3002
\n\n\u5982\u679c\u5177\u6709\u7ed9\u5b9a\u53c2\u6570\u7684reshape\u64cd\u4f5c\u662f\u53ef\u884c\u4e14\u5408\u7406\u7684\uff0c\u5219\u8f93\u51fa\u65b0\u7684\u91cd\u5851\u77e9\u9635\uff1b\u5426\u5219\uff0c\u8f93\u51fa\u539f\u59cb\u77e9\u9635\u3002
\u793a\u4f8b 1:
\n\n\n\u8f93\u5165: \nnums = \n[[1,2],\n [3,4]]\nr = 1, c = 4\n\u8f93\u51fa: \n[[1,2,3,4]]\n\u89e3\u91ca:\n\u884c\u904d\u5386nums\u7684\u7ed3\u679c\u662f [1,2,3,4]\u3002\u65b0\u7684\u77e9\u9635\u662f 1 * 4 \u77e9\u9635, \u7528\u4e4b\u524d\u7684\u5143\u7d20\u503c\u4e00\u884c\u4e00\u884c\u586b\u5145\u65b0\u77e9\u9635\u3002\n\n\n
\u793a\u4f8b 2:
\n\n\n\u8f93\u5165: \nnums = \n[[1,2],\n [3,4]]\nr = 2, c = 4\n\u8f93\u51fa: \n[[1,2],\n [3,4]]\n\u89e3\u91ca:\n\u6ca1\u6709\u529e\u6cd5\u5c06 2 * 2 \u77e9\u9635\u8f6c\u5316\u4e3a 2 * 4 \u77e9\u9635\u3002 \u6240\u4ee5\u8f93\u51fa\u539f\u77e9\u9635\u3002\n\n\n
\u6ce8\u610f\uff1a
\n\n\u5728MATLAB\u4e2d\uff0c\u6709\u4e00\u4e2a\u975e\u5e38\u6709\u7528\u7684\u51fd\u6570 reshape\uff0c\u5b83\u53ef\u4ee5\u5c06\u4e00\u4e2a\u77e9\u9635\u91cd\u5851\u4e3a\u53e6\u4e00\u4e2a\u5927\u5c0f\u4e0d\u540c\u7684\u65b0\u77e9\u9635\uff0c\u4f46\u4fdd\u7559\u5176\u539f\u59cb\u6570\u636e\u3002
\u7ed9\u51fa\u4e00\u4e2a\u7531\u4e8c\u7ef4\u6570\u7ec4\u8868\u793a\u7684\u77e9\u9635\uff0c\u4ee5\u53ca\u4e24\u4e2a\u6b63\u6574\u6570r\u548cc\uff0c\u5206\u522b\u8868\u793a\u60f3\u8981\u7684\u91cd\u6784\u7684\u77e9\u9635\u7684\u884c\u6570\u548c\u5217\u6570\u3002
\u91cd\u6784\u540e\u7684\u77e9\u9635\u9700\u8981\u5c06\u539f\u59cb\u77e9\u9635\u7684\u6240\u6709\u5143\u7d20\u4ee5\u76f8\u540c\u7684\u884c\u904d\u5386\u987a\u5e8f\u586b\u5145\u3002
\n\n\u5982\u679c\u5177\u6709\u7ed9\u5b9a\u53c2\u6570\u7684reshape\u64cd\u4f5c\u662f\u53ef\u884c\u4e14\u5408\u7406\u7684\uff0c\u5219\u8f93\u51fa\u65b0\u7684\u91cd\u5851\u77e9\u9635\uff1b\u5426\u5219\uff0c\u8f93\u51fa\u539f\u59cb\u77e9\u9635\u3002
\u793a\u4f8b 1:
\n\n\n\u8f93\u5165: \nnums = \n[[1,2],\n [3,4]]\nr = 1, c = 4\n\u8f93\u51fa: \n[[1,2,3,4]]\n\u89e3\u91ca:\n\u884c\u904d\u5386nums\u7684\u7ed3\u679c\u662f [1,2,3,4]\u3002\u65b0\u7684\u77e9\u9635\u662f 1 * 4 \u77e9\u9635, \u7528\u4e4b\u524d\u7684\u5143\u7d20\u503c\u4e00\u884c\u4e00\u884c\u586b\u5145\u65b0\u77e9\u9635\u3002\n\n\n
\u793a\u4f8b 2:
\n\n\n\u8f93\u5165: \nnums = \n[[1,2],\n [3,4]]\nr = 2, c = 4\n\u8f93\u51fa: \n[[1,2],\n [3,4]]\n\u89e3\u91ca:\n\u6ca1\u6709\u529e\u6cd5\u5c06 2 * 2 \u77e9\u9635\u8f6c\u5316\u4e3a 2 * 4 \u77e9\u9635\u3002 \u6240\u4ee5\u8f93\u51fa\u539f\u77e9\u9635\u3002\n\n\n
\u6ce8\u610f\uff1a
\n\n\nWe are stacking blocks to form a pyramid. Each block has a color which is a one letter string, like `'Z'`.\n
\nFor every block of color `C` we place not in the bottom row, we are placing it on top of a left block of color `A` and right block of color `B`. We are allowed to place the block there only if `(A, B, C)` is an allowed triple.\n
\nWe start with a bottom row of bottom, represented as a single string. We also start with a list of allowed triples allowed. Each allowed triple is represented as a string of length 3.\n
\nReturn true if we can build the pyramid all the way to the top, otherwise false.\n
\n\nExample 1:
\n
\nInput: bottom = \"XYZ\", allowed = [\"XYD\", \"YZE\", \"DEA\", \"FFF\"]\nOutput: true\nExplanation:\nWe can stack the pyramid like this:\n A\n / \\\n D E\n / \\ / \\\nX Y Z\n\nThis works because ('X', 'Y', 'D'), ('Y', 'Z', 'E'), and ('D', 'E', 'A') are allowed triples.\n\n\n\nExample 2:
\n
\nInput: bottom = \"XXYX\", allowed = [\"XXX\", \"XXY\", \"XYX\", \"XYY\", \"YXZ\"]\nOutput: false\nExplanation:\nWe can't stack the pyramid to the top.\nNote that there could be allowed triples (A, B, C) and (A, B, D) with C != D.\n\n\n\n
Note:
\n
bottom will be a string with length in range [2, 8].allowed will have length in range [0, 200].{'A', 'B', 'C', 'D', 'E', 'F', 'G'}.\u73b0\u5728\uff0c\u6211\u4eec\u7528\u4e00\u4e9b\u65b9\u5757\u6765\u5806\u780c\u4e00\u4e2a\u91d1\u5b57\u5854\u3002 \u6bcf\u4e2a\u65b9\u5757\u7528\u4ec5\u5305\u542b\u4e00\u4e2a\u5b57\u6bcd\u7684\u5b57\u7b26\u4e32\u8868\u793a\uff0c\u4f8b\u5982 “Z”\u3002
\n\n\u4f7f\u7528\u4e09\u5143\u7ec4\u8868\u793a\u91d1\u5b57\u5854\u7684\u5806\u780c\u89c4\u5219\u5982\u4e0b\uff1a
\n\n(A, B, C) \u8868\u793a\uff0c“C”\u4e3a\u9876\u5c42\u65b9\u5757\uff0c\u65b9\u5757“A”\u3001“B”\u5206\u522b\u4f5c\u4e3a\u65b9\u5757“C”\u4e0b\u4e00\u5c42\u7684\u7684\u5de6\u3001\u53f3\u5b50\u5757\u3002\u5f53\u4e14\u4ec5\u5f53(A, B, C)\u662f\u88ab\u5141\u8bb8\u7684\u4e09\u5143\u7ec4\uff0c\u6211\u4eec\u624d\u53ef\u4ee5\u5c06\u5176\u5806\u780c\u4e0a\u3002
\n\n\u521d\u59cb\u65f6\uff0c\u7ed9\u5b9a\u91d1\u5b57\u5854\u7684\u57fa\u5c42 bottom\uff0c\u7528\u4e00\u4e2a\u5b57\u7b26\u4e32\u8868\u793a\u3002\u4e00\u4e2a\u5141\u8bb8\u7684\u4e09\u5143\u7ec4\u5217\u8868 allowed\uff0c\u6bcf\u4e2a\u4e09\u5143\u7ec4\u7528\u4e00\u4e2a\u957f\u5ea6\u4e3a 3 \u7684\u5b57\u7b26\u4e32\u8868\u793a\u3002
\u5982\u679c\u53ef\u4ee5\u7531\u57fa\u5c42\u4e00\u76f4\u5806\u5230\u5854\u5c16\u8fd4\u56detrue\uff0c\u5426\u5219\u8fd4\u56defalse\u3002
\n\n\u793a\u4f8b 1:
\n\n\n\u8f93\u5165: bottom = "XYZ", allowed = ["XYD", "YZE", "DEA", "FFF"]\n\u8f93\u51fa: true\n\u89e3\u6790:\n\u53ef\u4ee5\u5806\u780c\u6210\u8fd9\u6837\u7684\u91d1\u5b57\u5854:\n A\n / \\\n D E\n / \\ / \\\nX Y Z\n\n\u56e0\u4e3a\u7b26\u5408('X', 'Y', 'D'), ('Y', 'Z', 'E') \u548c ('D', 'E', 'A') \u4e09\u79cd\u89c4\u5219\u3002\n\n\n\u793a\u4f8b 2:
\n\n\n\u8f93\u5165: bottom = "XXYX", allowed = ["XXX", "XXY", "XYX", "XYY", "YXZ"]\n\u8f93\u51fa: false\n\u89e3\u6790:\n\u65e0\u6cd5\u4e00\u76f4\u5806\u5230\u5854\u5c16\u3002\n\u6ce8\u610f, \u5141\u8bb8\u5b58\u5728\u4e09\u5143\u7ec4(A, B, C)\u548c (A, B, D) \uff0c\u5176\u4e2d C != D.\n\n\n
\u6ce8\u610f\uff1a
\n\nbottom \u7684\u957f\u5ea6\u8303\u56f4\u5728 [2, 8]\u3002allowed \u7684\u957f\u5ea6\u8303\u56f4\u5728[0, 200]\u3002{'A', 'B', 'C', 'D', 'E', 'F', 'G'}\u3002\u73b0\u5728\uff0c\u6211\u4eec\u7528\u4e00\u4e9b\u65b9\u5757\u6765\u5806\u780c\u4e00\u4e2a\u91d1\u5b57\u5854\u3002 \u6bcf\u4e2a\u65b9\u5757\u7528\u4ec5\u5305\u542b\u4e00\u4e2a\u5b57\u6bcd\u7684\u5b57\u7b26\u4e32\u8868\u793a\uff0c\u4f8b\u5982 “Z”\u3002
\n\n\u4f7f\u7528\u4e09\u5143\u7ec4\u8868\u793a\u91d1\u5b57\u5854\u7684\u5806\u780c\u89c4\u5219\u5982\u4e0b\uff1a
\n\n(A, B, C) \u8868\u793a\uff0c“C”\u4e3a\u9876\u5c42\u65b9\u5757\uff0c\u65b9\u5757“A”\u3001“B”\u5206\u522b\u4f5c\u4e3a\u65b9\u5757“C”\u4e0b\u4e00\u5c42\u7684\u7684\u5de6\u3001\u53f3\u5b50\u5757\u3002\u5f53\u4e14\u4ec5\u5f53(A, B, C)\u662f\u88ab\u5141\u8bb8\u7684\u4e09\u5143\u7ec4\uff0c\u6211\u4eec\u624d\u53ef\u4ee5\u5c06\u5176\u5806\u780c\u4e0a\u3002
\n\n\u521d\u59cb\u65f6\uff0c\u7ed9\u5b9a\u91d1\u5b57\u5854\u7684\u57fa\u5c42 bottom\uff0c\u7528\u4e00\u4e2a\u5b57\u7b26\u4e32\u8868\u793a\u3002\u4e00\u4e2a\u5141\u8bb8\u7684\u4e09\u5143\u7ec4\u5217\u8868 allowed\uff0c\u6bcf\u4e2a\u4e09\u5143\u7ec4\u7528\u4e00\u4e2a\u957f\u5ea6\u4e3a 3 \u7684\u5b57\u7b26\u4e32\u8868\u793a\u3002
\u5982\u679c\u53ef\u4ee5\u7531\u57fa\u5c42\u4e00\u76f4\u5806\u5230\u5854\u5c16\u8fd4\u56detrue\uff0c\u5426\u5219\u8fd4\u56defalse\u3002
\n\n\u793a\u4f8b 1:
\n\n\n\u8f93\u5165: bottom = "XYZ", allowed = ["XYD", "YZE", "DEA", "FFF"]\n\u8f93\u51fa: true\n\u89e3\u6790:\n\u53ef\u4ee5\u5806\u780c\u6210\u8fd9\u6837\u7684\u91d1\u5b57\u5854:\n A\n / \\\n D E\n / \\ / \\\nX Y Z\n\n\u56e0\u4e3a\u7b26\u5408('X', 'Y', 'D'), ('Y', 'Z', 'E') \u548c ('D', 'E', 'A') \u4e09\u79cd\u89c4\u5219\u3002\n\n\n\u793a\u4f8b 2:
\n\n\n\u8f93\u5165: bottom = "XXYX", allowed = ["XXX", "XXY", "XYX", "XYY", "YXZ"]\n\u8f93\u51fa: false\n\u89e3\u6790:\n\u65e0\u6cd5\u4e00\u76f4\u5806\u5230\u5854\u5c16\u3002\n\u6ce8\u610f, \u5141\u8bb8\u5b58\u5728\u4e09\u5143\u7ec4(A, B, C)\u548c (A, B, D) \uff0c\u5176\u4e2d C != D.\n\n\n
\u6ce8\u610f\uff1a
\n\nbottom \u7684\u957f\u5ea6\u8303\u56f4\u5728 [2, 8]\u3002allowed \u7684\u957f\u5ea6\u8303\u56f4\u5728[0, 200]\u3002{'A', 'B', 'C', 'D', 'E', 'F', 'G'}\u3002Given a 2D integer matrix M representing the gray scale of an image, you need to design a smoother to make the gray scale of each cell becomes the average gray scale (rounding down) of all the 8 surrounding cells and itself. If a cell has less than 8 surrounding cells, then use as many as you can.
\n\nExample 1:
\n
\nInput:\n[[1,1,1],\n [1,0,1],\n [1,1,1]]\nOutput:\n[[0, 0, 0],\n [0, 0, 0],\n [0, 0, 0]]\nExplanation:\nFor the point (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0\nFor the point (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0\nFor the point (1,1): floor(8/9) = floor(0.88888889) = 0\n\n\n\n
Note:
\n
\u5305\u542b\u6574\u6570\u7684\u4e8c\u7ef4\u77e9\u9635 M \u8868\u793a\u4e00\u4e2a\u56fe\u7247\u7684\u7070\u5ea6\u3002\u4f60\u9700\u8981\u8bbe\u8ba1\u4e00\u4e2a\u5e73\u6ed1\u5668\u6765\u8ba9\u6bcf\u4e00\u4e2a\u5355\u5143\u7684\u7070\u5ea6\u6210\u4e3a\u5e73\u5747\u7070\u5ea6 (\u5411\u4e0b\u820d\u5165) \uff0c\u5e73\u5747\u7070\u5ea6\u7684\u8ba1\u7b97\u662f\u5468\u56f4\u76848\u4e2a\u5355\u5143\u548c\u5b83\u672c\u8eab\u7684\u503c\u6c42\u5e73\u5747\uff0c\u5982\u679c\u5468\u56f4\u7684\u5355\u5143\u683c\u4e0d\u8db3\u516b\u4e2a\uff0c\u5219\u5c3d\u53ef\u80fd\u591a\u7684\u5229\u7528\u5b83\u4eec\u3002
\n\n\u793a\u4f8b 1:
\n\n\n\u8f93\u5165:\n[[1,1,1],\n [1,0,1],\n [1,1,1]]\n\u8f93\u51fa:\n[[0, 0, 0],\n [0, 0, 0],\n [0, 0, 0]]\n\u89e3\u91ca:\n\u5bf9\u4e8e\u70b9 (0,0), (0,2), (2,0), (2,2): \u5e73\u5747(3/4) = \u5e73\u5747(0.75) = 0\n\u5bf9\u4e8e\u70b9 (0,1), (1,0), (1,2), (2,1): \u5e73\u5747(5/6) = \u5e73\u5747(0.83333333) = 0\n\u5bf9\u4e8e\u70b9 (1,1): \u5e73\u5747(8/9) = \u5e73\u5747(0.88888889) = 0\n\n\n
\u6ce8\u610f:
\n\n\u5305\u542b\u6574\u6570\u7684\u4e8c\u7ef4\u77e9\u9635 M \u8868\u793a\u4e00\u4e2a\u56fe\u7247\u7684\u7070\u5ea6\u3002\u4f60\u9700\u8981\u8bbe\u8ba1\u4e00\u4e2a\u5e73\u6ed1\u5668\u6765\u8ba9\u6bcf\u4e00\u4e2a\u5355\u5143\u7684\u7070\u5ea6\u6210\u4e3a\u5e73\u5747\u7070\u5ea6 (\u5411\u4e0b\u820d\u5165) \uff0c\u5e73\u5747\u7070\u5ea6\u7684\u8ba1\u7b97\u662f\u5468\u56f4\u76848\u4e2a\u5355\u5143\u548c\u5b83\u672c\u8eab\u7684\u503c\u6c42\u5e73\u5747\uff0c\u5982\u679c\u5468\u56f4\u7684\u5355\u5143\u683c\u4e0d\u8db3\u516b\u4e2a\uff0c\u5219\u5c3d\u53ef\u80fd\u591a\u7684\u5229\u7528\u5b83\u4eec\u3002
\n\n\u793a\u4f8b 1:
\n\n\n\u8f93\u5165:\n[[1,1,1],\n [1,0,1],\n [1,1,1]]\n\u8f93\u51fa:\n[[0, 0, 0],\n [0, 0, 0],\n [0, 0, 0]]\n\u89e3\u91ca:\n\u5bf9\u4e8e\u70b9 (0,0), (0,2), (2,0), (2,2): \u5e73\u5747(3/4) = \u5e73\u5747(0.75) = 0\n\u5bf9\u4e8e\u70b9 (0,1), (1,0), (1,2), (2,1): \u5e73\u5747(5/6) = \u5e73\u5747(0.83333333) = 0\n\u5bf9\u4e8e\u70b9 (1,1): \u5e73\u5747(8/9) = \u5e73\u5747(0.88888889) = 0\n\n\n
\u6ce8\u610f:
\n\nWe are given a 2-dimensional grid. "." is an empty cell, "#" is a wall, "@" is the starting point, ("a", "b", ...) are keys, and ("A", "B", ...) are locks.
We start at the starting point, and one move consists of walking one space in one of the 4 cardinal directions. We cannot walk outside the grid, or walk into a wall. If we walk over a key, we pick it up. We can't walk over a lock unless we have the corresponding key.
\n\nFor some 1 <= K <= 6, there is exactly one lowercase and one uppercase letter of the first K letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet.
Return the lowest number of moves to acquire all keys. If it's impossible, return -1.
\n\n
Example 1:
\n\n\nInput: ["@.a.#","###.#","b.A.B"]\nOutput: 8\n\n\n
Example 2:
\n\n\nInput: ["@..aA","..B#.","....b"]\nOutput: 6\n\n
\n\n
Note:
\n\n1 <= grid.length <= 301 <= grid[0].length <= 30grid[i][j] contains only '.', '#', '@', 'a'-'f' and 'A'-'F'[1, 6]. Each key has a different letter and opens exactly one lock.\u7ed9\u5b9a\u4e00\u4e2a\u4e8c\u7ef4\u7f51\u683c grid\u3002 "." \u4ee3\u8868\u4e00\u4e2a\u7a7a\u623f\u95f4\uff0c "#" \u4ee3\u8868\u4e00\u5835\u5899\uff0c "@" \u662f\u8d77\u70b9\uff0c\uff08"a", "b", ...\uff09\u4ee3\u8868\u94a5\u5319\uff0c\uff08"A", "B", ...\uff09\u4ee3\u8868\u9501\u3002
\u6211\u4eec\u4ece\u8d77\u70b9\u5f00\u59cb\u51fa\u53d1\uff0c\u4e00\u6b21\u79fb\u52a8\u662f\u6307\u5411\u56db\u4e2a\u57fa\u672c\u65b9\u5411\u4e4b\u4e00\u884c\u8d70\u4e00\u4e2a\u5355\u4f4d\u7a7a\u95f4\u3002\u6211\u4eec\u4e0d\u80fd\u5728\u7f51\u683c\u5916\u9762\u884c\u8d70\uff0c\u4e5f\u65e0\u6cd5\u7a7f\u8fc7\u4e00\u5835\u5899\u3002\u5982\u679c\u9014\u7ecf\u4e00\u4e2a\u94a5\u5319\uff0c\u6211\u4eec\u5c31\u628a\u5b83\u6361\u8d77\u6765\u3002\u9664\u975e\u6211\u4eec\u624b\u91cc\u6709\u5bf9\u5e94\u7684\u94a5\u5319\uff0c\u5426\u5219\u65e0\u6cd5\u901a\u8fc7\u9501\u3002
\n\n\u5047\u8bbe K \u4e3a\u94a5\u5319/\u9501\u7684\u4e2a\u6570\uff0c\u4e14\u6ee1\u8db3 1 <= K <= 6\uff0c\u5b57\u6bcd\u8868\u4e2d\u7684\u524d K \u4e2a\u5b57\u6bcd\u5728\u7f51\u683c\u4e2d\u90fd\u6709\u81ea\u5df1\u5bf9\u5e94\u7684\u4e00\u4e2a\u5c0f\u5199\u548c\u4e00\u4e2a\u5927\u5199\u5b57\u6bcd\u3002\u6362\u8a00\u4e4b\uff0c\u6bcf\u4e2a\u9501\u6709\u552f\u4e00\u5bf9\u5e94\u7684\u94a5\u5319\uff0c\u6bcf\u4e2a\u94a5\u5319\u4e5f\u6709\u552f\u4e00\u5bf9\u5e94\u7684\u9501\u3002\u53e6\u5916\uff0c\u4ee3\u8868\u94a5\u5319\u548c\u9501\u7684\u5b57\u6bcd\u4e92\u4e3a\u5927\u5c0f\u5199\u5e76\u6309\u5b57\u6bcd\u987a\u5e8f\u6392\u5217\u3002
\u8fd4\u56de\u83b7\u53d6\u6240\u6709\u94a5\u5319\u6240\u9700\u8981\u7684\u79fb\u52a8\u7684\u6700\u5c11\u6b21\u6570\u3002\u5982\u679c\u65e0\u6cd5\u83b7\u53d6\u6240\u6709\u94a5\u5319\uff0c\u8fd4\u56de -1 \u3002
\n\n
\u793a\u4f8b 1\uff1a
\n\n\u8f93\u5165\uff1a["@.a.#","###.#","b.A.B"]\n\u8f93\u51fa\uff1a8\n\n\n
\u793a\u4f8b 2\uff1a
\n\n\u8f93\u5165\uff1a["@..aA","..B#.","....b"]\n\u8f93\u51fa\uff1a6\n\n\n
\n\n
\u63d0\u793a\uff1a
\n\n1 <= grid.length <= 301 <= grid[0].length <= 30grid[i][j] \u53ea\u542b\u6709 '.', '#', '@', 'a'-'f' \u4ee5\u53ca 'A'-'F'[1, 6]\uff0c\u6bcf\u4e2a\u94a5\u5319\u90fd\u5bf9\u5e94\u4e00\u4e2a\u4e0d\u540c\u7684\u5b57\u6bcd\uff0c\u6b63\u597d\u6253\u5f00\u4e00\u4e2a\u5bf9\u5e94\u7684\u9501\u3002\u7ed9\u5b9a\u4e00\u4e2a\u4e8c\u7ef4\u7f51\u683c grid\u3002 "." \u4ee3\u8868\u4e00\u4e2a\u7a7a\u623f\u95f4\uff0c "#" \u4ee3\u8868\u4e00\u5835\u5899\uff0c "@" \u662f\u8d77\u70b9\uff0c\uff08"a", "b", ...\uff09\u4ee3\u8868\u94a5\u5319\uff0c\uff08"A", "B", ...\uff09\u4ee3\u8868\u9501\u3002
\u6211\u4eec\u4ece\u8d77\u70b9\u5f00\u59cb\u51fa\u53d1\uff0c\u4e00\u6b21\u79fb\u52a8\u662f\u6307\u5411\u56db\u4e2a\u57fa\u672c\u65b9\u5411\u4e4b\u4e00\u884c\u8d70\u4e00\u4e2a\u5355\u4f4d\u7a7a\u95f4\u3002\u6211\u4eec\u4e0d\u80fd\u5728\u7f51\u683c\u5916\u9762\u884c\u8d70\uff0c\u4e5f\u65e0\u6cd5\u7a7f\u8fc7\u4e00\u5835\u5899\u3002\u5982\u679c\u9014\u7ecf\u4e00\u4e2a\u94a5\u5319\uff0c\u6211\u4eec\u5c31\u628a\u5b83\u6361\u8d77\u6765\u3002\u9664\u975e\u6211\u4eec\u624b\u91cc\u6709\u5bf9\u5e94\u7684\u94a5\u5319\uff0c\u5426\u5219\u65e0\u6cd5\u901a\u8fc7\u9501\u3002
\n\n\u5047\u8bbe K \u4e3a\u94a5\u5319/\u9501\u7684\u4e2a\u6570\uff0c\u4e14\u6ee1\u8db3 1 <= K <= 6\uff0c\u5b57\u6bcd\u8868\u4e2d\u7684\u524d K \u4e2a\u5b57\u6bcd\u5728\u7f51\u683c\u4e2d\u90fd\u6709\u81ea\u5df1\u5bf9\u5e94\u7684\u4e00\u4e2a\u5c0f\u5199\u548c\u4e00\u4e2a\u5927\u5199\u5b57\u6bcd\u3002\u6362\u8a00\u4e4b\uff0c\u6bcf\u4e2a\u9501\u6709\u552f\u4e00\u5bf9\u5e94\u7684\u94a5\u5319\uff0c\u6bcf\u4e2a\u94a5\u5319\u4e5f\u6709\u552f\u4e00\u5bf9\u5e94\u7684\u9501\u3002\u53e6\u5916\uff0c\u4ee3\u8868\u94a5\u5319\u548c\u9501\u7684\u5b57\u6bcd\u4e92\u4e3a\u5927\u5c0f\u5199\u5e76\u6309\u5b57\u6bcd\u987a\u5e8f\u6392\u5217\u3002
\u8fd4\u56de\u83b7\u53d6\u6240\u6709\u94a5\u5319\u6240\u9700\u8981\u7684\u79fb\u52a8\u7684\u6700\u5c11\u6b21\u6570\u3002\u5982\u679c\u65e0\u6cd5\u83b7\u53d6\u6240\u6709\u94a5\u5319\uff0c\u8fd4\u56de -1 \u3002
\n\n
\u793a\u4f8b 1\uff1a
\n\n\u8f93\u5165\uff1a["@.a.#","###.#","b.A.B"]\n\u8f93\u51fa\uff1a8\n\n\n
\u793a\u4f8b 2\uff1a
\n\n\u8f93\u5165\uff1a["@..aA","..B#.","....b"]\n\u8f93\u51fa\uff1a6\n\n\n
\n\n
\u63d0\u793a\uff1a
\n\n1 <= grid.length <= 301 <= grid[0].length <= 30grid[i][j] \u53ea\u542b\u6709 '.', '#', '@', 'a'-'f' \u4ee5\u53ca 'A'-'F'[1, 6]\uff0c\u6bcf\u4e2a\u94a5\u5319\u90fd\u5bf9\u5e94\u4e00\u4e2a\u4e0d\u540c\u7684\u5b57\u6bcd\uff0c\u6b63\u597d\u6253\u5f00\u4e00\u4e2a\u5bf9\u5e94\u7684\u9501\u3002A character is unique in string S if it occurs exactly once in it.
For example, in string S = "LETTER", the only unique characters are "L" and "R".
Let's define UNIQ(S) as the number of unique characters in string S.
For example, UNIQ("LETTER") = 2.
Given a string S, calculate the sum of UNIQ(substring) over all non-empty substrings of S.
If there are two or more equal substrings at different positions in S, we consider them different.
Since the answer can be very large, retrun the answer modulo 10 ^ 9 + 7.
\n\n
Example 1:
\n\n\nInput: "ABC"\nOutput: 10\nExplanation: All possible substrings are: "A","B","C","AB","BC" and "ABC".\nEvey substring is composed with only unique letters.\nSum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10\n\n
Example 2:
\n\n\nInput: "ABA"\nOutput: 8\nExplanation: The same as example 1, except uni("ABA") = 1.\n\n\n\n\n
Note: 0 <= S.length <= 10000.
\u5982\u679c\u4e00\u4e2a\u5b57\u7b26\u5728\u5b57\u7b26\u4e32 S \u4e2d\u6709\u4e14\u4ec5\u6709\u51fa\u73b0\u4e00\u6b21\uff0c\u90a3\u4e48\u6211\u4eec\u79f0\u5176\u4e3a\u72ec\u7279\u5b57\u7b26\u3002
\u4f8b\u5982\uff0c\u5728\u5b57\u7b26\u4e32 S = "LETTER" \u4e2d\uff0c"L" \u548c "R" \u53ef\u4ee5\u88ab\u79f0\u4e3a\u72ec\u7279\u5b57\u7b26\u3002
\u6211\u4eec\u518d\u5b9a\u4e49 UNIQ(S) \u4f5c\u4e3a\u5b57\u7b26\u4e32 S \u4e2d\u72ec\u7279\u5b57\u7b26\u7684\u4e2a\u6570\u3002
\u90a3\u4e48\uff0c\u5728 S = "LETTER" \u4e2d\uff0c UNIQ("LETTER") = 2\u3002
\u5bf9\u4e8e\u7ed9\u5b9a\u5b57\u7b26\u4e32 S\uff0c\u8ba1\u7b97\u5176\u6240\u6709\u975e\u7a7a\u5b50\u4e32\u7684\u72ec\u7279\u5b57\u7b26\u7684\u4e2a\u6570\uff0c\u5373 UNIQ(substring)\u3002
\u5982\u679c\u51fa\u73b0\u4e24\u4e2a\u6216\u8005\u591a\u4e2a\u76f8\u540c\u7684\u5b50\u4e32\uff0c\u5c06\u5176\u8ba4\u4e3a\u662f\u4e0d\u540c\u7684\u4e24\u4e2a\u5b50\u4e32\u3002
\n\n\u8003\u8651\u5230\u7b54\u6848\u53ef\u80fd\u4f1a\u975e\u5e38\u5927\uff0c\u89c4\u5b9a\u8fd4\u56de\u683c\u5f0f\u4e3a\uff1a\u7ed3\u679c mod 10 ^ 9 + 7\u3002
\u793a\u4f8b 1:
\n\n\n\u8f93\u5165: "ABC"\n\u8f93\u51fa: 10\n\u89e3\u91ca: \u6240\u6709\u53ef\u80fd\u7684\u5b50\u4e32\u4e3a\uff1a"A","B","C","AB","BC" \u548c "ABC"\u3002\n \u5176\u4e2d\uff0c\u6bcf\u4e00\u4e2a\u5b50\u4e32\u90fd\u7531\u72ec\u7279\u5b57\u7b26\u6784\u6210\u3002\n \u6240\u4ee5\u5176\u957f\u5ea6\u603b\u548c\u4e3a\uff1a1 + 1 + 1 + 2 + 2 + 3 = 10\n\n\n
\u793a\u4f8b 2:
\n\n\n\u8f93\u5165: "ABA"\n\u8f93\u51fa: 8\n\u89e3\u91ca: \u9664\u4e86\u5b50\u4e32 UNIQ('ABA') = 1\uff0c\u5176\u4f59\u4e0e\u793a\u4f8b1\u76f8\u540c\u3002\n\n\n\u8bf4\u660e: 0 <= S.length <= 10000\u3002
\u5982\u679c\u4e00\u4e2a\u5b57\u7b26\u5728\u5b57\u7b26\u4e32 S \u4e2d\u6709\u4e14\u4ec5\u6709\u51fa\u73b0\u4e00\u6b21\uff0c\u90a3\u4e48\u6211\u4eec\u79f0\u5176\u4e3a\u72ec\u7279\u5b57\u7b26\u3002
\u4f8b\u5982\uff0c\u5728\u5b57\u7b26\u4e32 S = "LETTER" \u4e2d\uff0c"L" \u548c "R" \u53ef\u4ee5\u88ab\u79f0\u4e3a\u72ec\u7279\u5b57\u7b26\u3002
\u6211\u4eec\u518d\u5b9a\u4e49 UNIQ(S) \u4f5c\u4e3a\u5b57\u7b26\u4e32 S \u4e2d\u72ec\u7279\u5b57\u7b26\u7684\u4e2a\u6570\u3002
\u90a3\u4e48\uff0c\u5728 S = "LETTER" \u4e2d\uff0c UNIQ("LETTER") = 2\u3002
\u5bf9\u4e8e\u7ed9\u5b9a\u5b57\u7b26\u4e32 S\uff0c\u8ba1\u7b97\u5176\u6240\u6709\u975e\u7a7a\u5b50\u4e32\u7684\u72ec\u7279\u5b57\u7b26\u7684\u4e2a\u6570\uff0c\u5373 UNIQ(substring)\u3002
\u5982\u679c\u51fa\u73b0\u4e24\u4e2a\u6216\u8005\u591a\u4e2a\u76f8\u540c\u7684\u5b50\u4e32\uff0c\u5c06\u5176\u8ba4\u4e3a\u662f\u4e0d\u540c\u7684\u4e24\u4e2a\u5b50\u4e32\u3002
\n\n\u8003\u8651\u5230\u7b54\u6848\u53ef\u80fd\u4f1a\u975e\u5e38\u5927\uff0c\u89c4\u5b9a\u8fd4\u56de\u683c\u5f0f\u4e3a\uff1a\u7ed3\u679c mod 10 ^ 9 + 7\u3002
\u793a\u4f8b 1:
\n\n\n\u8f93\u5165: "ABC"\n\u8f93\u51fa: 10\n\u89e3\u91ca: \u6240\u6709\u53ef\u80fd\u7684\u5b50\u4e32\u4e3a\uff1a"A","B","C","AB","BC" \u548c "ABC"\u3002\n \u5176\u4e2d\uff0c\u6bcf\u4e00\u4e2a\u5b50\u4e32\u90fd\u7531\u72ec\u7279\u5b57\u7b26\u6784\u6210\u3002\n \u6240\u4ee5\u5176\u957f\u5ea6\u603b\u548c\u4e3a\uff1a1 + 1 + 1 + 2 + 2 + 3 = 10\n\n\n
\u793a\u4f8b 2:
\n\n\n\u8f93\u5165: "ABA"\n\u8f93\u51fa: 8\n\u89e3\u91ca: \u9664\u4e86\u5b50\u4e32 UNIQ('ABA') = 1\uff0c\u5176\u4f59\u4e0e\u793a\u4f8b1\u76f8\u540c\u3002\n\n\n\u8bf4\u660e: 0 <= S.length <= 10000\u3002
We are given a binary tree (with root node root), a target node, and an integer value `K`.
Return a list of the values of all nodes that have a distance K from the target node. The answer can be returned in any order.
\n\n
Example 1:
\n\n\nInput: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, K = 2\nOutput: [7,4,1]\nExplanation: \nThe nodes that are a distance 2 from the target node (with value 5)\nhave values 7, 4, and 1.\n\n\n\nNote that the inputs "root" and "target" are actually TreeNodes.\nThe descriptions of the inputs above are just serializations of these objects.\n\n
Note:
\n\n0 <= node.val <= 500.target node is a node in the tree.0 <= K <= 1000.\u7ed9\u5b9a\u4e00\u4e2a\u4e8c\u53c9\u6811\uff08\u5177\u6709\u6839\u7ed3\u70b9 root\uff09\uff0c \u4e00\u4e2a\u76ee\u6807\u7ed3\u70b9 target \uff0c\u548c\u4e00\u4e2a\u6574\u6570\u503c K \u3002
\u8fd4\u56de\u5230\u76ee\u6807\u7ed3\u70b9 target \u8ddd\u79bb\u4e3a K \u7684\u6240\u6709\u7ed3\u70b9\u7684\u503c\u7684\u5217\u8868\u3002 \u7b54\u6848\u53ef\u4ee5\u4ee5\u4efb\u4f55\u987a\u5e8f\u8fd4\u56de\u3002
\n\n
\u793a\u4f8b 1\uff1a
\n\n\u8f93\u5165\uff1aroot = [3,5,1,6,2,0,8,null,null,7,4], target = 5, K = 2\n\n\u8f93\u51fa\uff1a[7,4,1]\n\n\u89e3\u91ca\uff1a\n\u6240\u6c42\u7ed3\u70b9\u4e3a\u4e0e\u76ee\u6807\u7ed3\u70b9\uff08\u503c\u4e3a 5\uff09\u8ddd\u79bb\u4e3a 2 \u7684\u7ed3\u70b9\uff0c\n\u503c\u5206\u522b\u4e3a 7\uff0c4\uff0c\u4ee5\u53ca 1\n\n\n\n\n\n\u6ce8\u610f\uff0c\u8f93\u5165\u7684 "root" \u548c "target" \u5b9e\u9645\u4e0a\u662f\u6811\u4e0a\u7684\u7ed3\u70b9\u3002\n\u4e0a\u9762\u7684\u8f93\u5165\u4ec5\u4ec5\u662f\u5bf9\u8fd9\u4e9b\u5bf9\u8c61\u8fdb\u884c\u4e86\u5e8f\u5217\u5316\u63cf\u8ff0\u3002\n
\n\n
\u63d0\u793a\uff1a
\n\nK \u4e2a\u7ed3\u70b9\u30020 <= node.val <= 500 \u3002target \u662f\u6811\u4e0a\u7684\u7ed3\u70b9\u30020 <= K <= 1000.\u7ed9\u5b9a\u4e00\u4e2a\u4e8c\u53c9\u6811\uff08\u5177\u6709\u6839\u7ed3\u70b9 root\uff09\uff0c \u4e00\u4e2a\u76ee\u6807\u7ed3\u70b9 target \uff0c\u548c\u4e00\u4e2a\u6574\u6570\u503c K \u3002
\u8fd4\u56de\u5230\u76ee\u6807\u7ed3\u70b9 target \u8ddd\u79bb\u4e3a K \u7684\u6240\u6709\u7ed3\u70b9\u7684\u503c\u7684\u5217\u8868\u3002 \u7b54\u6848\u53ef\u4ee5\u4ee5\u4efb\u4f55\u987a\u5e8f\u8fd4\u56de\u3002
\n\n
\u793a\u4f8b 1\uff1a
\n\n\u8f93\u5165\uff1aroot = [3,5,1,6,2,0,8,null,null,7,4], target = 5, K = 2\n\n\u8f93\u51fa\uff1a[7,4,1]\n\n\u89e3\u91ca\uff1a\n\u6240\u6c42\u7ed3\u70b9\u4e3a\u4e0e\u76ee\u6807\u7ed3\u70b9\uff08\u503c\u4e3a 5\uff09\u8ddd\u79bb\u4e3a 2 \u7684\u7ed3\u70b9\uff0c\n\u503c\u5206\u522b\u4e3a 7\uff0c4\uff0c\u4ee5\u53ca 1\n\n\n\n\n\n\u6ce8\u610f\uff0c\u8f93\u5165\u7684 "root" \u548c "target" \u5b9e\u9645\u4e0a\u662f\u6811\u4e0a\u7684\u7ed3\u70b9\u3002\n\u4e0a\u9762\u7684\u8f93\u5165\u4ec5\u4ec5\u662f\u5bf9\u8fd9\u4e9b\u5bf9\u8c61\u8fdb\u884c\u4e86\u5e8f\u5217\u5316\u63cf\u8ff0\u3002\n
\n\n
\u63d0\u793a\uff1a
\n\nK \u4e2a\u7ed3\u70b9\u30020 <= node.val <= 500 \u3002target \u662f\u6811\u4e0a\u7684\u7ed3\u70b9\u30020 <= K <= 1000.
\n# \n# \n# In the next chart, we will plot the data and its corresponding confidence ellipses using 2 std and 3 std. \n\n# In[4]:\n\n\n# Plot the samples using columns 1 and 2 of the matrix\nfig, ax = plt.subplots(figsize = (8, 8))\n\ncolors = ['red', 'green'] # Define a color palete\n\n# Color base on sentiment\n\nax.scatter(data.positive, data.negative, c=[colors[int(k)] for k in data.sentiment], s = 0.1, marker='*') # Plot a dot for tweet\n\n# Custom limits for this chart\nplt.xlim(-200,40) \nplt.ylim(-200,40)\n\nplt.xlabel(\"Positive\") # x-axis label\nplt.ylabel(\"Negative\") # y-axis label\n\ndata_pos = data[data.sentiment == 1] # Filter only the positive samples\ndata_neg = data[data.sentiment == 0] # Filter only the negative samples\n\n# Print confidence ellipses of 2 std\nconfidence_ellipse(data_pos.positive, data_pos.negative, ax, n_std=2, edgecolor='black', label=r'$2\\sigma$' )\nconfidence_ellipse(data_neg.positive, data_neg.negative, ax, n_std=2, edgecolor='orange')\n\n# Print confidence ellipses of 3 std\nconfidence_ellipse(data_pos.positive, data_pos.negative, ax, n_std=3, edgecolor='black', linestyle=':', label=r'$3\\sigma$')\nconfidence_ellipse(data_neg.positive, data_neg.negative, ax, n_std=3, edgecolor='orange', linestyle=':')\nax.legend()\n\nplt.show()\n\n\n# In the next cell, we will modify the features of the samples with positive sentiment (1), in a way that the two distributions overlap. In this case, the Na\u00efve Bayes method will produce a lower accuracy than with the original data.\n\n# In[5]:\n\n\ndata2 = data.copy() # Copy the whole data frame\n\n# The following 2 lines only modify the entries in the data frame where sentiment == 1\ndata2.negative[data.sentiment == 1] = data2.negative * 1.5 + 50 # Modify the negative attribute\ndata2.positive[data.sentiment == 1] = data2.positive / 1.5 - 50 # Modify the positive attribute \n\n\n# Now let us plot the two distributions and the confidence ellipses\n\n# In[6]:\n\n\n# Plot the samples using columns 1 and 2 of the matrix\nfig, ax = plt.subplots(figsize = (8, 8))\n\ncolors = ['red', 'green'] # Define a color palete\n\n# Color base on sentiment\n\n#data.negative[data.sentiment == 1] = data.negative * 2\n\nax.scatter(data2.positive, data2.negative, c=[colors[int(k)] for k in data2.sentiment], s = 0.1, marker='*') # Plot a dot for tweet\n# Custom limits for this chart\nplt.xlim(-200,40) \nplt.ylim(-200,40)\n\nplt.xlabel(\"Positive\") # x-axis label\nplt.ylabel(\"Negative\") # y-axis label\n\ndata_pos = data2[data2.sentiment == 1] # Filter only the positive samples\ndata_neg = data[data2.sentiment == 0] # Filter only the negative samples\n\n# Print confidence ellipses of 2 std\nconfidence_ellipse(data_pos.positive, data_pos.negative, ax, n_std=2, edgecolor='black', label=r'$2\\sigma$' )\nconfidence_ellipse(data_neg.positive, data_neg.negative, ax, n_std=2, edgecolor='orange')\n\n# Print confidence ellipses of 3 std\nconfidence_ellipse(data_pos.positive, data_pos.negative, ax, n_std=3, edgecolor='black', linestyle=':', label=r'$3\\sigma$')\nconfidence_ellipse(data_neg.positive, data_neg.negative, ax, n_std=3, edgecolor='orange', linestyle=':')\nax.legend()\n\nplt.show()\n\n\n# To give away: Understanding the data allows us to predict if the method will perform well or not. Alternatively, it will allow us to understand why it worked well or bad.\n\n# In[ ]:\n\n\n\n\n"}
{"doc_id": "2fdad5173a3a36df1661863252b49389", "text": "import string\r\nimport getpass\r\n\r\ndef check_password_strength(password):\r\n lower_alpha_count = upper_alpha_count = number_count = whitespace_count = special_char_count = 0\r\n for char in list(password):\r\n if char in string.ascii_lowercase:\r\n lower_alpha_count += 1\r\n elif char in string.ascii_uppercase:\r\n upper_alpha_count += 1\r\n elif char in string.digits:\r\n number_count += 1\r\n elif char == ' ':\r\n whitespace_count += 1\r\n else:\r\n special_char_count += 1\r\n strength = 0\r\n remarks = ''\r\n\r\n if lower_alpha_count >= 1:\r\n strength += 1\r\n if upper_alpha_count >= 1:\r\n strength += 1\r\n if number_count >= 1:\r\n strength += 1\r\n if whitespace_count >= 1:\r\n strength += 1\r\n if special_char_count >= 1:\r\n strength += 1\r\n\r\n if strength == 1:\r\n remarks = \"That's a very bad password. Change it as soon as possible.\"\r\n elif strength == 2:\r\n remarks = \"That's not a good password. You should consider making a tougher password.\"\r\n elif strength == 3:\r\n remarks = \"Your password is okay, but it can be improved a lot\"\r\n elif strength == 4:\r\n remarks = \"Your password is hard to guess. But you can make it even more secure\"\r\n elif strength == 5:\r\n remarks = \"Now that's one hell of a strong password !!! Hackers don't have a chance guessing that password.\"\r\n\r\n print(\"Your password has:-\")\r\n print(f\"{lower_alpha_count} lowercase letters\")\r\n print(f\"{upper_alpha_count} uppercase letters\")\r\n print(f\"{number_count} digits\")\r\n print(f'{whitespace_count} whitespaces')\r\n print(f\"{special_char_count} special characters\")\r\n print(f\"Password score: {strength}/5\")\r\n print(f\"Remarks: {remarks}\")\r\n\r\nprint(\"===== Welcome to Password Strength Checker =====\")\r\nwhile 1:\r\n choice = input(\"Do you want to check a password's strength (y/n) : \")\r\n if 'y' in choice.lower():\r\n password = getpass.getpass(\"Enter the password: \")\r\n check_password_strength(password)\r\n elif 'n' in choice.lower():\r\n print('Exiting...')\r\n break\r\n else:\r\n print('Invalid input...please try again.')\r\n print()"}
{"doc_id": "2fed0ef39b9e18d0cd2486051c8fe037", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nPyTorch: Custom nn Modules\n--------------------------\n\nA third order polynomial, trained to predict :math:`y=\\sin(x)` from :math:`-\\pi`\nto :math:`\\pi` by minimizing squared Euclidean distance.\n\nThis implementation defines the model as a custom Module subclass. Whenever you\nwant a model more complex than a simple sequence of existing Modules you will\nneed to define your model this way.\n\"\"\"\nimport torch\nimport math\n\n\nclass Polynomial3(torch.nn.Module):\n def __init__(self):\n \"\"\"\n In the constructor we instantiate four parameters and assign them as\n member parameters.\n \"\"\"\n super().__init__()\n self.a = torch.nn.Parameter(torch.randn(()))\n self.b = torch.nn.Parameter(torch.randn(()))\n self.c = torch.nn.Parameter(torch.randn(()))\n self.d = torch.nn.Parameter(torch.randn(()))\n\n def forward(self, x):\n \"\"\"\n In the forward function we accept a Tensor of input data and we must return\n a Tensor of output data. We can use Modules defined in the constructor as\n well as arbitrary operators on Tensors.\n \"\"\"\n return self.a + self.b * x + self.c * x ** 2 + self.d * x ** 3\n\n def string(self):\n \"\"\"\n Just like any class in Python, you can also define custom method on PyTorch modules\n \"\"\"\n return f'y = {self.a.item()} + {self.b.item()} x + {self.c.item()} x^2 + {self.d.item()} x^3'\n\n\n# Create Tensors to hold input and outputs.\nx = torch.linspace(-math.pi, math.pi, 2000)\ny = torch.sin(x)\n\n# Construct our model by instantiating the class defined above\nmodel = Polynomial3()\n\n# Construct our loss function and an Optimizer. The call to model.parameters()\n# in the SGD constructor will contain the learnable parameters (defined \n# with torch.nn.Parameter) which are members of the model.\ncriterion = torch.nn.MSELoss(reduction='sum')\noptimizer = torch.optim.SGD(model.parameters(), lr=1e-6)\nfor t in range(2000):\n # Forward pass: Compute predicted y by passing x to the model\n y_pred = model(x)\n\n # Compute and print loss\n loss = criterion(y_pred, y)\n if t % 100 == 99:\n print(t, loss.item())\n\n # Zero gradients, perform a backward pass, and update the weights.\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\nprint(f'Result: {model.string()}')\n"}
{"doc_id": "30098fcd9aed0aea34b11a904f18ad6e", "text": "\"\"\"\nThis problem was asked by Apple.\n\nGiven a tree, find the largest tree/subtree that is a BST.\n\nGiven a tree, return the size of the largest tree/subtree that is a BST.\n\"\"\"\n\n\nclass Node:\n def __init__(self, data, left=None, right=None):\n self.data = data\n self.right = right\n self.left = left\n\n def __repr__(self):\n if self.right is not None:\n fmt = '{}({data!r}, {left!r}, {right!r})'\n elif self.left is not None:\n fmt = '{}({data!r}, {left!r})'\n else:\n fmt = '{}({data!r})'\n return fmt.format(type(self).__name__, **vars(self))\n\n\ndef find_largest_bst_subtree(root):\n largest_root = None\n largest_size = 0\n\n def helper(root):\n nonlocal largest_root, largest_size\n is_bst = True\n size = 0\n if root.left:\n child_data, check_bst, temp_size = helper(root.left)\n is_bst = is_bst and child_data <= root.data and check_bst\n size += temp_size\n\n if root.right:\n child_data, check_bst, temp_size = helper(root.right)\n is_bst = is_bst and child_data > root.data and check_bst\n size += temp_size\n\n if is_bst and largest_size < size+1:\n largest_size = size+1\n largest_root = root\n\n return root.data, is_bst, size+1\n\n helper(root)\n return largest_root, largest_size\n\n\nif __name__ == '__main__':\n \"\"\"\n 5\n / \\\n largest, size 3--> 2 4\n / \\\n 1 3\n \"\"\"\n\n tree_1 = Node(data=5,\n left=Node(2,\n left=Node(1),\n right=Node(3)),\n right=Node(4)\n )\n\n largest_tree, size_of_largest_tree = find_largest_bst_subtree(tree_1)\n\n print(\"Size of largest tree : {}\".format(size_of_largest_tree))\n print(\"Largest tree is : \\n {}\".format(largest_tree))\n\n # --------------------\n print(\"\\n ----------- \\n\")\n\n \"\"\"\n 50\n / \\\n 30 60 <----- largest, size 5\n / \\ / \\ \n 5 20 45 70\n / \\\n 65 80\n \"\"\"\n\n tree_2 = Node(data=50,\n left=Node(30,\n left=Node(5),\n right=Node(20)),\n right=Node(60,\n left=Node(45),\n right=Node(70,\n left=Node(65),\n right=Node(80)))\n )\n\n largest_tree, size_of_largest_tree = find_largest_bst_subtree(tree_2)\n\n print(\"Size of largest tree : {}\".format(size_of_largest_tree))\n print(\"Largest tree is : \\n {}\".format(largest_tree))\n\n\n print(\"\\n ----------- \\n\")\n\n \"\"\"\n 6 <----- largest, size 7\n / \\\n 4 10 \n / \\ / \\ \n 3 5 9 11\n \n \"\"\"\n\n tree_3 = Node(data=6,\n left=Node(4,\n left=Node(4),\n right=Node(5)),\n right=Node(10,\n left=Node(9),\n right=Node(11))\n )\n\n largest_tree, size_of_largest_tree = find_largest_bst_subtree(tree_3)\n\n print(\"Size of largest tree : {}\".format(size_of_largest_tree))\n print(\"Largest tree is : \\n {}\".format(largest_tree))"}
{"doc_id": "30287650f283dfdab274afb8ca9fba66", "text": "# Fa\u00e7a um programa que leia um n\u00famero inteiro e mostre na tela a sua tabuada\n\nnum = int(input('Digite um n\u00famero para ver a sua tabuada: '))\n\nprint('-'*12)\nprint('{} x {:2} = {}'.format(num, 1, (num*1)))\nprint('{} x {:2} = {}'.format(num, 2, (num*2)))\nprint('{} x {:2} = {}'.format(num, 3, (num*3)))\nprint('{} x {:2} = {}'.format(num, 4, (num*4)))\nprint('{} x {:2} = {}'.format(num, 5, (num*5)))\nprint('{} x {:2} = {}'.format(num, 6, (num*6)))\nprint('{} x {:2} = {}'.format(num, 7, (num*7)))\nprint('{} x {:2} = {}'.format(num, 8, (num*8)))\nprint('{} x {:2} = {}'.format(num, 9, (num*9)))\nprint('{} x {:2} = {}'.format(num, 10, (num*10)))\n\nprint('-'*12)\n\n"}
{"doc_id": "308ae7e254044fcb6f134f466944e19d", "text": "# Question: The code is supposed to get some input from the user, but instead it produces an error. \n# Please try to understand the error and then fix it.\n\n# pass = input(\"Please enter your password: \") \n\n# Note: Please use raw_input instead of input if you are on Python 2. For Python 3 input is fine.\n\n# Answer:\nuser_pass = input(\"Please enter your password: \")\nprint(user_pass)\n\n# Explanation:\n# There was a SyntaxError error because the syntax to name the variable was wrong since pass is a reserved keyword in Python. However you can solve that by adding a number to the name or simply choosing another name for the variable."}
{"doc_id": "30b79613b2764776eeec90a8b62d12f7", "text": "\"\"\"Codewars: Complete The Pattern #2\n7 kyu\n\nURL: https://www.codewars.com/kata/55733d3ef7c43f8b0700007c/train/python\n\nTask:\nYou have to write a function pattern which returns the following Pattern \n(See Pattern & Examples) upto n number of rows.\nNote: \nReturning the pattern is not the same as Printing the pattern.\nRules/Note:\nIf n < 1 then it should return \"\" i.e. empty string.\nThere are no whitespaces in the pattern.\n\nPattern:\n(n)(n-1)(n-2)...4321\n(n)(n-1)(n-2)...432\n(n)(n-1)(n-2)...43\n(n)(n-1)(n-2)...4\n...............\n..............\n(n)(n-1)(n-2)\n(n)(n-1)\n(n)\nExamples:\npattern(4):\n\n4321\n432\n43\n4\n\"\"\"\n\n\ndef pattern(n):\n end = 0\n stair = 0\n lst = []\n if n < 1:\n return ''\n while stair != n: \n for i in range(n, end, -1):\n lst.append(str(i))\n if end + 1 != n:\n lst.append(\"\\n\") \n end += 1\n stair += 1\n return ''.join(lst)\n\n\ndef main():\n assert pattern(1) == \"1\"\n assert pattern(2) == \"21\\n2\"\n assert pattern(5) == \"54321\\n5432\\n543\\n54\\n5\"\n\n\nif __name__ == '__main__':\n main()\n\n"}
{"doc_id": "3105f192789b85d5d27a45e2e420ddae", "text": "\"\"\"\nQ1. We use a 2d list to represent a lake. The island is completely surrounded by water,\nand there is exactly one island (i.e., one or more connected land cells).\nDetermine the perimeter of the island.\n\nInput: [\n [0,1,0,0],\n [1,1,1,0],\n [0,1,0,0],\n [1,1,0,0]\n]\n\nOutput: 16\nexplain:\n first row has 3 because the 1 at lake[0][1] has three faces connected to water and 1 face connect with lake[1][1].\n second row has 6 because both lake[1][0] and lake[1][2] has 3 faces connected to water and lake[1][1] doesn't connect to water.\n third row has 2 because lake[2][1] has 2 sides connected to water.\n last row has 5 because lake[3][0] has 3 sides and lake[3][1] has 2 sides connected to water.\n\"\"\"\n\n\"\"\"\nQ2. Determine if a 9 x 9 Sudoku board is valid. \n\nInput: board = \n[\n [\"8\",\"3\",\".\",\".\",\"7\",\".\",\".\",\".\",\".\"],\n [\"6\",\".\",\".\",\"1\",\"9\",\"5\",\".\",\".\",\".\"],\n [\".\",\"9\",\"8\",\".\",\".\",\".\",\".\",\"6\",\".\"],\n [\"8\",\".\",\".\",\".\",\"6\",\".\",\".\",\".\",\"3\"],\n [\"4\",\".\",\".\",\"8\",\".\",\"3\",\".\",\".\",\"1\"],\n [\"7\",\".\",\".\",\".\",\"2\",\".\",\".\",\".\",\"6\"],\n [\".\",\"6\",\".\",\".\",\".\",\".\",\"2\",\"8\",\".\"],\n [\".\",\".\",\".\",\"4\",\"1\",\"9\",\".\",\".\",\"5\"],\n [\".\",\".\",\".\",\".\",\"8\",\".\",\".\",\"7\",\"9\"]\n]\nOutput: false\n\nExplain:\nEach row must contain the digits 1-9 without repetition.\nEach column must contain the digits 1-9 without repetition.\nEach of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.\n\"\"\"\n\n\n"}
{"doc_id": "310ca8e31148a6fa888088a1879707d9", "text": "# Ex: 051 - Desenvolva um programa que leia o primeiro termo e a raz\u00e3o de uma\r\n# PA. No final. mostre os 10 primeiros termos dessa progress\u00e3o.\r\n\r\nprint('''\r\n-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\r\n--Seja bem-vindo! \r\n--Exerc\u00edcio 051\r\n-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\r\n''')\r\n\r\nprint('--Progress\u00e3o Aritm\u00e9tica\\n'\r\n '--Preencha os Dados')\r\ntermo1 = int(input('N\u00famero Inicial: '))\r\nrazao = int(input('Raz\u00e3o: '))\r\nprint(f'\\n{termo1}', end=', ')\r\n\r\nfor c in range(1, 10):\r\n termo1 = termo1 + razao\r\n print(termo1, end=', ')\r\n\r\nprint('''\r\n-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\r\n--Obrigado pelo uso!\r\n--Desenvolvido por Thalles Torres\r\n-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-''')\r\n"}
{"doc_id": "312233691d6da666af226e63ede918a8", "text": "# Project Title : Noughts & Crosses\n# Version : 1.0\n# Developed By : Aditya Vikram Singh\n\n\ndef displayGameBoard(Board):\n print(\"-------------\")\n print(\"| \" + Board[0] + \" | \" + Board[1] + \" | \" + Board[2] + \" |\")\n print(\"-------------\")\n print(\"| \" + Board[3] + \" | \" + Board[4] + \" | \" + Board[5] + \" |\")\n print(\"-------------\")\n print(\"| \" + Board[6] + \" | \" + Board[7] + \" | \" + Board[8] + \" |\")\n print(\"-------------\")\n\n\ndef playGame(Board):\n position = -1\n playerOneMove = True\n for i in range(9):\n if winState(Board) != \"!\":\n break\n print(\n \"Player \" + (\"X\" if (playerOneMove) else \"O\") + \"'s Turn- Enter the move: \"\n )\n position = int(input())\n while Board[position - 1] == \"X\" or Board[position - 1] == \"O\":\n print(\"Invalid move! Already occupied space, please try again: \")\n position = int(input())\n Board[position - 1] = \"X\" if (playerOneMove) else \"O\"\n displayGameBoard(Board)\n playerOneMove = not playerOneMove\n if winState(Board) != \"!\":\n return winState(Board) + \" wins!\"\n else:\n return \"Game drawn!\"\n\n\ndef winState(Board):\n for i in range(3):\n if Board[3 * i] == Board[3 * i + 1] and Board[3 * i + 1] == Board[3 * i + 2]:\n return Board[3 * i + 1]\n if Board[i] == Board[i + 3] and Board[i + 3] == Board[i + 6]:\n return Board[i + 3]\n if Board[i] == Board[4] and Board[4] == Board[8 - i]:\n return Board[4]\n return \"!\"\n\n\ndef main():\n initialBoard = [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"]\n displayGameBoard(initialBoard)\n print(playGame(initialBoard))\n\n\nif __name__ == \"__main__\":\n main()\n"}
{"doc_id": "314a486181d5798be0d4a66466842e80", "text": "\"\"\" \nBreadth-first Search:\n\nYou're given a Node class that has a name and an array of optional children nodes.\nWhen put together, nodes form an acyclic tree-like structure.\nImplement the breadthFirstSearch method on the Node class, \nwhich takes in an empty array, traverses the tree using the Breadth-first Search approach (specifically navigating the tree from left to right),\nstores all of the nodes' names in the input array, and returns it.\n\n\nSample Input\n graph = A\n / | \\\n B C D\n / \\ / \\\n E F G H\n / \\ \\\n I J K\nSample Output\n [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\"]\n\nhttps://www.algoexpert.io/questions/Breadth-first%20Search\n\"\"\"\n\n\nclass Node:\n def __init__(self, name):\n self.children = []\n self.name = name\n\n def breadthFirstSearch(self, array):\n queue = [self]\n while len(queue) > 0:\n curr = queue.pop(0)\n array.append(curr.name)\n for child in curr.children:\n queue.append(child)\n return array\n\n\n\"\"\"\nBreadth-first Search:\n\nYou're given a Node class that has a name and an array of optional children nodes. \nWhen put together, nodes form an acyclic tree-like structure.\nImplement the breadthFirstSearch method on the Node class, which takes in an empty array,\n traverses the tree using the Breadth-first Search approach (specifically navigating the tree from left to right),\n stores all of the nodes' names in the input array, and returns it.\n https://www.algoexpert.io/questions/Breadth-first%20Search\n\"\"\"\n\n\n# Do not edit the class below except\n# for the breadthFirstSearch method.\n# Feel free to add new properties\n# and methods to the class.\nclass Node0:\n def __init__(self, name):\n self.children = []\n self.name = name\n\n def addChild(self, name):\n self.children.append(Node0(name))\n return self\n\n def breadthFirstSearch(self, array):\n output = []\n queue = [self] # my implementation of a queue\n while len(queue) > 0:\n curr = queue.pop(0)\n\n # add current element's name to output_array\n output.append(curr.name)\n\n queue = queue + curr.children # add current element's children to end of queue\n\n return output\n\n\n\"\"\"\n[ B C D E F G H]\nSample Input:\ngraph = A\n / | \\\n B C D\n / \\ / \\\n E F G H\n / \\ \\\n I J K\nSample Output\n [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\"]\n\n\n# Input: graph -> Node class that has a name and an array of optional children nodes\n# Output: array of node's names\n# Assumptions:\n - the tree will have at least one node\n - all nodes of the tree are valid\n\n# Need to figure out:\n - how to traverse in a BFS method from left to right\n\n# # First Approach: O(n) time | 0(n) space\n- have an output_array\n- have a queue used to keep track of elements to be traversed next\n# add current element's name to output_array\n# add current element's children to end of queue\n# repeat the above process starting with the first node in the queue\n- if the queue is empty, return the output_array\n# O(n) time | 0(n) space - where n is the number of nodes in the graph \n\n\n\n\"\"\"\n"}
{"doc_id": "3166cfb3fd4d7b61ba45dbfae5db2181", "text": "from typing import Callable\n\n\ndef to_power_three(number):\n \"\"\"\n Returns the number to the power of three.\n :param number: The number\n :return: The number to the power of three\n \"\"\"\n return number ** 3\n\n\ndef suma(a: int, b: int) -> int:\n print(a + b)\n\n\ndef process(number: int, fn: Callable[[int], int]) -> int:\n return fn(number)\n\n\ndef exercise1():\n print([(lambda x: x+1)(number) for number in range(20) if number % 2 == 0])\n\n\ndef main():\n my_range = range(20)\n my_odd_list = list(filter(lambda number: (number % 2 == 0), my_range))\n my_other_odd_list = [to_power_three(number) for number in my_range if number % 2 == 0]\n\n print(my_odd_list, my_other_odd_list, sep='\\n')\n\n #########\n items1 = [1, 2, 3, 4, 5]\n items2 = ['a', 'b', 'c', 'd', 'f']\n fusion = list(zip(items1, items2))\n print(fusion)\n\n ##########\n suma(1, 3.1)\n resta = lambda a, b: a-b\n print(type(resta), resta(3, 2))\n\n ##########\n result = process(10, lambda x: x**2)\n print(result)\n\n ##########\n exercise1()\n\nif __name__ == \"__main__\":\n main()\n"}
{"doc_id": "31677770b957d3047dcce97b6d898f9d", "text": "\"\"\"Build a Diamond Machine\nYou are a skilled diamondsmith whose business is getting better by the day. Eventually, you decided that \nyou needed to scale to keep up with demand.\n\n- Build a diamond-cutting machine (i.e. write a function that takes in a positive integer representing the \n raw stone's carat).\n- The output would be the finished diamond and tag indicating its quality, arranged in a list or array of \n two elements.\n- The first element would be a list of lists or array of arrays representing the diamond\n- The second element would be a string indicating 'perfect cut' if all the diamond's edges are pointy or \n 'good cut' otherwise.\n\nExamples\n\ndiamond(3) -> [\n [[0, 1, 0],\n [1, 0, 1],\n [0, 1, 0]],\n \"perfect cut\"\n]\n# Perfect edge.\n\ndiamond(4) -> [\n [[0, 1, 1, 0],\n [1, 0, 0, 1],\n [0, 1, 1, 0]],\n \"good cut\"\n]\n# First and last rows had blunt edges with two 1s each.\n\nNotes\n- Cut is more important than carat in the diamondsmith's world. Hence, to reduce the number of blunt edges, \n the machine would reduce the size of the diamond.\n- In the second example of a 4-carat raw stone, the machine produces a finished diamond of only 3 rows so that \n there would only be 2 blunt edges, instead of 4.\n- In the first and third examples, the machine was able to produce diamonds of n-rows from n-carat stones.\n\"\"\"\n\n\ndef diamond(carats):\n pass\n\n\nif __name__ == \"__main__\":\n assert diamond(3) == [\n [[0, 1, 0],\n [1, 0, 1],\n [0, 1, 0]],\n \"perfect cut\"\n ] # Perfect edge.\n assert diamond(4) == [\n [[0, 1, 1, 0],\n [1, 0, 0, 1],\n [0, 1, 1, 0]],\n \"good cut\"\n ] # First and last rows had blunt edges with two 1s each.\n assert diamond(11) == [\n [[0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0],\n [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0],\n [0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],\n [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0],\n [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],\n [0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0],\n [0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],\n [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]],\n \"perfect cut\"\n ]\n print(\"All cases passed!\")\n"}
{"doc_id": "319bc4ed8d83a9f3fd4e5b3412934713", "text": "'''\nA width x height grid is on an XY-plane with the bottom-left cell at (0, 0) and the top-right cell at (width - 1, height - 1). The grid is aligned with the four cardinal directions (\"North\", \"East\", \"South\", and \"West\"). A robot is initially at cell (0, 0) facing direction \"East\".\n\nThe robot can be instructed to move for a specific number of steps. For each step, it does the following.\n\nAttempts to move forward one cell in the direction it is facing.\nIf the cell the robot is moving to is out of bounds, the robot instead turns 90 degrees counterclockwise and retries the step.\nAfter the robot finishes moving the number of steps required, it stops and awaits the next instruction.\n\nImplement the Robot class:\n\nRobot(int width, int height) Initializes the width x height grid with the robot at (0, 0) facing \"East\".\nvoid step(int num) Instructs the robot to move forward num steps.\nint[] getPos() Returns the current cell the robot is at, as an array of length 2, [x, y].\nString getDir() Returns the current direction of the robot, \"North\", \"East\", \"South\", or \"West\".\n'''\n\nclass Robot:\n\n def __init__(self, width: int, height: int):\n self.perimeter = 2*width + 2*(height - 2)\n self.pos = 0\n self.atStart = True\n\n self.bottomRight = width - 1\n self.topRight = self.bottomRight + (height - 1)\n self.topLeft = self.topRight + (width - 1)\n\n def step(self, num: int) -> None:\n self.atStart = False\n self.pos = (self.pos + num) % self.perimeter\n\n def getPos(self) -> List[int]:\n if 0 <= self.pos <= self.bottomRight:\n return [self.pos, 0]\n\n if self.bottomRight < self.pos <= self.topRight:\n return [self.bottomRight, self.pos - self.bottomRight]\n\n if self.topRight < self.pos <= self.topLeft:\n return [self.bottomRight - (self.pos - self.topRight), self.topRight - self.bottomRight]\n \n return [0, self.topRight - self.bottomRight - (self.pos - self.topLeft)]\n\n def getDir(self) -> str:\n if self.atStart or 0 < self.pos <= self.bottomRight:\n return 'East'\n\n if self.bottomRight < self.pos <= self.topRight:\n return 'North'\n\n if self.topRight < self.pos <= self.topLeft:\n return 'West'\n \n return 'South'\n \n----------------------------------------\nclass Robot:\n\n def __init__(self, w: int, h: int):\n\n self.build = {0:[[0, 0], 'e']}\n self.moves = 0\n self.isMoved = False\n \n x, y = 1, 0\n d = 'e'\n count = 1\n while x or y:\n \n self.build[count] = [[x, y], d]\n \n \n if x == w - 1 and d == 'e':\n d = 'n'\n if y == h - 1 and d == 'n':\n d = 'w'\n if x == 0 and d == 'w':\n d = 's'\n \n \n \n if d == 'e':\n x += 1\n \n if d == 'n':\n y += 1\n if d == 'w':\n x -= 1\n if d == 's':\n y -= 1\n \n count += 1\n \n # print(self.build)\n \n\n def step(self, num: int) -> None:\n self.isMoved = True\n self.moves += num\n self.moves %= len(self.build)\n \n def getPos(self) -> List[int]:\n \n pos, d = self.build[self.moves]\n \n return pos\n \n\n def getDir(self) -> str:\n \n pos, d = self.build[self.moves]\n \n dirMap = {'e':'East', 'n': 'North', 's':\"South\", 'w': 'West'}\n \n \n if self.isMoved and self.moves == 0:\n return 'South'\n \n return dirMap[d]\n"}
{"doc_id": "31accd5a93914d3e248f0d87ad6a2ac5", "text": "#!/bin/env python3\n\n'''\nCLI Password Generator\nBy Ben Calvert \nDate: 6/1/2021\n'''\n\nimport random\n\n\n# Get user input on length \n\ndef get_input():\n while True: \n x = input('Please enter length of password: ')\n try:\n if int(x) and int(x) > 0:\n return int(x)\n except:\n print('Invalid Input; Try again!')\n\n\ndef main():\n\n # Set Constants \n UPPER = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n LOWER = 'abcdeefghijklmnopqrstuvwxyz'\n NUMBER = '0123456789'\n SYMBOLS = '!@#$%&*.?'\n\n # Combine all Constants\n all_values = UPPER + LOWER + NUMBER + SYMBOLS\n\n # Get password length from the user; pass length of all available characters\n password_length = get_input()\n\n # Find a random sample and generate password of specified length - values can repeat\n password_array = []\n for i in range(password_length):\n # Creates an array of one value\n value = random.sample(all_values,1)\n # Add value of array above to a new array\n password_array.append(value[0])\n\n # make the array a string\n password = ''.join([str(character) for character in password_array])\n\n # Print generated password\n print('\\n\\t' + password + '\\n')\n\n\nif __name__ == '__main__':\n\n main()\n"}
{"doc_id": "31cef47a67736757637538ed9c1522b9", "text": "\"\"\"\nContains several numerical related functions.\n\"\"\"\n\n\ndef add(x, y):\n \"\"\"The sum of two numbers.\n\n Parameters\n ----------\n\n x : (int, float)\n The first number to be added.\n y : (int, float)\n The second number to be added.\n\n Returns\n -------\n ret : (int, float)\n The sum of the inputs a and b\n\n Notes\n -----\n Python will often convert the types of the input values. For example if the\n input of x and y are integers the result will be in an integer. However if\n the input is a integer and a float a float will be returned.\n\n Examples\n --------\n\n Adding two integers together:\n\n >>> add(5, 3)\n 8\n\n An example of mixed input type:\n\n >>> add(5.0, 3)\n 8.0\n \"\"\"\n\n return x + y\n"}
{"doc_id": "32230cd39844bbc54d6c39a08b9188b5", "text": "\"\"\"\nProperties\n Stable\n O(1) extra space\n O(n^2) comparisons and swaps\n Adaptive: O(n) time when nearly sorted\n Very low overhead\n\"\"\"\n\n\"\"\"\nAlthough it is one of the elementary sorting algorithms\nwith O(n2) worst-case time, insertion sort is the algorithm\nof choice either when the data is nearly sorted\n(because it is adaptive) or when the problem size is small\n(because it has low overhead).\n\nFor these reasons, and because it is also stable,\ninsertion sort is often used as the recursive base case\n(when the problem size is small) for higher overhead\ndivide-and-conquer sorting algorithms, such as\nmerge sort or quick sort.\n\"\"\"\n\nimport sys\nimport cProfile\n\n\ndef insertion_sort_ascending(aList):\n \"\"\"\n Given a unsorted list of integers other comparable types,\n it rearrange the integers in natural order in place in an\n ascending order.\n Example: Input: [8,5,3,1,7,6,0,9,4,2,5]\n Output: [0,1,2,3,4,5,5,6,7,8,9]\n \"\"\"\n for i in range(1, len(aList)):\n j = i\n atHand = aList[i]\n while j > 0 and atHand < aList[j - 1]:\n aList[j] = aList[j - 1]\n j -= 1\n aList[j] = atHand\n\n return aList\n\n\ndef insertion_sort_descending(dList):\n \"\"\"\n Given a unsorted list of integers other comparable types,\n it rearrange the integers in natural order in place in an\n descending order.\n Example: Input: [8,5,3,1,7,6,0,9,4,2,5]\n Output: [9,8,7,6,5,5,4,3,2,1,0]\n \"\"\"\n n = len(dList)\n for i in range(n-2, -1, -1):\n j = i\n atHand = dList[i]\n while j < n-1 and atHand < dList[j + 1]:\n dList[j] = dList[j + 1]\n j += 1\n dList[j] = atHand\n\n return dList\n\n\ndef run_test_ascending():\n \"\"\"\n Test function.\n \"\"\"\n aList = [8, 5, 3, 1, 9, 6, 0, 7, 4, 2, 5]\n aList = insertion_sort_ascending(aList)\n print \"---------------------\"\n print \"aList Sorted. Ascending = {}\\n\".format(aList)\n\n\ndef run_test_escending():\n \"\"\"\n Test function.\n \"\"\"\n\n dList = [8, 5, 3, 1, 9, 6, 0, 7, 4, 2, 5]\n dList = insertion_sort_descending(dList)\n print \"---------------------\"\n print \"dList Sorted. Descending = {}\\n\".format(dList)\n\nif __name__ == \"__main__\":\n \"\"\"\n Run the code and profile it.\n \"\"\"\n cProfile.run('run_test_ascending()')\n cProfile.run('run_test_escending()')\n"}
{"doc_id": "322926d81f4c10cc59ecc3ce97fd1a7b", "text": "print(\"-----Bienvenido al programa de compraci\u00f3n de edades-----\")\nusuario1 = input('C\u00f3mo se llama el usuario 1?')\nedad_usuario1 = int(input(f'Que edad tiene {usuario1}?: '))\nusuario2 = input('C\u00f3mo se llama el usuario 2?')\nedad_usuario2 = int(input(f'Que edad tiene {usuario2}?: '))\n\nprint('-----------Resultado------------')\n\nif edad_usuario1 < edad_usuario2:\n print(f'{usuario1} tiene {edad_usuario1} a\u00f1os y es menor que {usuario2} que tiene {edad_usuario2} a\u00f1os')\nelif edad_usuario1 > edad_usuario2:\n print(f'{usuario1} tiene {edad_usuario1} a\u00f1os y es mayor que {usuario2} que tiene {edad_usuario2} a\u00f1os')\nelse :\n print(f'{usuario1} y {usuario2} tienen la misma edad {edad_usuario1} a\u00f1os')```\n"}
{"doc_id": "327e64d2b6663a2deb221a7f3ea24262", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nUgly numbers are numbers whose only prime factors are 2, 3 or 5. \nThe sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, \ufffd shows the first 11 ugly numbers. \nBy convention, 1 is included.\n\"\"\"\n\ndef ugly_numbers(n):\n \n ugly = [0]*n \n ugly[0] = 1\n i2 = i3 = i5 = 0\n \n for i in range(1,n):\n nu2 = ugly[i2]*2\n nu3 = ugly[i3]*3\n nu5 = ugly[i5]*5 \n nu = min(nu2,nu3,nu5)\n ugly[i] = nu\n \n if(nu==nu2):\n i2 += 1\n if(nu==nu3):\n i3 += 1 \n if(nu==nu5):\n i5 += 1\n \n \n return ugly[-1]\n\nprint(ugly_numbers(150))\n"}
{"doc_id": "3283a34e3768762a29f2e2fcdd895334", "text": "# Name: \n# Course: CPE 202\n# Instructor: Daniel Kauffman\n# Assignment: Problem Set II\n# Term: Spring 2021\n\nfrom typing import Optional, Tuple\n\n\n# do not modify this class\nclass StackNode:\n \"\"\"\n A StackNode is like a ListNode except that its ref attribute may only be\n accessed in the push or pop functions, to be defined below.\n \"\"\"\n\n def __init__(self, val: int, ref: Optional[\"StackNode\"]) -> None:\n self.val = val\n self.ref = ref\n\n def __eq__(self, other: \"StackNode\") -> bool:\n \"\"\"\n Return True if the two given stacks have the same number of StackNodes\n and the same StackNode val at each respective position and False\n otherwise.\n\n >>> xs = StackNode(1, StackNode(2, StackNode(3, None)))\n >>> ys = StackNode(1, StackNode(2, StackNode(4, None)))\n >>> xs == ys\n False\n \"\"\"\n while self is not None and other is not None:\n if self.val != other.val:\n return False\n self = self.ref\n other = other.ref\n return self is None and other is None\n\n def __repr__(self) -> str:\n \"\"\"\n Return a string representation of the stack. String representations of\n objects are useful for reading test suite errors.\n\n >>> xs = StackNode(1, StackNode(2, StackNode(3, None)))\n >>> str(xs)\n \"1-2-3\"\n \"\"\"\n stack_str = str(self.val)\n while True:\n self = self.ref\n if self is None:\n return stack_str\n stack_str += \"-\" + str(self.val)\n\n\n\n\ndef push(top: Optional[StackNode], new: StackNode) -> StackNode:\n \"\"\"\n Add the given new StackNode to the top of the stack and return a reference\n to it. Assume the new StackNode's ref attribute is None.\n\n >>> top = StackNode(2, StackNode(3, None))\n >>> push(top, StackNode(1, None))\n StackNode(1, StackNode(2, StackNode(3, None)))\n \"\"\"\n\n\n\n\ndef pop(top: Optional[StackNode]) -> Tuple[StackNode, Optional[StackNode]]:\n \"\"\"\n Remove the StackNode at the top of the stack and return the popped StackNode\n (with its ref set to None) and the reference to the new top of the stack. If\n the stack is initially empty, raise a ValueError.\n\n >>> top = StackNode(1, StackNode(2, StackNode(3, None)))\n >>> pop(top)\n (StackNode(1, None), StackNode(2, StackNode(3, None)))\n \"\"\"\n\n\n\n\ndef move(xs: StackNode,\n ys: Optional[StackNode]) -> Tuple[Optional[StackNode], StackNode]:\n \"\"\"\n Pop the top StackNode from xs and push it to ys. Return references to the\n tops of both stacks.\n\n >>> xs = StackNode(1, StackNode(2, StackNode(3, None)))\n >>> ys = None\n >>> move(xs, ys)\n (StackNode(2, StackNode(3, None)), StackNode(1, None))\n \"\"\"\n\n\n\n\ndef flip_stack(top: Optional[StackNode]) -> Optional[StackNode]:\n \"\"\"\n Return the reversal of the given stack by creating an empty stack and moving\n StackNodes onto it.\n\n >>> top = StackNode(1, StackNode(2, StackNode(3, None)))\n >>> flip_stack(top)\n StackNode(3, StackNode(2, StackNode(1, None)))\n \"\"\"\n\n\n\n\ndef concat(xs: Optional[StackNode],\n ys: Optional[StackNode]) -> Optional[StackNode]:\n \"\"\"\n Return the top of a stack that represents the concatenation of the given\n stacks, such that xs comes before ys.\n\n >>> xs = StackNode(1, StackNode(2, StackNode(3, None)))\n >>> ys = StackNode(4, StackNode(5, None))\n >>> concat(xs, ys)\n StackNode(1, StackNode(2, StackNode(3, StackNode(4, StackNode(5, None)))))\n \"\"\"\n\n\n\n\ndef pop_all(top: Optional[StackNode], val: int) -> Optional[StackNode]:\n \"\"\"\n Return a stack with all StackNodes containing the given integer value\n removed from the given stack.\n\n >>> top = StackNode(1, StackNode(2, StackNode(1, StackNode(3, None))))\n >>> pop_all(top, 1)\n StackNode(2, StackNode(3, None))\n \"\"\"\n\n\n\n\ndef zip_stacks(xs: Optional[StackNode],\n ys: Optional[StackNode]) -> Optional[StackNode]:\n \"\"\"\n Return the top of a stack that represents the pair-wise combination of the\n given stacks. If one stack runs out of StackNodes, append the remainder of\n the other stack.\n\n >>> xs = StackNode(1, StackNode(2, StackNode(3, None)))\n >>> ys = StackNode(4, None)\n >>> zip_stacks(xs, ys)\n StackNode(1, StackNode(4, StackNode(2, StackNode(3, None))))\n \"\"\"\n\n\n\n\ndef unzip_stack(top: Optional[StackNode]\n) -> Tuple[Optional[StackNode], Optional[StackNode]]:\n \"\"\"\n Return a 2-tuple of tops of stacks that represents the pair-wise separation\n of the given stacks. This operation is the inverse of zip_stacks.\n\n >>> top = StackNode(1, StackNode(4, StackNode(2, \\\n StackNode(5, StackNode(3, None)))))\n >>> unzip_stack(top)\n (StackNode(1, StackNode(2, StackNode(3, None))), \\\n StackNode(4, StackNode(5, None)))\n \"\"\"\n\n\n\n\ndef sort_stack(top: Optional[StackNode]) -> Optional[StackNode]:\n \"\"\"\n Return a stack in with the StackNodes from the given stack are sorted in\n ascending order by their integer values.\n\n It is recommended to create two empty stacks: one to which StackNodes are\n temporarily moved, and another to store the sorted StackNodes.\n\n >>> top = StackNode(5, StackNode(2, StackNode(8, None)))\n >>> sort_stack(top)\n StackNode(2, StackNode(5, StackNode(8, None)))\n \"\"\"\n\n"}
{"doc_id": "32bf78c35f82a12d1f79782bc677f9a3", "text": "import re, sys\n\ndef main() -> int:\n user_password = input('Enter a password: ')\n if is_strong_password(user_password):\n print(f'{user_password!r} is a strong password.')\n else:\n print(f'{user_password!r} is a weak password.\\nPlease try again.')\n return 0\n\ndef is_strong_password(password: str) -> bool:\n len_regex = re.compile(r'.{8}.*')\n uppercase_regex = re.compile(r'[A-Z]+')\n lowercase_regex = re.compile(r'[a-z]+')\n digit_regex = re.compile(r'\\d+')\n\n good_len = len_regex.search(password)\n good_upper = uppercase_regex.search(password)\n good_lower = lowercase_regex.search(password)\n good_digit = digit_regex.search(password)\n\n print(f'\\n:: Has minimum length of 8: {bool(good_len)}')\n print(f':: Contains uppercase letters: {bool(good_upper)}')\n print(f':: Constains lowercase letters: {bool(good_lower)}')\n print(f':: Contains digits: {bool(good_digit)}')\n print()\n\n if good_len and good_upper and good_lower and good_digit:\n return True\n else:\n return False\n\nif __name__ == '__main__':\n sys.exit(main())\n"}
{"doc_id": "341064ebaf417dcde2399dd4096e6838", "text": "# https://leetcode.com/problems/find-minimum-in-rotated-sorted-array\n\n\n'''\nNeed to find where the cut-off is.\nIt can either land in the middle of the left half,\nthe right half, or directly in the middle. We want to bisect\non whichever half has the cut-off.\n\nIf we've already passed the cut-off, we want to bisect on\nthe smaller half. I.e. basically just ordinary binary search.\n\n[2, 3, 4, | 5, 6, 0, 1]\n\n[6, 0, 1, | 2, 3, 4, 5]\n\n[0, 1, 2, | 3, 4, 5, 6]\n'''\n\nclass Solution(object):\n def findMin(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n return self.bisect(nums)\n\n def bisect(self, nums):\n print(f\"nums = {nums}\")\n length = len(nums)\n if length == 1:\n return nums[0]\n mid = length // 2\n left, right = nums[:mid], nums[mid:]\n print(f\"left = {left}, right = {right}\")\n if right[0] > right[-1]:\n return self.bisect(right)\n elif left[0] > left[-1]:\n return self.bisect(left)\n elif left[-1] > right[0]:\n return self.bisect(right)\n else:\n return self.bisect(left)\n\nif __name__ == \"__main__\":\n sol = Solution()\n tests = [\n ([3,4,5,1,2], 1),\n ([4,5,6,7,0,1,2], 0),\n ([11,13,15,17], 11),\n ]\n for (nums, solution) in tests:\n print(\"************************************\")\n result = sol.findMin(nums)\n assert result == solution, \\\n f\"result {result} != solution {solution}\"\n print(\"\u2705 All tests passed\")\n\n"}
{"doc_id": "3490b985be22f5d43af5fd5c5303ef39", "text": "# Pirate Bartender: Unit 1 / Lesson 3 / Project 2\nimport random # To choose a random ingredient\n\n\ndef drink_style():\n \n questions = {\n \"strong\": \"Do ye like yer drinks strong?\",\n \"salty\": \"Do ye like it with a salty tang?\",\n \"bitter\": \"Are ye a lubber who likes it bitter?\",\n \"sweet\": \"Would ye like a bit of sweetness with yer poison?\",\n \"fruity\": \"Are ye one for a fruity finish?\",\n }\n \n preferences = dict() # Create a new dictionary to store the answers\n \n for key in questions: # Iterate through the questions\n print(questions[key])\n \n try:\n ans = str(input(\"Yay or Nay?: \"))\n except ValueError:\n ans = str(input(\"I say it again, Yay or Nay?: \"))\n \n # Make sure to convert answers to lowercase\n if ans.lower() == \"yay\" or ans.lower() == \"y\" or ans.lower() == \"yes\":\n preferences[key] = True\n elif ans.lower() == \"nay\" or ans.lower() == \"n\" or ans.lower() == \"no\":\n preferences[key] = False\n else:\n preferences[key] = \"Unknown\" # In case of no yes/no answer\n \n return preferences \n\n\ndef cocktail(preferences):\n \n ingredients = {\n \"strong\": [\"glug of rum\", \"slug of whisky\", \"splash of gin\"],\n \"salty\": [\"olive on a stick\", \"salt-dusted rim\", \"rasher of bacon\"],\n \"bitter\": [\"shake of bitters\", \"splash of tonic\", \"twist of lemon peel\"],\n \"sweet\": [\"sugar cube\", \"spoonful of honey\", \"spash of cola\"],\n \"fruity\": [\"slice of orange\", \"dash of cassis\", \"cherry on top\"],\n }\n\n ingredients_list = []\n \n for key in preferences:\n if preferences[key] == True:\n ingredients_list.append(random.choice(ingredients[key]))\n else:\n pass\n \n print(\"Your cocktail is made of: \" + str(ingredients_list))\n\n\n# Main function\nif __name__ == '__main__':\n preference_dictionary = drink_style()\n cocktail(preference_dictionary)\n\n\n\n#######################\n\n# Extra challenges\n\n# If you found completing the basic requirements fairly straightforward then you should try to extend your app to add the following features:\n\n# Give the cocktails a name\n# All good cocktails should have a memorable name. Try to write a function which will name your cocktails. The name should be a random combination of an adjective and a noun (for example your bartender could make a \"Fluffy Chinchilla\", a \"Salty Sea-Dog\", or a \"Fluffy Sea-Dog\").\n\n# Keep 'em coming\n# At the moment you can only get one drink at a time from the bartender. A well trained pirate bartender should offer his customer another drink when they've finished their previous one. Try adding a loop in the main function which will ask the customer whether they want another drink, and keep creating new recipes as long as they agree.\n\n# Extension exercises\n\n# If the extra challenges were not a problem and you're running ahead of schedule then you could try to implement one or two of the following features in your app:\n\n# Multiple customers: The bartender could ask for the customer's name before they are served. They could then remember the customer's preferences for when the same customer asks for another drink.\n# Stock control: Even pirate bars don't have a limitless supply of ingredients. You could add a stock count for each ingredient which decreases whenever the bartender makes a drink. The bartender could restock the ingredients when supplies are low.\n\n#######################"}
{"doc_id": "34f15054dac2d2ac60a08723cf70fffc", "text": "#!/usr/bin/python\n\n\"\"\"\n--- Part Two ---\nOkay, it's time to go rescue the man's friend.\n\nAs you leave, he hands you some tools: a torch and some climbing gear. You can't equip both tools at once, but you can choose to use neither.\n\nTools can only be used in certain regions:\n\nIn rocky regions, you can use the climbing gear or the torch. You cannot use neither (you'll likely slip and fall).\nIn wet regions, you can use the climbing gear or neither tool. You cannot use the torch (if it gets wet, you won't have a light source).\nIn narrow regions, you can use the torch or neither tool. You cannot use the climbing gear (it's too bulky to fit).\nYou start at 0,0 (the mouth of the cave) with the torch equipped and must reach the target coordinates as quickly as possible. The regions with negative X or Y are solid rock and cannot be traversed. The fastest route might involve entering regions beyond the X or Y coordinate of the target.\n\nYou can move to an adjacent region (up, down, left, or right; never diagonally) if your currently equipped tool allows you to enter that region. Moving to an adjacent region takes one minute. (For example, if you have the torch equipped, you can move between rocky and narrow regions, but cannot enter wet regions.)\n\nYou can change your currently equipped tool or put both away if your new equipment would be valid for your current region. Switching to using the climbing gear, torch, or neither always takes seven minutes, regardless of which tools you start with. (For example, if you are in a rocky region, you can switch from the torch to the climbing gear, but you cannot switch to neither.)\n\nFinally, once you reach the target, you need the torch equipped before you can find him in the dark. The target is always in a rocky region, so if you arrive there with climbing gear equipped, you will need to spend seven minutes switching to your torch.\n\nFor example, using the same cave system as above, starting in the top left corner (0,0) and moving to the bottom right corner (the target, 10,10) as quickly as possible, one possible route is as follows, with your current position marked X:\n\nInitially:\nX=.|=.|.|=.|=|=.\n.|=|=|||..|.=...\n.==|....||=..|==\n=.|....|.==.|==.\n=|..==...=.|==..\n=||.=.=||=|=..|=\n|.=.===|||..=..|\n|..==||=.|==|===\n.=..===..=|.|||.\n.======|||=|=.|=\n.===|=|===T===||\n=|||...|==..|=.|\n=.=|=.=..=.||==|\n||=|=...|==.=|==\n|=.=||===.|||===\n||.|==.|.|.||=||\n\nDown:\nM=.|=.|.|=.|=|=.\nX|=|=|||..|.=...\n.==|....||=..|==\n=.|....|.==.|==.\n=|..==...=.|==..\n=||.=.=||=|=..|=\n|.=.===|||..=..|\n|..==||=.|==|===\n.=..===..=|.|||.\n.======|||=|=.|=\n.===|=|===T===||\n=|||...|==..|=.|\n=.=|=.=..=.||==|\n||=|=...|==.=|==\n|=.=||===.|||===\n||.|==.|.|.||=||\n\nRight:\nM=.|=.|.|=.|=|=.\n.X=|=|||..|.=...\n.==|....||=..|==\n=.|....|.==.|==.\n=|..==...=.|==..\n=||.=.=||=|=..|=\n|.=.===|||..=..|\n|..==||=.|==|===\n.=..===..=|.|||.\n.======|||=|=.|=\n.===|=|===T===||\n=|||...|==..|=.|\n=.=|=.=..=.||==|\n||=|=...|==.=|==\n|=.=||===.|||===\n||.|==.|.|.||=||\n\nSwitch from using the torch to neither tool:\nM=.|=.|.|=.|=|=.\n.X=|=|||..|.=...\n.==|....||=..|==\n=.|....|.==.|==.\n=|..==...=.|==..\n=||.=.=||=|=..|=\n|.=.===|||..=..|\n|..==||=.|==|===\n.=..===..=|.|||.\n.======|||=|=.|=\n.===|=|===T===||\n=|||...|==..|=.|\n=.=|=.=..=.||==|\n||=|=...|==.=|==\n|=.=||===.|||===\n||.|==.|.|.||=||\n\nRight 3:\nM=.|=.|.|=.|=|=.\n.|=|X|||..|.=...\n.==|....||=..|==\n=.|....|.==.|==.\n=|..==...=.|==..\n=||.=.=||=|=..|=\n|.=.===|||..=..|\n|..==||=.|==|===\n.=..===..=|.|||.\n.======|||=|=.|=\n.===|=|===T===||\n=|||...|==..|=.|\n=.=|=.=..=.||==|\n||=|=...|==.=|==\n|=.=||===.|||===\n||.|==.|.|.||=||\n\nSwitch from using neither tool to the climbing gear:\nM=.|=.|.|=.|=|=.\n.|=|X|||..|.=...\n.==|....||=..|==\n=.|....|.==.|==.\n=|..==...=.|==..\n=||.=.=||=|=..|=\n|.=.===|||..=..|\n|..==||=.|==|===\n.=..===..=|.|||.\n.======|||=|=.|=\n.===|=|===T===||\n=|||...|==..|=.|\n=.=|=.=..=.||==|\n||=|=...|==.=|==\n|=.=||===.|||===\n||.|==.|.|.||=||\n\nDown 7:\nM=.|=.|.|=.|=|=.\n.|=|=|||..|.=...\n.==|....||=..|==\n=.|....|.==.|==.\n=|..==...=.|==..\n=||.=.=||=|=..|=\n|.=.===|||..=..|\n|..==||=.|==|===\n.=..X==..=|.|||.\n.======|||=|=.|=\n.===|=|===T===||\n=|||...|==..|=.|\n=.=|=.=..=.||==|\n||=|=...|==.=|==\n|=.=||===.|||===\n||.|==.|.|.||=||\n\nRight:\nM=.|=.|.|=.|=|=.\n.|=|=|||..|.=...\n.==|....||=..|==\n=.|....|.==.|==.\n=|..==...=.|==..\n=||.=.=||=|=..|=\n|.=.===|||..=..|\n|..==||=.|==|===\n.=..=X=..=|.|||.\n.======|||=|=.|=\n.===|=|===T===||\n=|||...|==..|=.|\n=.=|=.=..=.||==|\n||=|=...|==.=|==\n|=.=||===.|||===\n||.|==.|.|.||=||\n\nDown 3:\nM=.|=.|.|=.|=|=.\n.|=|=|||..|.=...\n.==|....||=..|==\n=.|....|.==.|==.\n=|..==...=.|==..\n=||.=.=||=|=..|=\n|.=.===|||..=..|\n|..==||=.|==|===\n.=..===..=|.|||.\n.======|||=|=.|=\n.===|=|===T===||\n=|||.X.|==..|=.|\n=.=|=.=..=.||==|\n||=|=...|==.=|==\n|=.=||===.|||===\n||.|==.|.|.||=||\n\nRight:\nM=.|=.|.|=.|=|=.\n.|=|=|||..|.=...\n.==|....||=..|==\n=.|....|.==.|==.\n=|..==...=.|==..\n=||.=.=||=|=..|=\n|.=.===|||..=..|\n|..==||=.|==|===\n.=..===..=|.|||.\n.======|||=|=.|=\n.===|=|===T===||\n=|||..X|==..|=.|\n=.=|=.=..=.||==|\n||=|=...|==.=|==\n|=.=||===.|||===\n||.|==.|.|.||=||\n\nDown:\nM=.|=.|.|=.|=|=.\n.|=|=|||..|.=...\n.==|....||=..|==\n=.|....|.==.|==.\n=|..==...=.|==..\n=||.=.=||=|=..|=\n|.=.===|||..=..|\n|..==||=.|==|===\n.=..===..=|.|||.\n.======|||=|=.|=\n.===|=|===T===||\n=|||...|==..|=.|\n=.=|=.X..=.||==|\n||=|=...|==.=|==\n|=.=||===.|||===\n||.|==.|.|.||=||\n\nRight 4:\nM=.|=.|.|=.|=|=.\n.|=|=|||..|.=...\n.==|....||=..|==\n=.|....|.==.|==.\n=|..==...=.|==..\n=||.=.=||=|=..|=\n|.=.===|||..=..|\n|..==||=.|==|===\n.=..===..=|.|||.\n.======|||=|=.|=\n.===|=|===T===||\n=|||...|==..|=.|\n=.=|=.=..=X||==|\n||=|=...|==.=|==\n|=.=||===.|||===\n||.|==.|.|.||=||\n\nUp 2:\nM=.|=.|.|=.|=|=.\n.|=|=|||..|.=...\n.==|....||=..|==\n=.|....|.==.|==.\n=|..==...=.|==..\n=||.=.=||=|=..|=\n|.=.===|||..=..|\n|..==||=.|==|===\n.=..===..=|.|||.\n.======|||=|=.|=\n.===|=|===X===||\n=|||...|==..|=.|\n=.=|=.=..=.||==|\n||=|=...|==.=|==\n|=.=||===.|||===\n||.|==.|.|.||=||\n\nSwitch from using the climbing gear to the torch:\nM=.|=.|.|=.|=|=.\n.|=|=|||..|.=...\n.==|....||=..|==\n=.|....|.==.|==.\n=|..==...=.|==..\n=||.=.=||=|=..|=\n|.=.===|||..=..|\n|..==||=.|==|===\n.=..===..=|.|||.\n.======|||=|=.|=\n.===|=|===X===||\n=|||...|==..|=.|\n=.=|=.=..=.||==|\n||=|=...|==.=|==\n|=.=||===.|||===\n||.|==.|.|.||=||\nThis is tied with other routes as the fastest way to reach the target: 45 minutes. In it, 21 minutes are spent switching tools (three times, seven minutes each) and the remaining 24 minutes are spent moving.\n\nWhat is the fewest number of minutes you can take to reach the target?\n\"\"\"\n\n# 16:31 - 17:06 - 19:00\n\nfrom collections import defaultdict\nfrom collections import deque\n\nfrom functools import partial\nimport multiprocessing\nimport re\nimport sys\nimport time\n\nDEPTH = 10647\nTARGET = (7, 770)\n\ndef print_cave(cave):\n global DEPTH\n for row in cave:\n print ''.join(['.', '=', '|'][idx % 3] for idx in row)\n\n\ndef map_cave():\n global DEPTH\n global TARGET\n\n # some slop for exploring\n width = 5 * TARGET[0]\n height = 5 * TARGET[1]\n\n erosion_levels = list(list(0 for x in range(width + 1)) for y in range(height + 1))\n\n for y in range(height + 1):\n geologic_index = ((y % 20183) * (48271 % 20183)) % 20183\n erosion_levels[y][0] = (geologic_index + DEPTH) % 20183 \n\n for x in range(width + 1):\n geologic_index = ((x % 20183) * (16807 % 20183)) % 20183\n erosion_levels[0][x] = (geologic_index + DEPTH) % 20183\n\n for y in range(1, height + 1):\n for x in range(1, width + 1):\n if (x, y) == TARGET:\n # TARGET erosion level is always 0\n continue\n left = erosion_levels[y][x - 1]\n top = erosion_levels[y - 1][x]\n geologic_index = ((left % 20183) * (top % 20183) % 20183)\n erosion_levels[y][x] = (geologic_index + DEPTH) % 20183\n\n return erosion_levels\n\n\ndef adjacency_hof(width, height, position):\n return filter(\n lambda pos: pos[0] >= 0 and pos[1] >= 0 and pos[0] < width and pos[1] < height,\n ((position[0] + adj[0], position[1] + adj[1]) for adj in [(1, 0), (-1, 0), (0, 1), (0, -1)]))\n\n\nVALID_TOOLS = {\n '.': ['TORCH', 'CLIMBING_GEAR'],\n '=': ['CLIMBING_GEAR', 'NEITHER'],\n '|': ['TORCH', 'NEITHER'],\n}\n\n\ndef tool_change(current_tile, next_tile, current_tool):\n if current_tile == next_tile:\n return tool_change_for_same_tile_type(current_tile, current_tool)\n else:\n return tool_change_for_different_tile_type(current_tile, next_tile, current_tool)\n\n \ndef tool_change_for_same_tile_type(tile, current_tool):\n global VALID_TOOLS\n assert current_tool in VALID_TOOLS[tile]\n if tile == '.':\n return 'TORCH' if current_tool == 'CLIMBING_GEAR' else 'CLIMBING_GEAR'\n elif tile == '=':\n return 'CLIMBING_GEAR' if current_tool == 'NEITHER' else 'NEITHER'\n elif tile == '|':\n return 'TORCH' if current_tool == 'NEITHER' else 'NEITHER'\n\n\ndef tool_change_for_different_tile_type(current_tile, next_tile, current_tool):\n global VALID_TOOLS\n assert current_tool in VALID_TOOLS[current_tile]\n candidates = set(VALID_TOOLS[current_tile]).intersection(set(VALID_TOOLS[next_tile]))\n assert current_tool not in candidates, '%s %s %s %s' % (current_tile, next_tile, current_tool, candidates)\n assert len(candidates) == 1\n return list(candidates)[0]\n\n \ndef can_keep_tool(current_tile, next_tile, current_tool):\n global VALID_TOOLS\n return current_tool in VALID_TOOLS[current_tile] and current_tool in VALID_TOOLS[next_tile]\n\n\ndef can_change_tool(current_tile, next_tile, current_tool):\n global VALID_TOOLS\n candidates = set(VALID_TOOLS[current_tile]).intersection(set(VALID_TOOLS[next_tile]))\n if len(candidates) == 1:\n return False\n\n return True\n\n\ndef find_path(cave):\n global VALID_TOOLS\n costs = { ((0, 0), 'TORCH'): 0 }\n path = {}\n width = len(cave[0])\n height = len(cave)\n \n front = [((0, 0), 'TORCH')]\n while len(front) > 0:\n front = sorted(front, key=lambda p: -costs[p])\n current_position, current_tool = front.pop()\n current_tile = ['.', '=', '|'][cave[current_position[1]][current_position[0]] % 3]\n current_cost = costs[(current_position, current_tool)]\n\n # Try tool changes for this tile\n for new_tool in VALID_TOOLS[current_tile]:\n if new_tool == current_tool:\n continue\n new_position = current_position\n if (new_position, new_tool) not in costs or costs[(new_position, new_tool)] > current_cost + 7:\n front.append((new_position, new_tool))\n costs[(new_position, new_tool)] = current_cost + 7 # 7 minutes to change tool\n path[(new_position, new_tool)] = (current_position, current_tool)\n\n # Try no tool changes for this tile\n for edge_position in adjacency_hof(width, height, current_position):\n new_position = edge_position\n next_tile = ['.', '=', '|'][cave[new_position[1]][new_position[0]] % 3]\n \n if can_keep_tool(current_tile, next_tile, current_tool):\n new_tool = current_tool\n if (new_position, new_tool) not in costs or costs[(new_position, new_tool)] > current_cost + 1:\n front.append((new_position, new_tool))\n costs[(new_position, new_tool)] = current_cost + 1 # just one minute\n path[(new_position, new_tool)] = (current_position, current_tool)\n\n return costs, path\n\ndef print_path(path, costs, target):\n if target not in path:\n print target, costs[target]\n else:\n print_path(path, costs, path[target])\n print target, costs[target]\n\n\ndef main():\n global TARGET\n cave = map_cave()\n print_cave(cave)\n print\n print\n costs, path = find_path(cave)\n print 'With torch', costs[(TARGET, 'TORCH')]\n\nif __name__ == \"__main__\":\n main()\n"}
{"doc_id": "34fd9661dfc154d0cd8fc2809ecd057d", "text": "\"\"\"\nAxis class\n==========\nAxis is a named ordered collection of values.\n\nFor these doctests to run we are going to import numcube.Axis and numpy.\n>>> from numcube import Axis\n>>> import numpy as np\n\nCreation\n--------\nTo create an Axis object, you have to supply it with name and values. Name must be a string,\nvalues must be convertible to one-dimensional numpy array. The values should be of the same type,\notherwise they are converted to the most flexible type.\n\n- initialized by explicit values:\n(note: dtype=object is not necessary, it is here to pass the doctests below in both Python 2 and Python 3)\n>>> months = Axis(\"month\", [\"jan\", \"feb\", \"mar\", \"apr\", \"may\", \"jun\", \"jul\", \"aug\", \"sep\", \"oct\", \"nov\", \"dec\"])\n>>> months\nAxis('month', ['jan' 'feb' 'mar' 'apr' 'may' 'jun' 'jul' 'aug' 'sep' 'oct' 'nov' 'dec'])\n\n- initialized from a range:\n>>> years = Axis(\"year\", range(2010, 2020))\n>>> years\nAxis('year', [2010 2011 2012 2013 2014 2015 2016 2017 2018 2019])\n\nProperties\n----------\n\n- 'name' returns a string\n>>> months.name\n'month'\n\n- 'values' returns a numpy array\nnote: this is commented out since this test is not portable between Python 2 and Python 3\n#>>> months.values # doctest: +NORMALIZE_WHITESPACE\narray(['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep',\n 'oct', 'nov', 'dec'])\n\n- str(years) converts the axis to its string representation\n>>> str(years)\n\"Axis('year', [2010 2011 2012 2013 2014 2015 2016 2017 2018 2019])\"\n\n- len(axis) returns the number of values\n>>> len(months)\n12\n\nSlicing, indexing, filtering\n----------------------------\nThe returned object is also Axis with the same name and subset of values.\n\n>>> months[0:4]\nAxis('month', ['jan' 'feb' 'mar' 'apr'])\n\n>>> months[-1]\nAxis('month', ['dec'])\n\n>>> months[::2]\nAxis('month', ['jan' 'mar' 'may' 'jul' 'sep' 'nov'])\n\nWhen accessing values by their indices, you have to provide double square brackets!\n\n>>> months[[0, 2, 4]]\nAxis('month', ['jan' 'mar' 'may'])\n\nThe values can be repeated using repeated indices.\n\n>>> months[[1, 2, 1, 2]]\nAxis('month', ['feb' 'mar' 'feb' 'mar'])\n\nTo filter axis by index, you can also use method take(), which is similar to numpy.take().\n\n>>> months.take([0, 2, 4])\nAxis('month', ['jan' 'mar' 'may'])\n\nYou can filter the axis by using logical values in a numpy array.\n\n>>> years[np.array([True, False, True, False, True, False, True, False, True, False])]\nAxis('year', [2010 2012 2014 2016 2018])\n\nThe previous example was not very useful by itself. But numpy array of logical values is\nthe result of logical expression with axis values. Now this is much more useful.\n\n>>> years[years.values % 2 == 0] # even years\nAxis('year', [2010 2012 2014 2016 2018])\n\n>>> years[(years.values >= 2013) & (years.values <= 2016)] # note the single '&', do not confuse with C/C++ '&&' style\nAxis('year', [2013 2014 2015 2016])\n\nTo filter axis by logical values, you can also use method compress(), which is similar to numpy.compress().\nIn this case you do not need to convert logical values to numpy array.\n\n>>> years.compress([True, False, True, False, True, False, True, False, True, False])\nAxis('year', [2010 2012 2014 2016 2018])\n\nRenaming\n--------\nWe can rename the axis. Renaming returns a new axis (do not forget to assign it to a new variable!),\nthe original axis remains unchanged.\n\n>>> m = months.rename(\"M\")\n>>> m\nAxis('M', ['jan' 'feb' 'mar' 'apr' 'may' 'jun' 'jul' 'aug' 'sep' 'oct' 'nov' 'dec'])\n\nThis is the original axis, still with the old name:\n\n>>> months\nAxis('month', ['jan' 'feb' 'mar' 'apr' 'may' 'jun' 'jul' 'aug' 'sep' 'oct' 'nov' 'dec'])\n\nSorting\n-------\nSorting is one of the places where numcube API and numpy API differs. Numcube sorting returns a copy\nof the axis which is analogy to numpy.sort(array) function. On the other hand array.sort() sorts the\narray in-place. The reason is that numcube aims to support immutability as much as possible.\n\n>>> persons = Axis(\"person\", [\"Steve\", \"John\", \"Alex\", \"Peter\", \"Linda\"])\n>>> sorted_persons = persons.sort()\n>>> sorted_persons\nAxis('person', ['Alex' 'John' 'Linda' 'Peter' 'Steve'])\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)\n\"\"\"\n"}
{"doc_id": "351152d198cfa7387eb891a2c2026300", "text": "#! /usr/bin/env python\n\n\ndef run_opcode(code_list):\n \"\"\"Run the opcode as determined by the values in code_list\n\n Before you enter the next loop, check to see if the opcode\n (the first number in the sequence of 4) is 99. If it is, then\n you can stop and return the code as it stands.\n\n Parameters\n ----------\n code_list : list\n The opcode\n \"\"\"\n opcode, pos0, pos1, posout = 0, 0, 0, 0\n\n for i in range(len(code_list) // 4):\n\n # Read in the next 4 digits of the opcode\n opcode, pos0, pos1, posout = code_list[i*4:(i+1)*4:]\n\n # Add or multiply the values at positions 0 and 1 together\n if opcode == 1:\n output = code_list[pos0] + code_list[pos1]\n elif opcode == 2:\n output = code_list[pos0] * code_list[pos1]\n\n # Put the output value in the output position\n code_list[posout] = output\n\n # Get the next round's opcode\n opcode = code_list[(i+1)*4]\n\n # Don't do anything if the opcode is 99.\n # The code has stopped so you can stop!\n if opcode == 99:\n return code_list\n\n\ndef load_computer_data(fname):\n \"\"\"Read in input file with the computer's opcode as provided.\n\n Parameters\n ----------\n fname : string\n File provided by advent of code competition\n \"\"\"\n\n # Create empty code list\n code_list = []\n\n # Read in each line, and split by comma\n with open(fname, 'r') as f:\n for line in f:\n code_list += line.split(',')\n\n # Convert all items to integer\n code_list = [int(item) for item in code_list]\n\n return code_list\n\n\ndef adjust_data(code_list):\n \"\"\"Return the computer code to the 1202 state before it caught fire.\n\n > 'Before running the program, replace position 1 with the value 12 and\n > replace position 2 with the value 2.'\n\n Parameters\n ----------\n code_list : list\n opcode as provided by advent of code\n \"\"\"\n\n code_list[1] = 12\n code_list[2] = 2\n\n return code_list\n\n\nif __name__ == \"__main__\":\n \"\"\"Load in the data, adjust it to the state before the computer caught fire,\n then run the opcode and print the value in position 0 to the screen.\n \"\"\"\n code_list = load_computer_data('day02/input.txt')\n code_list = adjust_data(code_list)\n code_list = run_opcode(code_list)\n\n print('\\n---- Day 2, Puzzle 1 ----')\n print(f'Value at position 0: {code_list[0]}')\n"}
{"doc_id": "352ed806979658a2a940008a901e6357", "text": "'''\nSpiral Matrix\n\nGiven a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.\n\nInput:\n[\n [ 1, 2, 3 ],\n [ 4, 5, 6 ],\n [ 7, 8, 9 ]\n]\nOutput: [1, 2, 3, 6, 9, 8, 7, 4, 5]\n\nInput:\n[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12]\n]\nOutput: [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]\n\n=========================================\nSimulate spiral moving, start from (0,0) and when a border is reached change the X or Y direction.\n Time Complexity: O(N*M)\n Space Complexity: O(N*M)\n'''\n\n\n############\n# Solution #\n############\n\ndef spiral_matrix(matrix):\n n = len(matrix)\n if n == 0:\n return []\n\n m = len(matrix[0])\n if m == 0:\n return []\n\n total = n * m\n res = []\n\n n -= 1\n xDir, yDir = 1, 1\n x, y = 0, -1\n\n while len(res) < total:\n for i in range(m):\n y += yDir\n res.append(matrix[x][y])\n m -= 1 # decrease horizontal moving steps\n yDir *= -1 # change the Y direction\n\n for i in range(n):\n x += xDir\n res.append(matrix[x][y])\n n -= 1 # decrease vertical moving steps\n xDir *= -1 # change the Y direction\n\n return res\n\n\n###########\n# Testing #\n###########\n\n# Test 1\n# Correct result => [1, 2, 3, 6, 9, 8, 7, 4, 5]\nprint(spiral_matrix([[ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]]))\n\n# Test 2\n# Correct result => [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]\nprint(spiral_matrix([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]))"}
{"doc_id": "35369638f1957c099403caa06e78e657", "text": "from getpass import getpass\n\n\ndef prompt_for_password(prompt: str = 'Enter a password: ',\n verify_prompt: str = 'Re-enter the password: ',\n validate: bool = True) -> str:\n \"\"\" Utility for password prompts\n\n Allows for password validation. If the passwords don't match,\n the function is called again until the passwords match\n\n :param prompt: The first prompt, defaults to 'Enter a password: '\n :type prompt: str, optional\n :param verify_prompt: The validation prompt, defaults to 'Re-enter the password: '\n :type verify_prompt: str, optional\n :param validate: ``True`` if validation needed, ``False`` otherwise, defaults to True\n :type validate: bool, optional\n :return: The password entered by the user\n :rtype: str\n \"\"\"\n\n p1 = getpass(prompt=prompt)\n\n if validate:\n p2 = getpass(prompt=verify_prompt)\n\n if p1 == p2:\n return p1\n else:\n print(\"Passwords don't match\")\n return prompt_for_password()\n else:\n return p1\n"}
{"doc_id": "356185b814121cb70f3233e556c77a5c", "text": "\"\"\"\nFile: weather_master.py\nName: Mike\n-----------------------\nThis program should implement a console program\nthat asks weather data from user to compute the\naverage, highest, lowest, cold days among the inputs.\nOutput format should match what is shown in the sample\nrun in the Assignment 2 Handout.\n\n\"\"\"\nEXIT = -460\n\n\ndef main():\n\t\"\"\"\n\tpre-condition: To find out the highest, lowest, average, temperature\n\tand how many days are there below 16 degree among the temperature(s) you entered\n\tpost-condition: Display the highest, lowest, average temperature\n\tand how many days there are below 16 degree\n\t\"\"\"\n\tprint('stanCode \\\"Weather 4.0\"')\n\tx = int(input('Next Temperature: (Or ' + str(EXIT) + ' to quit)?'))\n\tcount = 0\n\ttotal = 0\n\tcold_days = 0\n\tif x == EXIT:\n\t\tprint('No temperatures were entered.')\n\telse:\n\t\tmaximum = x\n\t\tminimum = x\n\t\tcount = count + 1\n\t\ttotal = total + x\n\t\tif x < 16:\n\t\t\tcold_days = cold_days + 1\n\t\twhile True:\n\t\t\tx = int(input('Next Temperature: (Or ' + str(EXIT) + ' to quit)?'))\n\t\t\tcount = count + 1\n\t\t\ttotal = total + x\n\t\t\tif x < 16:\n\t\t\t\tcold_days = cold_days + 1\n\t\t\tif x == EXIT:\n\t\t\t\tcount = count - 1\n\t\t\t\ttotal = total - x\n\t\t\t\tif x < 16:\n\t\t\t\t\tcold_days = cold_days - 1\n\t\t\t\tbreak\n\t\t\tif x > maximum:\n\t\t\t\tmaximum = x\n\t\t\tif x < minimum:\n\t\t\t\tminimum = x\n\t\taverage = total / count\n\t\tprint('Highest temperature: ' + str(maximum))\n\t\tprint('Lowest temperature: ' + str(minimum))\n\t\tprint('Average: ' + str(average))\n\t\tprint(str(cold_days) + ' cold day(s)')\n\n\n###### DO NOT EDIT CODE BELOW THIS LINE ######\n\nif __name__ == \"__main__\":\n\tmain()\n"}
{"doc_id": "3561ae62508204f3ff9c856a298513bc", "text": "#reads the passowrd.txt file to get the external passowrd and assigns it to the variable \"name\"\r\nwith open(\"password.txt\") as f:\r\n name = f.read()\r\n #print(name)\r\n\r\n#sets variable for number of available tries\r\ntries = 5 \r\n#Begins the while loop until tries reaches 0\r\nwhile tries > 0:\r\n \r\n#calls for and assigns user input as \"x\"\r\n x = input(\"Enter Password: \")\r\n \r\n#Compares the input stored in \"x\" to the password stored in \"name\",\r\n#if correct prints \"correct\" then stops the loop \r\n if x == name:\r\n print(\"correct\")\r\n break\r\n \r\n#compares the input stored in \"x\" to the password stored in \"name\",\r\n#if true prints \"out of tries\" signalling the end of the loop and locking user out. \r\n if tries == 1:\r\n print(\"Out of tries\")\r\n break\r\n \r\n#if incorrect, reduces tries by 1 and asks for input again for the next try.\r\n else:\r\n print(\"incorrect\") \r\n tries -= 1\r\n print(\"Tries left:\",tries)\r\n\r\n\r\n\r\n"}
{"doc_id": "35686c950584bc8c0f6e669bcdbf2c13", "text": "# --- MADE BY RYAN --- #\n\ndef add():\n in1 = float(input(\"Enter First Number: \"))\n in2 = float(input(\"Enter Second Number: \"))\n answer = in1 + in2\n print(f\"{str(in1)} + {str(in2)} = {str(answer)}\")\n\ndef sub():\n in1 = float(input(\"Enter First Number: \"))\n in2 = float(input(\"Enter Second Number: \"))\n answer = in1 - in2\n print(f\"{str(in1)} - {str(in2)} = {str(answer)}\")\n\ndef multi():\n in1 = float(input(\"Enter First Number: \"))\n in2 = float(input(\"Enter Second Number: \"))\n answer = in1 * in2\n print(f\"{str(in1)} * {str(in2)} = {str(answer)}\")\n\ndef div():\n in1 = float(input(\"Enter First Number: \"))\n in2 = float(input(\"Enter Second Number: \"))\n answer = in1 / in2\n print(f\"{str(in1)} / {str(in2)} = {str(answer)}\")\n\ndef area_square():\n in1 = float(input(\"Enter Length: \"))\n answer = in1 * in1\n print(f\"{str(in1)} * {str(in1)} = {str(answer)}\")\n\ndef perimeter_square():\n in1 = float(input(\"Enter Length: \"))\n answer = in1 * 4\n print(f\"{str(in1)} * 4 = {str(answer)}\")\n\ndef check_continue():\n yes_option = [\"Yes\", \"Y\"]\n no_option = [\"No\", \"N\"]\n user_in = input(\"Continue? [Y/N] \")\n if user_in.title() in yes_option or no_option:\n if user_in.title() in yes_option:\n user()\n elif user_in.title() in no_option:\n exit()\n else:\n print(\"Please enter Yes, No, Y or N.\")\n check_continue()\n else:\n print(\"Please enter Yes, No, Y or N.\")\n check_continue()\n\ndef user():\n try:\n maincmd = int(input('''\n Enter 1 for Operations\n Enter 2 for Area & Perimeter\n >>> '''))\n except ValueError:\n print(\"Value Error. Try again!\")\n check_continue()\n else:\n if maincmd == 1:\n try:\n cmd = int(input('''\n Enter 1 for Addition\n Enter 2 for Subtraction\n Enter 3 for Multiplication\n Enter 4 for Division\n >>> '''))\n except ValueError:\n print(\"Valur Error. Try again!\")\n check_continue()\n else:\n if cmd == 1:\n add()\n check_continue()\n elif cmd == 2:\n sub()\n check_continue()\n elif cmd == 3:\n multi()\n check_continue()\n elif cmd == 4:\n div()\n check_continue()\n else:\n print(\"This service is currently unavailable. Try another service.\")\n check_continue()\n elif maincmd == 2:\n try:\n cmd = int(input('''\n Enter 1 for Area of Square\n Enter 2 for Perimeter of Square\n >>> ''')) \n except ValueError:\n print(\"Value Error. Try again!\")\n check_continue()\n else:\n if cmd == 1:\n area_square()\n check_continue()\n elif cmd == 2:\n perimeter_square()\n check_continue()\n else:\n print(\"This service is currently unavailable. Try another service.\")\n check_continue()\n else:\n print(\"This service is currently unavailable. Try another service.\")\n check_continue()\n"}
{"doc_id": "359f5435e5b64d4b68bd6f8422eda4ab", "text": "\"\"\"\nFile: weather_master.py\n-----------------------\nThis program should implement a console program\nthat asks weather data from user to compute the\naverage, highest, lowest, cold days among the inputs.\nOutput format should match what is shown in the sample\nrun in the Assignment 2 Handout.\n\n\"\"\"\n\n# This constant controls when to stop asking new number\nEXIT = -100\n\n\ndef main():\n\t\"\"\"\n\tWhen scientist keys in temperature, the app is able to provide average, highest, lowest, cold days info back to user.\n\t\"\"\"\n\tprint('stanCode Master \\\"Weather master 4.0\" !')\n\tprint('Key in ' + str(EXIT) + ' to stop')\n\tweather = int(input('Daily Temperature:'))\n\tif weather == EXIT:\n\t\tprint('No temperature was entered')\n\telse:\n\t\tlowest = weather\n\t\thighest = weather\n\t\t# sum_ record: to add up all weather record\n\t\tsum_record = weather\n\t\t# count: to count how many numbers are keyed in for average\n\t\tcount = 1\n\t\taverage = weather / count\n\t\tif weather < 16:\n\t\t\tcold_day = 1\n\t\telse:\n\t\t\tcold_day = 0\n\t\twhile True:\n\t\t\tweather = int(input('Daily Temperature:'))\n\t\t\tif weather == EXIT:\n\t\t\t\tbreak\n\t\t\telse:\n\n\t\t\t\tif weather < lowest:\n\t\t\t\t\tlowest = weather\n\t\t\t\tif weather > highest:\n\t\t\t\t\thighest = weather\n\t\t\t\tif weather < 16:\n\t\t\t\t\tcold_day += 1\n\t\t\t\tsum_record += weather\n\t\t\t\tcount += 1\n\t\t\t\taverage = sum_record / count\n\n\t\tprint('The highest temperature is ' + str(highest))\n\t\tprint('The lowest temperature is ' + str(lowest))\n\t\tprint('Average temperature is ' + str(average))\n\t\tprint(str(cold_day) + ' cold day(s)')\n\t\tprint('Total temperature entered: ' + str(count))\n\n\n###### DO NOT EDIT CODE BELOW THIS LINE ######\n\nif __name__ == \"__main__\":\n\tmain()\n"}
{"doc_id": "35e3f466029d06d320898ab904b5d459", "text": "\nmy_name = \"ddHansi Vordorf\"\nprint(my_name, type(my_name))\n\nprint(\"----------Gro\u00df/Klein/Split/Strip/ersetzen/etc.----------\")\n\n# erste Buchstabe gro\u00df Rest klein\nprint(my_name.capitalize())\n# alles klein\nprint(my_name.lower())\n# alles gro\u00df\nprint(my_name.upper())\n\n# beim Leerzeichen splitten -> Liste\nword_list = my_name.split(' ')\nprint(word_list)\n\n# alle d am Anfang entfernen\nmy_name_modified = my_name.strip('d')\nprint(my_name_modified)\n\nmy_name = 'Peter Peterson'\n# \u00fcberpr\u00fcfen erste Wort\nprint(my_name.startswith('Peter'))\n# \u00fcberpr\u00fcfen letzte Wort\nprint(my_name.endswith('Peterson'))\n\nif my_name.startswith('Peter'):\n # ersetzen\n my_name = my_name.replace('Peter', 'Magnus')\n\nprint(my_name)\n\nprint(\"----------Zusammenf\u00fcgen----------\")\nfriend_names = ['Jan', 'Peter', 'Dennis']\n\noutput_str = ' '.join(friend_names)\nprint(output_str)"}
{"doc_id": "35e7b8bc7d5be9160ad8bf6fc061e4c1", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on: Mon Sep 3 23:12:59 2018\n@author: Deepti Kulkarni \n\"\"\"\n\n\n\"\"\"Chapter 3, Exercise 2\nRewrite your pay program using try and except so that your program handles non-\nnumeric input gracefully by printing a message\nand exiting the program. The following shows two executions of the program. \"\"\"\n\n\ntry:\n hours= float(input('Enter Hours: '))\n rate=float(input('Enter Rate: '))\n print('Pay: ',hours*rate)\n \nexcept:\n hours=-1\n rate=-1\n print(\"Error! Please enter numeric values only.\")\n\n\n\"\"\"Chapter 3, Exercise 3\nWrite a program to prompt for a score between 0.0 and 1.0. If the score is out \nof range, print an error message. If the score is\nbetween 0.0 and 1.0, print a grade using the following table: Score Grade\n>= 0.9 A\n>= 0.8 B\n>= 0.7 C\n>= 0.6 D\n< 0.6 F \"\"\"\n\n\ntry:\n score=float(input(\"Enter score between 0.0 and 1.0: \"))\n if score>1.0 or score<0:\n print(\"Error! Please enter score between 0.0 and 1.0 only. \")\n elif score>=0.9:\n print(\"Grade is 'A'\")\n elif score>=0.8:\n print(\"Grade is 'B'\")\n elif score>=0.7:\n print(\"Grade is 'C'\")\n elif score>=0.6:\n print(\"Grade is 'D'\")\n else:\n print(\"Grade is 'F'\")\n\nexcept:\n score= -1\n print(\"Error! Please enter numeric values only.\") \n \n \n\n\"\"\"Chapter 4, Exercise 6\nRewrite your pay computation with time-and-a-half for over-\ntime and create a function called computepay which takes two parameters\n(hours and rate).\"\"\"\n\ndef computepay(hours,rate):\n \n if hours>40:\n overtime_rate=1.5*rate\n overtime_hours=hours-40\n overtime=overtime_hours*overtime_rate \n pay=(40*rate)+overtime\n else:\n pay=hours*rate\n return pay\n\ntry:\n \n hours= float(input('Enter Hours: '))\n rate=float(input('Enter Rate: '))\n pay=computepay(hours,rate)\n \n print('Pay: ',pay)\n\nexcept:\n score= -1\n print(\"Error! Please enter numeric values only.\") \n \n \n\"\"\"Chapter 4, Exercise 7\nRewrite the grade program from the previous chapter using a function called \ncomputegrade that takes a score as its parameter and\nreturns a grade as a string.\"\"\"\n\ndef computegrade(score):\n if score>=0.9:\n grade=\"A\"\n elif score>=0.8:\n grade=\"B\"\n elif score>=0.7:\n grade=\"C\"\n elif score>=0.6:\n grade=\"D\"\n else:\n grade=\"F\"\n return grade\n \ntry:\n score=float(input(\"Enter score between 0.0 and 1.0: \"))\n if score>1.0 or score<0:\n print(\"Error! Please enter score between 0.0 and 1.0 only. \")\n else:\n grade=computegrade(score)\n print(\"Grade is: \",grade)\n \nexcept:\n score= -1\n print(\"Error! Please enter numeric values only.\") \n \n\n\n\n\"\"\"\n--------Sample Output(Chapter 3, Exercise 2)------------\n\nEnter Hours: 12\n\nEnter Rate: nine\nError! Please enter numeric values only.\n\nEnter Hours: nine\nError! Please enter numeric values only.\n\n--------Sample Output(Chapter 3, Exercise 3)------------\n\nEnter score between 0.0 and 1.0: 2\nError! Please enter score between 0.0 and 1.0 only. \n\nEnter score between 0.0 and 1.0: nine\nError! Please enter numeric values only.\n\nEnter score between 0.0 and 1.0: 0.99\nGrade is 'A'\n\nEnter score between 0.0 and 1.0: 0.77\nGrade is 'C'\n\nEnter score between 0.0 and 1.0: 0.66\nGrade is 'D'\n\nEnter score between 0.0 and 1.0: 0.5\nGrade is 'F'\n\n--------Sample Output(Chapter 4, Exercise 6)------------\n\nEnter Hours: 45\n\nEnter Rate: 10\nPay: 475.0\n\n--------Sample Output(Chapter 4, Exercise 7)------------\n\nEnter score between 0.0 and 1.0: 0.7\nGrade is: C\n\n\"\"\"\n"}
{"doc_id": "360b316c4f8c4f7ae8098f7da285baa2", "text": "'''\nClock object\n============\n\nThe :class:`Clock` object allows you to schedule a function call in the\nfuture; once or repeatedly at specified intervals::\n\n def my_callback(dt):\n pass\n\n # call my_callback every 0.5 seconds\n Clock.schedule_interval(my_callback, 0.5)\n\n # call my_callback in 5 seconds\n Clock.schedule_once(my_callback, 5)\n\n # call my_callback as soon as possible (usually next frame.)\n Clock.schedule_once(my_callback)\n\n.. note::\n\n If the callback returns False, the schedule will be removed.\n\nIf you want to schedule a function to call with default arguments, you can use\nthe `functools.partial\nGiven a list of positive integers, the adjacent integers will perform the float division. For example, [2,3,4] -> 2 / 3 / 4.
\n\nHowever, you can add any number of parenthesis at any position to change the priority of operations. You should find out how to add parenthesis to get the maximum result, and return the corresponding expression in string format. Your expression should NOT contain redundant parenthesis.
\n\nExample:
\n
\nInput: [1000,100,10,2]\nOutput: \"1000/(100/10/2)\"\nExplanation:\n1000/(100/10/2) = 1000/((100/10)/2) = 200\nHowever, the bold parenthesis in \"1000/((100/10)/2)\" are redundant,\n\n\n
since they don't influence the operation priority. So you should return \"1000/(100/10/2)\". \n\nOther cases:\n1000/(100/10)/2 = 50\n1000/(100/(10/2)) = 50\n1000/100/10/2 = 0.5\n1000/100/(10/2) = 2\n
Note:\n
\u7ed9\u5b9a\u4e00\u7ec4\u6b63\u6574\u6570\uff0c\u76f8\u90bb\u7684\u6574\u6570\u4e4b\u95f4\u5c06\u4f1a\u8fdb\u884c\u6d6e\u70b9\u9664\u6cd5\u64cd\u4f5c\u3002\u4f8b\u5982\uff0c [2,3,4] -> 2 / 3 / 4 \u3002
\n\n\u4f46\u662f\uff0c\u4f60\u53ef\u4ee5\u5728\u4efb\u610f\u4f4d\u7f6e\u6dfb\u52a0\u4efb\u610f\u6570\u76ee\u7684\u62ec\u53f7\uff0c\u6765\u6539\u53d8\u7b97\u6570\u7684\u4f18\u5148\u7ea7\u3002\u4f60\u9700\u8981\u627e\u51fa\u600e\u4e48\u6dfb\u52a0\u62ec\u53f7\uff0c\u624d\u80fd\u5f97\u5230\u6700\u5927\u7684\u7ed3\u679c\uff0c\u5e76\u4e14\u8fd4\u56de\u76f8\u5e94\u7684\u5b57\u7b26\u4e32\u683c\u5f0f\u7684\u8868\u8fbe\u5f0f\u3002\u4f60\u7684\u8868\u8fbe\u5f0f\u4e0d\u5e94\u8be5\u542b\u6709\u5197\u4f59\u7684\u62ec\u53f7\u3002
\n\n\u793a\u4f8b\uff1a
\n\n\n\u8f93\u5165: [1000,100,10,2]\n\u8f93\u51fa: "1000/(100/10/2)"\n\u89e3\u91ca:\n1000/(100/10/2) = 1000/((100/10)/2) = 200\n\u4f46\u662f\uff0c\u4ee5\u4e0b\u52a0\u7c97\u7684\u62ec\u53f7 "1000/((100/10)/2)" \u662f\u5197\u4f59\u7684\uff0c\n\u56e0\u4e3a\u4ed6\u4eec\u5e76\u4e0d\u5f71\u54cd\u64cd\u4f5c\u7684\u4f18\u5148\u7ea7\uff0c\u6240\u4ee5\u4f60\u9700\u8981\u8fd4\u56de "1000/(100/10/2)"\u3002\n\n\u5176\u4ed6\u7528\u4f8b:\n1000/(100/10)/2 = 50\n1000/(100/(10/2)) = 50\n1000/100/10/2 = 0.5\n1000/100/(10/2) = 2\n\n\n
\u8bf4\u660e:
\n\n\u7ed9\u5b9a\u4e00\u7ec4\u6b63\u6574\u6570\uff0c\u76f8\u90bb\u7684\u6574\u6570\u4e4b\u95f4\u5c06\u4f1a\u8fdb\u884c\u6d6e\u70b9\u9664\u6cd5\u64cd\u4f5c\u3002\u4f8b\u5982\uff0c [2,3,4] -> 2 / 3 / 4 \u3002
\n\n\u4f46\u662f\uff0c\u4f60\u53ef\u4ee5\u5728\u4efb\u610f\u4f4d\u7f6e\u6dfb\u52a0\u4efb\u610f\u6570\u76ee\u7684\u62ec\u53f7\uff0c\u6765\u6539\u53d8\u7b97\u6570\u7684\u4f18\u5148\u7ea7\u3002\u4f60\u9700\u8981\u627e\u51fa\u600e\u4e48\u6dfb\u52a0\u62ec\u53f7\uff0c\u624d\u80fd\u5f97\u5230\u6700\u5927\u7684\u7ed3\u679c\uff0c\u5e76\u4e14\u8fd4\u56de\u76f8\u5e94\u7684\u5b57\u7b26\u4e32\u683c\u5f0f\u7684\u8868\u8fbe\u5f0f\u3002\u4f60\u7684\u8868\u8fbe\u5f0f\u4e0d\u5e94\u8be5\u542b\u6709\u5197\u4f59\u7684\u62ec\u53f7\u3002
\n\n\u793a\u4f8b\uff1a
\n\n\n\u8f93\u5165: [1000,100,10,2]\n\u8f93\u51fa: "1000/(100/10/2)"\n\u89e3\u91ca:\n1000/(100/10/2) = 1000/((100/10)/2) = 200\n\u4f46\u662f\uff0c\u4ee5\u4e0b\u52a0\u7c97\u7684\u62ec\u53f7 "1000/((100/10)/2)" \u662f\u5197\u4f59\u7684\uff0c\n\u56e0\u4e3a\u4ed6\u4eec\u5e76\u4e0d\u5f71\u54cd\u64cd\u4f5c\u7684\u4f18\u5148\u7ea7\uff0c\u6240\u4ee5\u4f60\u9700\u8981\u8fd4\u56de "1000/(100/10/2)"\u3002\n\n\u5176\u4ed6\u7528\u4f8b:\n1000/(100/10)/2 = 50\n1000/(100/(10/2)) = 50\n1000/100/10/2 = 0.5\n1000/100/(10/2) = 2\n\n\n
\u8bf4\u660e:
\n\nMedian is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.
\nExamples:[2,3,4] , the median is 3
[2,3], the median is (2 + 3) / 2 = 2.5
Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Your job is to output the median array for each window in the original array.
\n\nFor example,
\nGiven nums = [1,3,-1,-3,5,3,6,7], and k = 3.
\nWindow position Median\n--------------- -----\n[1 3 -1] -3 5 3 6 7 1\n 1 [3 -1 -3] 5 3 6 7 -1\n 1 3 [-1 -3 5] 3 6 7 -1\n 1 3 -1 [-3 5 3] 6 7 3\n 1 3 -1 -3 [5 3 6] 7 5\n 1 3 -1 -3 5 [3 6 7] 6\n\n\n
Therefore, return the median sliding window as [1,-1,-1,3,5,6].
Note:
\nYou may assume k is always valid, ie: k is always smaller than input array's size for non-empty array.
\u4e2d\u4f4d\u6570\u662f\u6709\u5e8f\u5e8f\u5217\u6700\u4e2d\u95f4\u7684\u90a3\u4e2a\u6570\u3002\u5982\u679c\u5e8f\u5217\u7684\u5927\u5c0f\u662f\u5076\u6570\uff0c\u5219\u6ca1\u6709\u6700\u4e2d\u95f4\u7684\u6570\uff1b\u6b64\u65f6\u4e2d\u4f4d\u6570\u662f\u6700\u4e2d\u95f4\u7684\u4e24\u4e2a\u6570\u7684\u5e73\u5747\u6570\u3002
\n\n\u4f8b\u5982\uff1a
\n\n[2,3,4]\uff0c\u4e2d\u4f4d\u6570\u662f 3
[2,3]\uff0c\u4e2d\u4f4d\u6570\u662f (2 + 3) / 2 = 2.5
\u7ed9\u51fa\u4e00\u4e2a\u6570\u7ec4 nums\uff0c\u6709\u4e00\u4e2a\u5927\u5c0f\u4e3a k \u7684\u7a97\u53e3\u4ece\u6700\u5de6\u7aef\u6ed1\u52a8\u5230\u6700\u53f3\u7aef\u3002\u7a97\u53e3\u4e2d\u6709 k \u4e2a\u6570\uff0c\u6bcf\u6b21\u7a97\u53e3\u79fb\u52a8 1 \u4f4d\u3002\u4f60\u7684\u4efb\u52a1\u662f\u627e\u51fa\u6bcf\u6b21\u7a97\u53e3\u79fb\u52a8\u540e\u5f97\u5230\u7684\u65b0\u7a97\u53e3\u4e2d\u5143\u7d20\u7684\u4e2d\u4f4d\u6570\uff0c\u5e76\u8f93\u51fa\u7531\u5b83\u4eec\u7ec4\u6210\u7684\u6570\u7ec4\u3002
\n\n\u4f8b\u5982\uff1a
\n\n\u7ed9\u51fa nums = [1,3,-1,-3,5,3,6,7]\uff0c\u4ee5\u53ca k = 3\u3002
\n\u7a97\u53e3\u4f4d\u7f6e \u4e2d\u4f4d\u6570\n--------------- -----\n[1 3 -1] -3 5 3 6 7 1\n 1 [3 -1 -3] 5 3 6 7 -1\n 1 3 [-1 -3 5] 3 6 7 -1\n 1 3 -1 [-3 5 3] 6 7 3\n 1 3 -1 -3 [5 3 6] 7 5\n 1 3 -1 -3 5 [3 6 7] 6\n\n\n
\u56e0\u6b64\uff0c\u8fd4\u56de\u8be5\u6ed1\u52a8\u7a97\u53e3\u7684\u4e2d\u4f4d\u6570\u6570\u7ec4 [1,-1,-1,3,5,6]\u3002
\u63d0\u793a\uff1a
\n\u5047\u8bbek\u662f\u5408\u6cd5\u7684\uff0c\u5373\uff1ak \u59cb\u7ec8\u5c0f\u4e8e\u8f93\u5165\u7684\u975e\u7a7a\u6570\u7ec4\u7684\u5143\u7d20\u4e2a\u6570.
\u4e2d\u4f4d\u6570\u662f\u6709\u5e8f\u5e8f\u5217\u6700\u4e2d\u95f4\u7684\u90a3\u4e2a\u6570\u3002\u5982\u679c\u5e8f\u5217\u7684\u5927\u5c0f\u662f\u5076\u6570\uff0c\u5219\u6ca1\u6709\u6700\u4e2d\u95f4\u7684\u6570\uff1b\u6b64\u65f6\u4e2d\u4f4d\u6570\u662f\u6700\u4e2d\u95f4\u7684\u4e24\u4e2a\u6570\u7684\u5e73\u5747\u6570\u3002
\n\n\u4f8b\u5982\uff1a
\n\n[2,3,4]\uff0c\u4e2d\u4f4d\u6570\u662f 3
[2,3]\uff0c\u4e2d\u4f4d\u6570\u662f (2 + 3) / 2 = 2.5
\u7ed9\u51fa\u4e00\u4e2a\u6570\u7ec4 nums\uff0c\u6709\u4e00\u4e2a\u5927\u5c0f\u4e3a k \u7684\u7a97\u53e3\u4ece\u6700\u5de6\u7aef\u6ed1\u52a8\u5230\u6700\u53f3\u7aef\u3002\u7a97\u53e3\u4e2d\u6709 k \u4e2a\u6570\uff0c\u6bcf\u6b21\u7a97\u53e3\u79fb\u52a8 1 \u4f4d\u3002\u4f60\u7684\u4efb\u52a1\u662f\u627e\u51fa\u6bcf\u6b21\u7a97\u53e3\u79fb\u52a8\u540e\u5f97\u5230\u7684\u65b0\u7a97\u53e3\u4e2d\u5143\u7d20\u7684\u4e2d\u4f4d\u6570\uff0c\u5e76\u8f93\u51fa\u7531\u5b83\u4eec\u7ec4\u6210\u7684\u6570\u7ec4\u3002
\n\n\u4f8b\u5982\uff1a
\n\n\u7ed9\u51fa nums = [1,3,-1,-3,5,3,6,7]\uff0c\u4ee5\u53ca k = 3\u3002
\n\u7a97\u53e3\u4f4d\u7f6e \u4e2d\u4f4d\u6570\n--------------- -----\n[1 3 -1] -3 5 3 6 7 1\n 1 [3 -1 -3] 5 3 6 7 -1\n 1 3 [-1 -3 5] 3 6 7 -1\n 1 3 -1 [-3 5 3] 6 7 3\n 1 3 -1 -3 [5 3 6] 7 5\n 1 3 -1 -3 5 [3 6 7] 6\n\n\n
\u56e0\u6b64\uff0c\u8fd4\u56de\u8be5\u6ed1\u52a8\u7a97\u53e3\u7684\u4e2d\u4f4d\u6570\u6570\u7ec4 [1,-1,-1,3,5,6]\u3002
\u63d0\u793a\uff1a
\n\u5047\u8bbek\u662f\u5408\u6cd5\u7684\uff0c\u5373\uff1ak \u59cb\u7ec8\u5c0f\u4e8e\u8f93\u5165\u7684\u975e\u7a7a\u6570\u7ec4\u7684\u5143\u7d20\u4e2a\u6570.
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
Example 1:
\n\n\nInput: num1 = "2", num2 = "3"\nOutput: "6"\n\n
Example 2:
\n\n\nInput: num1 = "123", num2 = "456"\nOutput: "56088"\n\n\n
Note:
\n\nnum1 and num2 is < 110.num1 and num2 contain only digits 0-9.num1 and num2 do not contain any leading zero, except the number 0 itself.\u7ed9\u5b9a\u4e24\u4e2a\u4ee5\u5b57\u7b26\u4e32\u5f62\u5f0f\u8868\u793a\u7684\u975e\u8d1f\u6574\u6570 num1 \u548c num2\uff0c\u8fd4\u56de num1 \u548c num2 \u7684\u4e58\u79ef\uff0c\u5b83\u4eec\u7684\u4e58\u79ef\u4e5f\u8868\u793a\u4e3a\u5b57\u7b26\u4e32\u5f62\u5f0f\u3002
\u793a\u4f8b 1:
\n\n\u8f93\u5165: num1 = "2", num2 = "3"\n\u8f93\u51fa: "6"\n\n
\u793a\u4f8b 2:
\n\n\u8f93\u5165: num1 = "123", num2 = "456"\n\u8f93\u51fa: "56088"\n\n
\u8bf4\u660e\uff1a
\n\nnum1 \u548c num2 \u7684\u957f\u5ea6\u5c0f\u4e8e110\u3002num1 \u548c num2 \u53ea\u5305\u542b\u6570\u5b57 0-9\u3002num1 \u548c num2 \u5747\u4e0d\u4ee5\u96f6\u5f00\u5934\uff0c\u9664\u975e\u662f\u6570\u5b57 0 \u672c\u8eab\u3002\u7ed9\u5b9a\u4e24\u4e2a\u4ee5\u5b57\u7b26\u4e32\u5f62\u5f0f\u8868\u793a\u7684\u975e\u8d1f\u6574\u6570 num1 \u548c num2\uff0c\u8fd4\u56de num1 \u548c num2 \u7684\u4e58\u79ef\uff0c\u5b83\u4eec\u7684\u4e58\u79ef\u4e5f\u8868\u793a\u4e3a\u5b57\u7b26\u4e32\u5f62\u5f0f\u3002
\u793a\u4f8b 1:
\n\n\u8f93\u5165: num1 = "2", num2 = "3"\n\u8f93\u51fa: "6"\n\n
\u793a\u4f8b 2:
\n\n\u8f93\u5165: num1 = "123", num2 = "456"\n\u8f93\u51fa: "56088"\n\n
\u8bf4\u660e\uff1a
\n\nnum1 \u548c num2 \u7684\u957f\u5ea6\u5c0f\u4e8e110\u3002num1 \u548c num2 \u53ea\u5305\u542b\u6570\u5b57 0-9\u3002num1 \u548c num2 \u5747\u4e0d\u4ee5\u96f6\u5f00\u5934\uff0c\u9664\u975e\u662f\u6570\u5b57 0 \u672c\u8eab\u3002